X86: Turn fp selects into mask operations.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
18 #include "X86.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
62                                 SelectionDAG &DAG, SDLoc dl,
63                                 unsigned vectorWidth) {
64   assert((vectorWidth == 128 || vectorWidth == 256) &&
65          "Unsupported vector width");
66   EVT VT = Vec.getValueType();
67   EVT ElVT = VT.getVectorElementType();
68   unsigned Factor = VT.getSizeInBits()/vectorWidth;
69   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
70                                   VT.getVectorNumElements()/Factor);
71
72   // Extract from UNDEF is UNDEF.
73   if (Vec.getOpcode() == ISD::UNDEF)
74     return DAG.getUNDEF(ResultVT);
75
76   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
77   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
78
79   // This is the index of the first element of the vectorWidth-bit chunk
80   // we want.
81   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
82                                * ElemsPerChunk);
83
84   // If the input is a buildvector just emit a smaller one.
85   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
86     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
87                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
88
89   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
90   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
91                                VecIdx);
92
93   return Result;
94   
95 }
96 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
99 /// instructions or a simple subregister reference. Idx is an index in the
100 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
101 /// lowering EXTRACT_VECTOR_ELT operations easier.
102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
103                                    SelectionDAG &DAG, SDLoc dl) {
104   assert((Vec.getValueType().is256BitVector() ||
105           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
106   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
107 }
108
109 /// Generate a DAG to grab 256-bits from a 512-bit vector.
110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
111                                    SelectionDAG &DAG, SDLoc dl) {
112   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
113   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
114 }
115
116 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
117                                unsigned IdxVal, SelectionDAG &DAG,
118                                SDLoc dl, unsigned vectorWidth) {
119   assert((vectorWidth == 128 || vectorWidth == 256) &&
120          "Unsupported vector width");
121   // Inserting UNDEF is Result
122   if (Vec.getOpcode() == ISD::UNDEF)
123     return Result;
124   EVT VT = Vec.getValueType();
125   EVT ElVT = VT.getVectorElementType();
126   EVT ResultVT = Result.getValueType();
127
128   // Insert the relevant vectorWidth bits.
129   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
130
131   // This is the index of the first element of the vectorWidth-bit chunk
132   // we want.
133   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
134                                * ElemsPerChunk);
135
136   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
137   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
138                      VecIdx);
139 }
140 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
143 /// simple superregister reference.  Idx is an index in the 128 bits
144 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
145 /// lowering INSERT_VECTOR_ELT operations easier.
146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
147                                   unsigned IdxVal, SelectionDAG &DAG,
148                                   SDLoc dl) {
149   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
150   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
151 }
152
153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
154                                   unsigned IdxVal, SelectionDAG &DAG,
155                                   SDLoc dl) {
156   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
157   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
158 }
159
160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
161 /// instructions. This is used because creating CONCAT_VECTOR nodes of
162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
163 /// large BUILD_VECTORS.
164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
165                                    unsigned NumElems, SelectionDAG &DAG,
166                                    SDLoc dl) {
167   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
168   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
169 }
170
171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
172                                    unsigned NumElems, SelectionDAG &DAG,
173                                    SDLoc dl) {
174   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
175   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
176 }
177
178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
179   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
180   bool is64Bit = Subtarget->is64Bit();
181
182   if (Subtarget->isTargetEnvMacho()) {
183     if (is64Bit)
184       return new X86_64MachoTargetObjectFile();
185     return new TargetLoweringObjectFileMachO();
186   }
187
188   if (Subtarget->isTargetLinux())
189     return new X86LinuxTargetObjectFile();
190   if (Subtarget->isTargetELF())
191     return new TargetLoweringObjectFileELF();
192   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
193     return new TargetLoweringObjectFileCOFF();
194   llvm_unreachable("unknown subtarget type");
195 }
196
197 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
198   : TargetLowering(TM, createTLOF(TM)) {
199   Subtarget = &TM.getSubtarget<X86Subtarget>();
200   X86ScalarSSEf64 = Subtarget->hasSSE2();
201   X86ScalarSSEf32 = Subtarget->hasSSE1();
202   TD = getDataLayout();
203
204   resetOperationActions();
205 }
206
207 void X86TargetLowering::resetOperationActions() {
208   const TargetMachine &TM = getTargetMachine();
209   static bool FirstTimeThrough = true;
210
211   // If none of the target options have changed, then we don't need to reset the
212   // operation actions.
213   if (!FirstTimeThrough && TO == TM.Options) return;
214
215   if (!FirstTimeThrough) {
216     // Reinitialize the actions.
217     initActions();
218     FirstTimeThrough = false;
219   }
220
221   TO = TM.Options;
222
223   // Set up the TargetLowering object.
224   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
225
226   // X86 is weird, it always uses i8 for shift amounts and setcc results.
227   setBooleanContents(ZeroOrOneBooleanContent);
228   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
229   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
230
231   // For 64-bit since we have so many registers use the ILP scheduler, for
232   // 32-bit code use the register pressure specific scheduling.
233   // For Atom, always use ILP scheduling.
234   if (Subtarget->isAtom())
235     setSchedulingPreference(Sched::ILP);
236   else if (Subtarget->is64Bit())
237     setSchedulingPreference(Sched::ILP);
238   else
239     setSchedulingPreference(Sched::RegPressure);
240   const X86RegisterInfo *RegInfo =
241     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
242   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
243
244   // Bypass expensive divides on Atom when compiling with O2
245   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
246     addBypassSlowDiv(32, 8);
247     if (Subtarget->is64Bit())
248       addBypassSlowDiv(64, 16);
249   }
250
251   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
252     // Setup Windows compiler runtime calls.
253     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
254     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
255     setLibcallName(RTLIB::SREM_I64, "_allrem");
256     setLibcallName(RTLIB::UREM_I64, "_aullrem");
257     setLibcallName(RTLIB::MUL_I64, "_allmul");
258     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
259     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
260     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
263
264     // The _ftol2 runtime function has an unusual calling conv, which
265     // is modeled by a special pseudo-instruction.
266     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
267     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
268     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
269     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
270   }
271
272   if (Subtarget->isTargetDarwin()) {
273     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
274     setUseUnderscoreSetJmp(false);
275     setUseUnderscoreLongJmp(false);
276   } else if (Subtarget->isTargetMingw()) {
277     // MS runtime is weird: it exports _setjmp, but longjmp!
278     setUseUnderscoreSetJmp(true);
279     setUseUnderscoreLongJmp(false);
280   } else {
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(true);
283   }
284
285   // Set up the register classes.
286   addRegisterClass(MVT::i8, &X86::GR8RegClass);
287   addRegisterClass(MVT::i16, &X86::GR16RegClass);
288   addRegisterClass(MVT::i32, &X86::GR32RegClass);
289   if (Subtarget->is64Bit())
290     addRegisterClass(MVT::i64, &X86::GR64RegClass);
291
292   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
293
294   // We don't accept any truncstore of integer registers.
295   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
296   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
297   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
298   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
299   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
300   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
301
302   // SETOEQ and SETUNE require checking two conditions.
303   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
304   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
305   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
306   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
307   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
309
310   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
311   // operation.
312   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
313   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
315
316   if (Subtarget->is64Bit()) {
317     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
318     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
319   } else if (!TM.Options.UseSoftFloat) {
320     // We have an algorithm for SSE2->double, and we turn this into a
321     // 64-bit FILD followed by conditional FADD for other targets.
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
323     // We have an algorithm for SSE2, and we turn this into a 64-bit
324     // FILD for other targets.
325     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
326   }
327
328   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
329   // this operation.
330   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
331   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
332
333   if (!TM.Options.UseSoftFloat) {
334     // SSE has no i16 to fp conversion, only i32
335     if (X86ScalarSSEf32) {
336       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
337       // f32 and f64 cases are Legal, f80 case is not
338       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
339     } else {
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
342     }
343   } else {
344     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
345     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
346   }
347
348   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
349   // are Legal, f80 is custom lowered.
350   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
351   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
352
353   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
354   // this operation.
355   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
356   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
357
358   if (X86ScalarSSEf32) {
359     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
360     // f32 and f64 cases are Legal, f80 case is not
361     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
362   } else {
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
365   }
366
367   // Handle FP_TO_UINT by promoting the destination to a larger signed
368   // conversion.
369   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
370   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
372
373   if (Subtarget->is64Bit()) {
374     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
375     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
376   } else if (!TM.Options.UseSoftFloat) {
377     // Since AVX is a superset of SSE3, only check for SSE here.
378     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
379       // Expand FP_TO_UINT into a select.
380       // FIXME: We would like to use a Custom expander here eventually to do
381       // the optimal thing for SSE vs. the default expansion in the legalizer.
382       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
383     else
384       // With SSE3 we can use fisttpll to convert to a signed i64; without
385       // SSE, we're stuck with a fistpll.
386       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
387   }
388
389   if (isTargetFTOL()) {
390     // Use the _ftol2 runtime function, which has a pseudo-instruction
391     // to handle its weird calling convention.
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
393   }
394
395   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
396   if (!X86ScalarSSEf64) {
397     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
398     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
399     if (Subtarget->is64Bit()) {
400       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
401       // Without SSE, i64->f64 goes through memory.
402       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
403     }
404   }
405
406   // Scalar integer divide and remainder are lowered to use operations that
407   // produce two results, to match the available instructions. This exposes
408   // the two-result form to trivial CSE, which is able to combine x/y and x%y
409   // into a single instruction.
410   //
411   // Scalar integer multiply-high is also lowered to use two-result
412   // operations, to match the available instructions. However, plain multiply
413   // (low) operations are left as Legal, as there are single-result
414   // instructions for this in x86. Using the two-result multiply instructions
415   // when both high and low results are needed must be arranged by dagcombine.
416   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
417     MVT VT = IntVTs[i];
418     setOperationAction(ISD::MULHS, VT, Expand);
419     setOperationAction(ISD::MULHU, VT, Expand);
420     setOperationAction(ISD::SDIV, VT, Expand);
421     setOperationAction(ISD::UDIV, VT, Expand);
422     setOperationAction(ISD::SREM, VT, Expand);
423     setOperationAction(ISD::UREM, VT, Expand);
424
425     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
426     setOperationAction(ISD::ADDC, VT, Custom);
427     setOperationAction(ISD::ADDE, VT, Custom);
428     setOperationAction(ISD::SUBC, VT, Custom);
429     setOperationAction(ISD::SUBE, VT, Custom);
430   }
431
432   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
433   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
434   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
435   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
436   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
438   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
441   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
442   if (Subtarget->is64Bit())
443     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
444   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
445   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
447   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
448   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
449   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
450   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
451   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
452
453   // Promote the i8 variants and force them on up to i32 which has a shorter
454   // encoding.
455   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
456   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
457   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
458   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
459   if (Subtarget->hasBMI()) {
460     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
461     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
462     if (Subtarget->is64Bit())
463       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
464   } else {
465     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
466     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
467     if (Subtarget->is64Bit())
468       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
469   }
470
471   if (Subtarget->hasLZCNT()) {
472     // When promoting the i8 variants, force them to i32 for a shorter
473     // encoding.
474     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
475     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
476     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
477     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
478     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
479     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
480     if (Subtarget->is64Bit())
481       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
482   } else {
483     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
484     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
485     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
486     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
487     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
489     if (Subtarget->is64Bit()) {
490       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
491       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
492     }
493   }
494
495   if (Subtarget->hasPOPCNT()) {
496     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
497   } else {
498     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
499     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
500     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
501     if (Subtarget->is64Bit())
502       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
503   }
504
505   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
506   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
507
508   // These should be promoted to a larger select which is supported.
509   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
510   // X86 wants to expand cmov itself.
511   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
512   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
513   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
514   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
515   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
516   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
517   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
518   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
519   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
520   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
523   if (Subtarget->is64Bit()) {
524     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
525     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
526   }
527   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
528   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
529   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
530   // support continuation, user-level threading, and etc.. As a result, no
531   // other SjLj exception interfaces are implemented and please don't build
532   // your own exception handling based on them.
533   // LLVM/Clang supports zero-cost DWARF exception handling.
534   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
535   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
536
537   // Darwin ABI issue.
538   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
539   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
540   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
541   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
542   if (Subtarget->is64Bit())
543     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
544   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
545   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
546   if (Subtarget->is64Bit()) {
547     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
548     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
549     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
550     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
551     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
552   }
553   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
554   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
555   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
556   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
557   if (Subtarget->is64Bit()) {
558     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
559     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
560     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
561   }
562
563   if (Subtarget->hasSSE1())
564     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
565
566   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
567
568   // Expand certain atomics
569   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
570     MVT VT = IntVTs[i];
571     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
572     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
573     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
574   }
575
576   if (!Subtarget->is64Bit()) {
577     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
578     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
579     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
580     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
581     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
589   }
590
591   if (Subtarget->hasCmpxchg16b()) {
592     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
593   }
594
595   // FIXME - use subtarget debug flags
596   if (!Subtarget->isTargetDarwin() &&
597       !Subtarget->isTargetELF() &&
598       !Subtarget->isTargetCygMing()) {
599     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
600   }
601
602   if (Subtarget->is64Bit()) {
603     setExceptionPointerRegister(X86::RAX);
604     setExceptionSelectorRegister(X86::RDX);
605   } else {
606     setExceptionPointerRegister(X86::EAX);
607     setExceptionSelectorRegister(X86::EDX);
608   }
609   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
610   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
611
612   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
613   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
614
615   setOperationAction(ISD::TRAP, MVT::Other, Legal);
616   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
617
618   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
619   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
620   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
621   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
622     // TargetInfo::X86_64ABIBuiltinVaList
623     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
624     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
625   } else {
626     // TargetInfo::CharPtrBuiltinVaList
627     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
628     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
629   }
630
631   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
632   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
633
634   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
635     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
636                        MVT::i64 : MVT::i32, Custom);
637   else if (TM.Options.EnableSegmentedStacks)
638     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639                        MVT::i64 : MVT::i32, Custom);
640   else
641     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642                        MVT::i64 : MVT::i32, Expand);
643
644   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
645     // f32 and f64 use SSE.
646     // Set up the FP register classes.
647     addRegisterClass(MVT::f32, &X86::FR32RegClass);
648     addRegisterClass(MVT::f64, &X86::FR64RegClass);
649
650     // Use ANDPD to simulate FABS.
651     setOperationAction(ISD::FABS , MVT::f64, Custom);
652     setOperationAction(ISD::FABS , MVT::f32, Custom);
653
654     // Use XORP to simulate FNEG.
655     setOperationAction(ISD::FNEG , MVT::f64, Custom);
656     setOperationAction(ISD::FNEG , MVT::f32, Custom);
657
658     // Use ANDPD and ORPD to simulate FCOPYSIGN.
659     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
660     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
661
662     // Lower this to FGETSIGNx86 plus an AND.
663     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
664     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
665
666     // We don't support sin/cos/fmod
667     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
668     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
669     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
670     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
671     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
672     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
673
674     // Expand FP immediates into loads from the stack, except for the special
675     // cases we handle.
676     addLegalFPImmediate(APFloat(+0.0)); // xorpd
677     addLegalFPImmediate(APFloat(+0.0f)); // xorps
678   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
679     // Use SSE for f32, x87 for f64.
680     // Set up the FP register classes.
681     addRegisterClass(MVT::f32, &X86::FR32RegClass);
682     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
683
684     // Use ANDPS to simulate FABS.
685     setOperationAction(ISD::FABS , MVT::f32, Custom);
686
687     // Use XORP to simulate FNEG.
688     setOperationAction(ISD::FNEG , MVT::f32, Custom);
689
690     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
691
692     // Use ANDPS and ORPS to simulate FCOPYSIGN.
693     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
695
696     // We don't support sin/cos/fmod
697     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
698     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
699     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
700
701     // Special cases we handle for FP constants.
702     addLegalFPImmediate(APFloat(+0.0f)); // xorps
703     addLegalFPImmediate(APFloat(+0.0)); // FLD0
704     addLegalFPImmediate(APFloat(+1.0)); // FLD1
705     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
706     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
707
708     if (!TM.Options.UnsafeFPMath) {
709       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
710       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
711       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
712     }
713   } else if (!TM.Options.UseSoftFloat) {
714     // f32 and f64 in x87.
715     // Set up the FP register classes.
716     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
717     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
718
719     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
720     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
721     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
722     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
723
724     if (!TM.Options.UnsafeFPMath) {
725       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
726       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
727       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
728       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
729       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
730       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
731     }
732     addLegalFPImmediate(APFloat(+0.0)); // FLD0
733     addLegalFPImmediate(APFloat(+1.0)); // FLD1
734     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
735     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
736     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
737     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
738     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
739     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
740   }
741
742   // We don't support FMA.
743   setOperationAction(ISD::FMA, MVT::f64, Expand);
744   setOperationAction(ISD::FMA, MVT::f32, Expand);
745
746   // Long double always uses X87.
747   if (!TM.Options.UseSoftFloat) {
748     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
749     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
750     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
751     {
752       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
753       addLegalFPImmediate(TmpFlt);  // FLD0
754       TmpFlt.changeSign();
755       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
756
757       bool ignored;
758       APFloat TmpFlt2(+1.0);
759       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
760                       &ignored);
761       addLegalFPImmediate(TmpFlt2);  // FLD1
762       TmpFlt2.changeSign();
763       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
764     }
765
766     if (!TM.Options.UnsafeFPMath) {
767       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
768       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
769       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
770     }
771
772     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
773     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
774     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
775     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
776     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
777     setOperationAction(ISD::FMA, MVT::f80, Expand);
778   }
779
780   // Always use a library call for pow.
781   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
782   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
783   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
784
785   setOperationAction(ISD::FLOG, MVT::f80, Expand);
786   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
787   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
788   setOperationAction(ISD::FEXP, MVT::f80, Expand);
789   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
790
791   // First set operation action for all vector types to either promote
792   // (for widening) or expand (for scalarization). Then we will selectively
793   // turn on ones that can be effectively codegen'd.
794   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
795            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
796     MVT VT = (MVT::SimpleValueType)i;
797     setOperationAction(ISD::ADD , VT, Expand);
798     setOperationAction(ISD::SUB , VT, Expand);
799     setOperationAction(ISD::FADD, VT, Expand);
800     setOperationAction(ISD::FNEG, VT, Expand);
801     setOperationAction(ISD::FSUB, VT, Expand);
802     setOperationAction(ISD::MUL , VT, Expand);
803     setOperationAction(ISD::FMUL, VT, Expand);
804     setOperationAction(ISD::SDIV, VT, Expand);
805     setOperationAction(ISD::UDIV, VT, Expand);
806     setOperationAction(ISD::FDIV, VT, Expand);
807     setOperationAction(ISD::SREM, VT, Expand);
808     setOperationAction(ISD::UREM, VT, Expand);
809     setOperationAction(ISD::LOAD, VT, Expand);
810     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
811     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
812     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
813     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
814     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
815     setOperationAction(ISD::FABS, VT, Expand);
816     setOperationAction(ISD::FSIN, VT, Expand);
817     setOperationAction(ISD::FSINCOS, VT, Expand);
818     setOperationAction(ISD::FCOS, VT, Expand);
819     setOperationAction(ISD::FSINCOS, VT, Expand);
820     setOperationAction(ISD::FREM, VT, Expand);
821     setOperationAction(ISD::FMA,  VT, Expand);
822     setOperationAction(ISD::FPOWI, VT, Expand);
823     setOperationAction(ISD::FSQRT, VT, Expand);
824     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
825     setOperationAction(ISD::FFLOOR, VT, Expand);
826     setOperationAction(ISD::FCEIL, VT, Expand);
827     setOperationAction(ISD::FTRUNC, VT, Expand);
828     setOperationAction(ISD::FRINT, VT, Expand);
829     setOperationAction(ISD::FNEARBYINT, VT, Expand);
830     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
831     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
832     setOperationAction(ISD::SDIVREM, VT, Expand);
833     setOperationAction(ISD::UDIVREM, VT, Expand);
834     setOperationAction(ISD::FPOW, VT, Expand);
835     setOperationAction(ISD::CTPOP, VT, Expand);
836     setOperationAction(ISD::CTTZ, VT, Expand);
837     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838     setOperationAction(ISD::CTLZ, VT, Expand);
839     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840     setOperationAction(ISD::SHL, VT, Expand);
841     setOperationAction(ISD::SRA, VT, Expand);
842     setOperationAction(ISD::SRL, VT, Expand);
843     setOperationAction(ISD::ROTL, VT, Expand);
844     setOperationAction(ISD::ROTR, VT, Expand);
845     setOperationAction(ISD::BSWAP, VT, Expand);
846     setOperationAction(ISD::SETCC, VT, Expand);
847     setOperationAction(ISD::FLOG, VT, Expand);
848     setOperationAction(ISD::FLOG2, VT, Expand);
849     setOperationAction(ISD::FLOG10, VT, Expand);
850     setOperationAction(ISD::FEXP, VT, Expand);
851     setOperationAction(ISD::FEXP2, VT, Expand);
852     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857     setOperationAction(ISD::TRUNCATE, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861     setOperationAction(ISD::VSELECT, VT, Expand);
862     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864       setTruncStoreAction(VT,
865                           (MVT::SimpleValueType)InnerVT, Expand);
866     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
869   }
870
871   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872   // with -msoft-float, disable use of MMX as well.
873   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875     // No operations on x86mmx supported, everything uses intrinsics.
876   }
877
878   // MMX-sized vectors (other than x86mmx) are expected to be expanded
879   // into smaller operations.
880   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
881   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
882   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
883   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
884   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
885   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
886   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
887   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
888   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
889   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
890   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
891   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
892   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
893   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
894   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
895   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
900   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
901   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
902   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
904   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
909
910   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
912
913     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
918     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
919     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
920     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
921     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
922     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
923     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
925   }
926
927   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
929
930     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931     // registers cannot be used even for integer operations.
932     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
936
937     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
938     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
939     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
940     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
941     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
942     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
943     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
944     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
945     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
946     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
947     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
948     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
949     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
953     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
954     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
955
956     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
957     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
958     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
959     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
960
961     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
962     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
966
967     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
968     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
969       MVT VT = (MVT::SimpleValueType)i;
970       // Do not attempt to custom lower non-power-of-2 vectors
971       if (!isPowerOf2_32(VT.getVectorNumElements()))
972         continue;
973       // Do not attempt to custom lower non-128-bit vectors
974       if (!VT.is128BitVector())
975         continue;
976       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
977       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
978       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
979     }
980
981     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
982     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
983     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
984     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
985     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
986     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
987
988     if (Subtarget->is64Bit()) {
989       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
990       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
991     }
992
993     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
994     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
995       MVT VT = (MVT::SimpleValueType)i;
996
997       // Do not attempt to promote non-128-bit vectors
998       if (!VT.is128BitVector())
999         continue;
1000
1001       setOperationAction(ISD::AND,    VT, Promote);
1002       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1003       setOperationAction(ISD::OR,     VT, Promote);
1004       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1005       setOperationAction(ISD::XOR,    VT, Promote);
1006       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1007       setOperationAction(ISD::LOAD,   VT, Promote);
1008       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1009       setOperationAction(ISD::SELECT, VT, Promote);
1010       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1011     }
1012
1013     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1014
1015     // Custom lower v2i64 and v2f64 selects.
1016     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1017     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1018     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1019     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1020
1021     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1022     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1023
1024     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1025     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1026     // As there is no 64-bit GPR available, we need build a special custom
1027     // sequence to convert from v2i32 to v2f32.
1028     if (!Subtarget->is64Bit())
1029       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1030
1031     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1032     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1033
1034     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1035   }
1036
1037   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1038     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1039     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1040     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1041     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1042     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1043     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1044     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1045     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1046     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1047     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1048
1049     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1050     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1051     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1052     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1053     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1054     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1055     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1056     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1057     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1058     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1059
1060     // FIXME: Do we need to handle scalar-to-vector here?
1061     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1062
1063     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1064     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1065     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1066     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1067     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1068
1069     // i8 and i16 vectors are custom , because the source register and source
1070     // source memory operand types are not the same width.  f32 vectors are
1071     // custom since the immediate controlling the insert encodes additional
1072     // information.
1073     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1074     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1075     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1076     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1077
1078     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1079     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1080     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1081     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1082
1083     // FIXME: these should be Legal but thats only for the case where
1084     // the index is constant.  For now custom expand to deal with that.
1085     if (Subtarget->is64Bit()) {
1086       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1087       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1088     }
1089   }
1090
1091   if (Subtarget->hasSSE2()) {
1092     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1093     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1094
1095     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1096     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1097
1098     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1099     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1100
1101     // In the customized shift lowering, the legal cases in AVX2 will be
1102     // recognized.
1103     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1104     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1105
1106     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1107     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1108
1109     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1110
1111     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1112     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1113   }
1114
1115   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1116     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1117     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1118     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1119     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1120     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1122
1123     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1124     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1125     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1126
1127     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1128     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1130     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1132     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1133     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1134     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1135     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1136     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1137     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1138     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1139
1140     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1141     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1142     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1143     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1144     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1145     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1146     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1147     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1148     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1149     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1150     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1151     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1152
1153     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1154     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1155
1156     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1157
1158     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1159     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1160     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1161     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1162
1163     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1164     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1165     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1166
1167     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1168
1169     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1170     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1171
1172     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1173     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1174
1175     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1176     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1177
1178     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1179
1180     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1181     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1182     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1183     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1184
1185     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1186     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1187     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1188
1189     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1190     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1191     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1192     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1193
1194     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1195     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1197     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1200
1201     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1202       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1203       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1204       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1205       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1206       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1207       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1208     }
1209
1210     if (Subtarget->hasInt256()) {
1211       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1212       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1213       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1214       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1215
1216       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1217       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1218       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1219       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1220
1221       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1222       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1223       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1224       // Don't lower v32i8 because there is no 128-bit byte mul
1225
1226       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1227
1228       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1229     } else {
1230       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1231       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1232       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1233       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1234
1235       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1236       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1237       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1238       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1239
1240       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1241       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1242       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1243       // Don't lower v32i8 because there is no 128-bit byte mul
1244     }
1245
1246     // In the customized shift lowering, the legal cases in AVX2 will be
1247     // recognized.
1248     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1249     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1250
1251     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1252     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1253
1254     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1255
1256     // Custom lower several nodes for 256-bit types.
1257     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1258              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1259       MVT VT = (MVT::SimpleValueType)i;
1260
1261       // Extract subvector is special because the value type
1262       // (result) is 128-bit but the source is 256-bit wide.
1263       if (VT.is128BitVector())
1264         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1265
1266       // Do not attempt to custom lower other non-256-bit vectors
1267       if (!VT.is256BitVector())
1268         continue;
1269
1270       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1271       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1272       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1273       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1274       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1275       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1276       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1277     }
1278
1279     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1280     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1281       MVT VT = (MVT::SimpleValueType)i;
1282
1283       // Do not attempt to promote non-256-bit vectors
1284       if (!VT.is256BitVector())
1285         continue;
1286
1287       setOperationAction(ISD::AND,    VT, Promote);
1288       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1289       setOperationAction(ISD::OR,     VT, Promote);
1290       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1291       setOperationAction(ISD::XOR,    VT, Promote);
1292       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1293       setOperationAction(ISD::LOAD,   VT, Promote);
1294       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1295       setOperationAction(ISD::SELECT, VT, Promote);
1296       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1297     }
1298   }
1299
1300   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1301     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1302     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1303     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1304     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1305
1306     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1307     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1308
1309     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1310     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1312     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1313     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1314     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1315
1316     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1317     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1319     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1320     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1321     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1322
1323     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1324     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1325     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1326     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1327     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1328     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1329     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1330     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1331     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1332
1333
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1338     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1340     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1341     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1342
1343     setOperationAction(ISD::TRUNCATE,           MVT::i1, Legal);
1344     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1345     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1346     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1347     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1348     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1349     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1350     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1351     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1352     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1353     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1354     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1355
1356     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1357     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1358     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1359     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1360     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1361
1362     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1363     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1364
1365     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1366
1367     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1368     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1369     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1370     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1371     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1372
1373     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1374     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1375
1376     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1377     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1378
1379     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1380
1381     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1382     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1383
1384     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1385     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1386
1387     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1388     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1389
1390     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1391     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1392     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1393
1394     // Custom lower several nodes.
1395     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1396              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1397       MVT VT = (MVT::SimpleValueType)i;
1398
1399       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1400       // Extract subvector is special because the value type
1401       // (result) is 256/128-bit but the source is 512-bit wide.
1402       if (VT.is128BitVector() || VT.is256BitVector())
1403         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1404
1405       if (VT.getVectorElementType() == MVT::i1)
1406         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1407
1408       // Do not attempt to custom lower other non-512-bit vectors
1409       if (!VT.is512BitVector())
1410         continue;
1411
1412       if (VT != MVT::v8i64) {
1413         setOperationAction(ISD::XOR,   VT, Promote);
1414         AddPromotedToType (ISD::XOR,   VT, MVT::v8i64);
1415         setOperationAction(ISD::OR,    VT, Promote);
1416         AddPromotedToType (ISD::OR,    VT, MVT::v8i64);
1417         setOperationAction(ISD::AND,   VT, Promote);
1418         AddPromotedToType (ISD::AND,   VT, MVT::v8i64);
1419       }
1420       if ( EltSize >= 32) {
1421         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1422         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1423         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1424         setOperationAction(ISD::VSELECT,             VT, Legal);
1425         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1426         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1427         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1428       }
1429     }
1430     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1431       MVT VT = (MVT::SimpleValueType)i;
1432
1433       // Do not attempt to promote non-256-bit vectors
1434       if (!VT.is512BitVector())
1435         continue;
1436
1437       setOperationAction(ISD::LOAD,   VT, Promote);
1438       AddPromotedToType (ISD::LOAD,   VT, MVT::v8i64);
1439       setOperationAction(ISD::SELECT, VT, Promote);
1440       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1441     }
1442   }// has  AVX-512
1443
1444   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1445   // of this type with custom code.
1446   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1447            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1448     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1449                        Custom);
1450   }
1451
1452   // We want to custom lower some of our intrinsics.
1453   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1454   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1455
1456   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1457   // handle type legalization for these operations here.
1458   //
1459   // FIXME: We really should do custom legalization for addition and
1460   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1461   // than generic legalization for 64-bit multiplication-with-overflow, though.
1462   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1463     // Add/Sub/Mul with overflow operations are custom lowered.
1464     MVT VT = IntVTs[i];
1465     setOperationAction(ISD::SADDO, VT, Custom);
1466     setOperationAction(ISD::UADDO, VT, Custom);
1467     setOperationAction(ISD::SSUBO, VT, Custom);
1468     setOperationAction(ISD::USUBO, VT, Custom);
1469     setOperationAction(ISD::SMULO, VT, Custom);
1470     setOperationAction(ISD::UMULO, VT, Custom);
1471   }
1472
1473   // There are no 8-bit 3-address imul/mul instructions
1474   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1475   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1476
1477   if (!Subtarget->is64Bit()) {
1478     // These libcalls are not available in 32-bit.
1479     setLibcallName(RTLIB::SHL_I128, 0);
1480     setLibcallName(RTLIB::SRL_I128, 0);
1481     setLibcallName(RTLIB::SRA_I128, 0);
1482   }
1483
1484   // Combine sin / cos into one node or libcall if possible.
1485   if (Subtarget->hasSinCos()) {
1486     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1487     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1488     if (Subtarget->isTargetDarwin()) {
1489       // For MacOSX, we don't want to the normal expansion of a libcall to
1490       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1491       // traffic.
1492       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1493       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1494     }
1495   }
1496
1497   // We have target-specific dag combine patterns for the following nodes:
1498   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1499   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1500   setTargetDAGCombine(ISD::VSELECT);
1501   setTargetDAGCombine(ISD::SELECT);
1502   setTargetDAGCombine(ISD::SHL);
1503   setTargetDAGCombine(ISD::SRA);
1504   setTargetDAGCombine(ISD::SRL);
1505   setTargetDAGCombine(ISD::OR);
1506   setTargetDAGCombine(ISD::AND);
1507   setTargetDAGCombine(ISD::ADD);
1508   setTargetDAGCombine(ISD::FADD);
1509   setTargetDAGCombine(ISD::FSUB);
1510   setTargetDAGCombine(ISD::FMA);
1511   setTargetDAGCombine(ISD::SUB);
1512   setTargetDAGCombine(ISD::LOAD);
1513   setTargetDAGCombine(ISD::STORE);
1514   setTargetDAGCombine(ISD::ZERO_EXTEND);
1515   setTargetDAGCombine(ISD::ANY_EXTEND);
1516   setTargetDAGCombine(ISD::SIGN_EXTEND);
1517   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1518   setTargetDAGCombine(ISD::TRUNCATE);
1519   setTargetDAGCombine(ISD::SINT_TO_FP);
1520   setTargetDAGCombine(ISD::SETCC);
1521   if (Subtarget->is64Bit())
1522     setTargetDAGCombine(ISD::MUL);
1523   setTargetDAGCombine(ISD::XOR);
1524
1525   computeRegisterProperties();
1526
1527   // On Darwin, -Os means optimize for size without hurting performance,
1528   // do not reduce the limit.
1529   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1530   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1531   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1532   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1533   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1534   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1535   setPrefLoopAlignment(4); // 2^4 bytes.
1536
1537   // Predictable cmov don't hurt on atom because it's in-order.
1538   PredictableSelectIsExpensive = !Subtarget->isAtom();
1539
1540   setPrefFunctionAlignment(4); // 2^4 bytes.
1541 }
1542
1543 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1544   if (!VT.isVector()) return MVT::i8;
1545   return VT.changeVectorElementTypeToInteger();
1546 }
1547
1548 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1549 /// the desired ByVal argument alignment.
1550 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1551   if (MaxAlign == 16)
1552     return;
1553   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1554     if (VTy->getBitWidth() == 128)
1555       MaxAlign = 16;
1556   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1557     unsigned EltAlign = 0;
1558     getMaxByValAlign(ATy->getElementType(), EltAlign);
1559     if (EltAlign > MaxAlign)
1560       MaxAlign = EltAlign;
1561   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1562     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1563       unsigned EltAlign = 0;
1564       getMaxByValAlign(STy->getElementType(i), EltAlign);
1565       if (EltAlign > MaxAlign)
1566         MaxAlign = EltAlign;
1567       if (MaxAlign == 16)
1568         break;
1569     }
1570   }
1571 }
1572
1573 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1574 /// function arguments in the caller parameter area. For X86, aggregates
1575 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1576 /// are at 4-byte boundaries.
1577 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1578   if (Subtarget->is64Bit()) {
1579     // Max of 8 and alignment of type.
1580     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1581     if (TyAlign > 8)
1582       return TyAlign;
1583     return 8;
1584   }
1585
1586   unsigned Align = 4;
1587   if (Subtarget->hasSSE1())
1588     getMaxByValAlign(Ty, Align);
1589   return Align;
1590 }
1591
1592 /// getOptimalMemOpType - Returns the target specific optimal type for load
1593 /// and store operations as a result of memset, memcpy, and memmove
1594 /// lowering. If DstAlign is zero that means it's safe to destination
1595 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1596 /// means there isn't a need to check it against alignment requirement,
1597 /// probably because the source does not need to be loaded. If 'IsMemset' is
1598 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1599 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1600 /// source is constant so it does not need to be loaded.
1601 /// It returns EVT::Other if the type should be determined using generic
1602 /// target-independent logic.
1603 EVT
1604 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1605                                        unsigned DstAlign, unsigned SrcAlign,
1606                                        bool IsMemset, bool ZeroMemset,
1607                                        bool MemcpyStrSrc,
1608                                        MachineFunction &MF) const {
1609   const Function *F = MF.getFunction();
1610   if ((!IsMemset || ZeroMemset) &&
1611       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1612                                        Attribute::NoImplicitFloat)) {
1613     if (Size >= 16 &&
1614         (Subtarget->isUnalignedMemAccessFast() ||
1615          ((DstAlign == 0 || DstAlign >= 16) &&
1616           (SrcAlign == 0 || SrcAlign >= 16)))) {
1617       if (Size >= 32) {
1618         if (Subtarget->hasInt256())
1619           return MVT::v8i32;
1620         if (Subtarget->hasFp256())
1621           return MVT::v8f32;
1622       }
1623       if (Subtarget->hasSSE2())
1624         return MVT::v4i32;
1625       if (Subtarget->hasSSE1())
1626         return MVT::v4f32;
1627     } else if (!MemcpyStrSrc && Size >= 8 &&
1628                !Subtarget->is64Bit() &&
1629                Subtarget->hasSSE2()) {
1630       // Do not use f64 to lower memcpy if source is string constant. It's
1631       // better to use i32 to avoid the loads.
1632       return MVT::f64;
1633     }
1634   }
1635   if (Subtarget->is64Bit() && Size >= 8)
1636     return MVT::i64;
1637   return MVT::i32;
1638 }
1639
1640 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1641   if (VT == MVT::f32)
1642     return X86ScalarSSEf32;
1643   else if (VT == MVT::f64)
1644     return X86ScalarSSEf64;
1645   return true;
1646 }
1647
1648 bool
1649 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1650   if (Fast)
1651     *Fast = Subtarget->isUnalignedMemAccessFast();
1652   return true;
1653 }
1654
1655 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1656 /// current function.  The returned value is a member of the
1657 /// MachineJumpTableInfo::JTEntryKind enum.
1658 unsigned X86TargetLowering::getJumpTableEncoding() const {
1659   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1660   // symbol.
1661   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1662       Subtarget->isPICStyleGOT())
1663     return MachineJumpTableInfo::EK_Custom32;
1664
1665   // Otherwise, use the normal jump table encoding heuristics.
1666   return TargetLowering::getJumpTableEncoding();
1667 }
1668
1669 const MCExpr *
1670 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1671                                              const MachineBasicBlock *MBB,
1672                                              unsigned uid,MCContext &Ctx) const{
1673   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1674          Subtarget->isPICStyleGOT());
1675   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1676   // entries.
1677   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1678                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1679 }
1680
1681 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1682 /// jumptable.
1683 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1684                                                     SelectionDAG &DAG) const {
1685   if (!Subtarget->is64Bit())
1686     // This doesn't have SDLoc associated with it, but is not really the
1687     // same as a Register.
1688     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1689   return Table;
1690 }
1691
1692 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1693 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1694 /// MCExpr.
1695 const MCExpr *X86TargetLowering::
1696 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1697                              MCContext &Ctx) const {
1698   // X86-64 uses RIP relative addressing based on the jump table label.
1699   if (Subtarget->isPICStyleRIPRel())
1700     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1701
1702   // Otherwise, the reference is relative to the PIC base.
1703   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1704 }
1705
1706 // FIXME: Why this routine is here? Move to RegInfo!
1707 std::pair<const TargetRegisterClass*, uint8_t>
1708 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1709   const TargetRegisterClass *RRC = 0;
1710   uint8_t Cost = 1;
1711   switch (VT.SimpleTy) {
1712   default:
1713     return TargetLowering::findRepresentativeClass(VT);
1714   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1715     RRC = Subtarget->is64Bit() ?
1716       (const TargetRegisterClass*)&X86::GR64RegClass :
1717       (const TargetRegisterClass*)&X86::GR32RegClass;
1718     break;
1719   case MVT::x86mmx:
1720     RRC = &X86::VR64RegClass;
1721     break;
1722   case MVT::f32: case MVT::f64:
1723   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1724   case MVT::v4f32: case MVT::v2f64:
1725   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1726   case MVT::v4f64:
1727     RRC = &X86::VR128RegClass;
1728     break;
1729   }
1730   return std::make_pair(RRC, Cost);
1731 }
1732
1733 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1734                                                unsigned &Offset) const {
1735   if (!Subtarget->isTargetLinux())
1736     return false;
1737
1738   if (Subtarget->is64Bit()) {
1739     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1740     Offset = 0x28;
1741     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1742       AddressSpace = 256;
1743     else
1744       AddressSpace = 257;
1745   } else {
1746     // %gs:0x14 on i386
1747     Offset = 0x14;
1748     AddressSpace = 256;
1749   }
1750   return true;
1751 }
1752
1753 //===----------------------------------------------------------------------===//
1754 //               Return Value Calling Convention Implementation
1755 //===----------------------------------------------------------------------===//
1756
1757 #include "X86GenCallingConv.inc"
1758
1759 bool
1760 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1761                                   MachineFunction &MF, bool isVarArg,
1762                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1763                         LLVMContext &Context) const {
1764   SmallVector<CCValAssign, 16> RVLocs;
1765   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1766                  RVLocs, Context);
1767   return CCInfo.CheckReturn(Outs, RetCC_X86);
1768 }
1769
1770 SDValue
1771 X86TargetLowering::LowerReturn(SDValue Chain,
1772                                CallingConv::ID CallConv, bool isVarArg,
1773                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1774                                const SmallVectorImpl<SDValue> &OutVals,
1775                                SDLoc dl, SelectionDAG &DAG) const {
1776   MachineFunction &MF = DAG.getMachineFunction();
1777   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1778
1779   SmallVector<CCValAssign, 16> RVLocs;
1780   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1781                  RVLocs, *DAG.getContext());
1782   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1783
1784   SDValue Flag;
1785   SmallVector<SDValue, 6> RetOps;
1786   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1787   // Operand #1 = Bytes To Pop
1788   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1789                    MVT::i16));
1790
1791   // Copy the result values into the output registers.
1792   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1793     CCValAssign &VA = RVLocs[i];
1794     assert(VA.isRegLoc() && "Can only return in registers!");
1795     SDValue ValToCopy = OutVals[i];
1796     EVT ValVT = ValToCopy.getValueType();
1797
1798     // Promote values to the appropriate types
1799     if (VA.getLocInfo() == CCValAssign::SExt)
1800       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1801     else if (VA.getLocInfo() == CCValAssign::ZExt)
1802       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1803     else if (VA.getLocInfo() == CCValAssign::AExt)
1804       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1805     else if (VA.getLocInfo() == CCValAssign::BCvt)
1806       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1807
1808     // If this is x86-64, and we disabled SSE, we can't return FP values,
1809     // or SSE or MMX vectors.
1810     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1811          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1812           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1813       report_fatal_error("SSE register return with SSE disabled");
1814     }
1815     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1816     // llvm-gcc has never done it right and no one has noticed, so this
1817     // should be OK for now.
1818     if (ValVT == MVT::f64 &&
1819         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1820       report_fatal_error("SSE2 register return with SSE2 disabled");
1821
1822     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1823     // the RET instruction and handled by the FP Stackifier.
1824     if (VA.getLocReg() == X86::ST0 ||
1825         VA.getLocReg() == X86::ST1) {
1826       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1827       // change the value to the FP stack register class.
1828       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1829         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1830       RetOps.push_back(ValToCopy);
1831       // Don't emit a copytoreg.
1832       continue;
1833     }
1834
1835     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1836     // which is returned in RAX / RDX.
1837     if (Subtarget->is64Bit()) {
1838       if (ValVT == MVT::x86mmx) {
1839         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1840           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1841           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1842                                   ValToCopy);
1843           // If we don't have SSE2 available, convert to v4f32 so the generated
1844           // register is legal.
1845           if (!Subtarget->hasSSE2())
1846             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1847         }
1848       }
1849     }
1850
1851     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1852     Flag = Chain.getValue(1);
1853     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1854   }
1855
1856   // The x86-64 ABIs require that for returning structs by value we copy
1857   // the sret argument into %rax/%eax (depending on ABI) for the return.
1858   // Win32 requires us to put the sret argument to %eax as well.
1859   // We saved the argument into a virtual register in the entry block,
1860   // so now we copy the value out and into %rax/%eax.
1861   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1862       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1863     MachineFunction &MF = DAG.getMachineFunction();
1864     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865     unsigned Reg = FuncInfo->getSRetReturnReg();
1866     assert(Reg &&
1867            "SRetReturnReg should have been set in LowerFormalArguments().");
1868     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1869
1870     unsigned RetValReg
1871         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1872           X86::RAX : X86::EAX;
1873     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1874     Flag = Chain.getValue(1);
1875
1876     // RAX/EAX now acts like a return value.
1877     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1878   }
1879
1880   RetOps[0] = Chain;  // Update chain.
1881
1882   // Add the flag if we have it.
1883   if (Flag.getNode())
1884     RetOps.push_back(Flag);
1885
1886   return DAG.getNode(X86ISD::RET_FLAG, dl,
1887                      MVT::Other, &RetOps[0], RetOps.size());
1888 }
1889
1890 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1891   if (N->getNumValues() != 1)
1892     return false;
1893   if (!N->hasNUsesOfValue(1, 0))
1894     return false;
1895
1896   SDValue TCChain = Chain;
1897   SDNode *Copy = *N->use_begin();
1898   if (Copy->getOpcode() == ISD::CopyToReg) {
1899     // If the copy has a glue operand, we conservatively assume it isn't safe to
1900     // perform a tail call.
1901     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1902       return false;
1903     TCChain = Copy->getOperand(0);
1904   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1905     return false;
1906
1907   bool HasRet = false;
1908   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1909        UI != UE; ++UI) {
1910     if (UI->getOpcode() != X86ISD::RET_FLAG)
1911       return false;
1912     HasRet = true;
1913   }
1914
1915   if (!HasRet)
1916     return false;
1917
1918   Chain = TCChain;
1919   return true;
1920 }
1921
1922 MVT
1923 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1924                                             ISD::NodeType ExtendKind) const {
1925   MVT ReturnMVT;
1926   // TODO: Is this also valid on 32-bit?
1927   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1928     ReturnMVT = MVT::i8;
1929   else
1930     ReturnMVT = MVT::i32;
1931
1932   MVT MinVT = getRegisterType(ReturnMVT);
1933   return VT.bitsLT(MinVT) ? MinVT : VT;
1934 }
1935
1936 /// LowerCallResult - Lower the result values of a call into the
1937 /// appropriate copies out of appropriate physical registers.
1938 ///
1939 SDValue
1940 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1941                                    CallingConv::ID CallConv, bool isVarArg,
1942                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1943                                    SDLoc dl, SelectionDAG &DAG,
1944                                    SmallVectorImpl<SDValue> &InVals) const {
1945
1946   // Assign locations to each value returned by this call.
1947   SmallVector<CCValAssign, 16> RVLocs;
1948   bool Is64Bit = Subtarget->is64Bit();
1949   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1950                  getTargetMachine(), RVLocs, *DAG.getContext());
1951   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1952
1953   // Copy all of the result registers out of their specified physreg.
1954   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1955     CCValAssign &VA = RVLocs[i];
1956     EVT CopyVT = VA.getValVT();
1957
1958     // If this is x86-64, and we disabled SSE, we can't return FP values
1959     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1960         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1961       report_fatal_error("SSE register return with SSE disabled");
1962     }
1963
1964     SDValue Val;
1965
1966     // If this is a call to a function that returns an fp value on the floating
1967     // point stack, we must guarantee the value is popped from the stack, so
1968     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1969     // if the return value is not used. We use the FpPOP_RETVAL instruction
1970     // instead.
1971     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1972       // If we prefer to use the value in xmm registers, copy it out as f80 and
1973       // use a truncate to move it from fp stack reg to xmm reg.
1974       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1975       SDValue Ops[] = { Chain, InFlag };
1976       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1977                                          MVT::Other, MVT::Glue, Ops), 1);
1978       Val = Chain.getValue(0);
1979
1980       // Round the f80 to the right size, which also moves it to the appropriate
1981       // xmm register.
1982       if (CopyVT != VA.getValVT())
1983         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1984                           // This truncation won't change the value.
1985                           DAG.getIntPtrConstant(1));
1986     } else {
1987       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1988                                  CopyVT, InFlag).getValue(1);
1989       Val = Chain.getValue(0);
1990     }
1991     InFlag = Chain.getValue(2);
1992     InVals.push_back(Val);
1993   }
1994
1995   return Chain;
1996 }
1997
1998 //===----------------------------------------------------------------------===//
1999 //                C & StdCall & Fast Calling Convention implementation
2000 //===----------------------------------------------------------------------===//
2001 //  StdCall calling convention seems to be standard for many Windows' API
2002 //  routines and around. It differs from C calling convention just a little:
2003 //  callee should clean up the stack, not caller. Symbols should be also
2004 //  decorated in some fancy way :) It doesn't support any vector arguments.
2005 //  For info on fast calling convention see Fast Calling Convention (tail call)
2006 //  implementation LowerX86_32FastCCCallTo.
2007
2008 /// CallIsStructReturn - Determines whether a call uses struct return
2009 /// semantics.
2010 enum StructReturnType {
2011   NotStructReturn,
2012   RegStructReturn,
2013   StackStructReturn
2014 };
2015 static StructReturnType
2016 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2017   if (Outs.empty())
2018     return NotStructReturn;
2019
2020   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2021   if (!Flags.isSRet())
2022     return NotStructReturn;
2023   if (Flags.isInReg())
2024     return RegStructReturn;
2025   return StackStructReturn;
2026 }
2027
2028 /// ArgsAreStructReturn - Determines whether a function uses struct
2029 /// return semantics.
2030 static StructReturnType
2031 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2032   if (Ins.empty())
2033     return NotStructReturn;
2034
2035   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2036   if (!Flags.isSRet())
2037     return NotStructReturn;
2038   if (Flags.isInReg())
2039     return RegStructReturn;
2040   return StackStructReturn;
2041 }
2042
2043 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2044 /// by "Src" to address "Dst" with size and alignment information specified by
2045 /// the specific parameter attribute. The copy will be passed as a byval
2046 /// function parameter.
2047 static SDValue
2048 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2049                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2050                           SDLoc dl) {
2051   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2052
2053   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2054                        /*isVolatile*/false, /*AlwaysInline=*/true,
2055                        MachinePointerInfo(), MachinePointerInfo());
2056 }
2057
2058 /// IsTailCallConvention - Return true if the calling convention is one that
2059 /// supports tail call optimization.
2060 static bool IsTailCallConvention(CallingConv::ID CC) {
2061   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2062           CC == CallingConv::HiPE);
2063 }
2064
2065 /// \brief Return true if the calling convention is a C calling convention.
2066 static bool IsCCallConvention(CallingConv::ID CC) {
2067   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2068           CC == CallingConv::X86_64_SysV);
2069 }
2070
2071 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2072   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2073     return false;
2074
2075   CallSite CS(CI);
2076   CallingConv::ID CalleeCC = CS.getCallingConv();
2077   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2078     return false;
2079
2080   return true;
2081 }
2082
2083 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2084 /// a tailcall target by changing its ABI.
2085 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2086                                    bool GuaranteedTailCallOpt) {
2087   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2088 }
2089
2090 SDValue
2091 X86TargetLowering::LowerMemArgument(SDValue Chain,
2092                                     CallingConv::ID CallConv,
2093                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2094                                     SDLoc dl, SelectionDAG &DAG,
2095                                     const CCValAssign &VA,
2096                                     MachineFrameInfo *MFI,
2097                                     unsigned i) const {
2098   // Create the nodes corresponding to a load from this parameter slot.
2099   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2100   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2101                               getTargetMachine().Options.GuaranteedTailCallOpt);
2102   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2103   EVT ValVT;
2104
2105   // If value is passed by pointer we have address passed instead of the value
2106   // itself.
2107   if (VA.getLocInfo() == CCValAssign::Indirect)
2108     ValVT = VA.getLocVT();
2109   else
2110     ValVT = VA.getValVT();
2111
2112   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2113   // changed with more analysis.
2114   // In case of tail call optimization mark all arguments mutable. Since they
2115   // could be overwritten by lowering of arguments in case of a tail call.
2116   if (Flags.isByVal()) {
2117     unsigned Bytes = Flags.getByValSize();
2118     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2119     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2120     return DAG.getFrameIndex(FI, getPointerTy());
2121   } else {
2122     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2123                                     VA.getLocMemOffset(), isImmutable);
2124     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2125     return DAG.getLoad(ValVT, dl, Chain, FIN,
2126                        MachinePointerInfo::getFixedStack(FI),
2127                        false, false, false, 0);
2128   }
2129 }
2130
2131 SDValue
2132 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2133                                         CallingConv::ID CallConv,
2134                                         bool isVarArg,
2135                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2136                                         SDLoc dl,
2137                                         SelectionDAG &DAG,
2138                                         SmallVectorImpl<SDValue> &InVals)
2139                                           const {
2140   MachineFunction &MF = DAG.getMachineFunction();
2141   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2142
2143   const Function* Fn = MF.getFunction();
2144   if (Fn->hasExternalLinkage() &&
2145       Subtarget->isTargetCygMing() &&
2146       Fn->getName() == "main")
2147     FuncInfo->setForceFramePointer(true);
2148
2149   MachineFrameInfo *MFI = MF.getFrameInfo();
2150   bool Is64Bit = Subtarget->is64Bit();
2151   bool IsWindows = Subtarget->isTargetWindows();
2152   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2153
2154   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2155          "Var args not supported with calling convention fastcc, ghc or hipe");
2156
2157   // Assign locations to all of the incoming arguments.
2158   SmallVector<CCValAssign, 16> ArgLocs;
2159   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2160                  ArgLocs, *DAG.getContext());
2161
2162   // Allocate shadow area for Win64
2163   if (IsWin64)
2164     CCInfo.AllocateStack(32, 8);
2165
2166   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2167
2168   unsigned LastVal = ~0U;
2169   SDValue ArgValue;
2170   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2171     CCValAssign &VA = ArgLocs[i];
2172     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2173     // places.
2174     assert(VA.getValNo() != LastVal &&
2175            "Don't support value assigned to multiple locs yet");
2176     (void)LastVal;
2177     LastVal = VA.getValNo();
2178
2179     if (VA.isRegLoc()) {
2180       EVT RegVT = VA.getLocVT();
2181       const TargetRegisterClass *RC;
2182       if (RegVT == MVT::i32)
2183         RC = &X86::GR32RegClass;
2184       else if (Is64Bit && RegVT == MVT::i64)
2185         RC = &X86::GR64RegClass;
2186       else if (RegVT == MVT::f32)
2187         RC = &X86::FR32RegClass;
2188       else if (RegVT == MVT::f64)
2189         RC = &X86::FR64RegClass;
2190       else if (RegVT.is512BitVector())
2191         RC = &X86::VR512RegClass;
2192       else if (RegVT.is256BitVector())
2193         RC = &X86::VR256RegClass;
2194       else if (RegVT.is128BitVector())
2195         RC = &X86::VR128RegClass;
2196       else if (RegVT == MVT::x86mmx)
2197         RC = &X86::VR64RegClass;
2198       else if (RegVT == MVT::v8i1)
2199         RC = &X86::VK8RegClass;
2200       else if (RegVT == MVT::v16i1)
2201         RC = &X86::VK16RegClass;
2202       else
2203         llvm_unreachable("Unknown argument type!");
2204
2205       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2206       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2207
2208       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2209       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2210       // right size.
2211       if (VA.getLocInfo() == CCValAssign::SExt)
2212         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2213                                DAG.getValueType(VA.getValVT()));
2214       else if (VA.getLocInfo() == CCValAssign::ZExt)
2215         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2216                                DAG.getValueType(VA.getValVT()));
2217       else if (VA.getLocInfo() == CCValAssign::BCvt)
2218         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2219
2220       if (VA.isExtInLoc()) {
2221         // Handle MMX values passed in XMM regs.
2222         if (RegVT.isVector())
2223           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2224         else
2225           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2226       }
2227     } else {
2228       assert(VA.isMemLoc());
2229       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2230     }
2231
2232     // If value is passed via pointer - do a load.
2233     if (VA.getLocInfo() == CCValAssign::Indirect)
2234       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2235                              MachinePointerInfo(), false, false, false, 0);
2236
2237     InVals.push_back(ArgValue);
2238   }
2239
2240   // The x86-64 ABIs require that for returning structs by value we copy
2241   // the sret argument into %rax/%eax (depending on ABI) for the return.
2242   // Win32 requires us to put the sret argument to %eax as well.
2243   // Save the argument into a virtual register so that we can access it
2244   // from the return points.
2245   if (MF.getFunction()->hasStructRetAttr() &&
2246       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2247     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2248     unsigned Reg = FuncInfo->getSRetReturnReg();
2249     if (!Reg) {
2250       MVT PtrTy = getPointerTy();
2251       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2252       FuncInfo->setSRetReturnReg(Reg);
2253     }
2254     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2255     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2256   }
2257
2258   unsigned StackSize = CCInfo.getNextStackOffset();
2259   // Align stack specially for tail calls.
2260   if (FuncIsMadeTailCallSafe(CallConv,
2261                              MF.getTarget().Options.GuaranteedTailCallOpt))
2262     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2263
2264   // If the function takes variable number of arguments, make a frame index for
2265   // the start of the first vararg value... for expansion of llvm.va_start.
2266   if (isVarArg) {
2267     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2268                     CallConv != CallingConv::X86_ThisCall)) {
2269       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2270     }
2271     if (Is64Bit) {
2272       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2273
2274       // FIXME: We should really autogenerate these arrays
2275       static const uint16_t GPR64ArgRegsWin64[] = {
2276         X86::RCX, X86::RDX, X86::R8,  X86::R9
2277       };
2278       static const uint16_t GPR64ArgRegs64Bit[] = {
2279         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2280       };
2281       static const uint16_t XMMArgRegs64Bit[] = {
2282         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2283         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2284       };
2285       const uint16_t *GPR64ArgRegs;
2286       unsigned NumXMMRegs = 0;
2287
2288       if (IsWin64) {
2289         // The XMM registers which might contain var arg parameters are shadowed
2290         // in their paired GPR.  So we only need to save the GPR to their home
2291         // slots.
2292         TotalNumIntRegs = 4;
2293         GPR64ArgRegs = GPR64ArgRegsWin64;
2294       } else {
2295         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2296         GPR64ArgRegs = GPR64ArgRegs64Bit;
2297
2298         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2299                                                 TotalNumXMMRegs);
2300       }
2301       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2302                                                        TotalNumIntRegs);
2303
2304       bool NoImplicitFloatOps = Fn->getAttributes().
2305         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2306       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2307              "SSE register cannot be used when SSE is disabled!");
2308       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2309                NoImplicitFloatOps) &&
2310              "SSE register cannot be used when SSE is disabled!");
2311       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2312           !Subtarget->hasSSE1())
2313         // Kernel mode asks for SSE to be disabled, so don't push them
2314         // on the stack.
2315         TotalNumXMMRegs = 0;
2316
2317       if (IsWin64) {
2318         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2319         // Get to the caller-allocated home save location.  Add 8 to account
2320         // for the return address.
2321         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2322         FuncInfo->setRegSaveFrameIndex(
2323           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2324         // Fixup to set vararg frame on shadow area (4 x i64).
2325         if (NumIntRegs < 4)
2326           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2327       } else {
2328         // For X86-64, if there are vararg parameters that are passed via
2329         // registers, then we must store them to their spots on the stack so
2330         // they may be loaded by deferencing the result of va_next.
2331         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2332         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2333         FuncInfo->setRegSaveFrameIndex(
2334           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2335                                false));
2336       }
2337
2338       // Store the integer parameter registers.
2339       SmallVector<SDValue, 8> MemOps;
2340       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2341                                         getPointerTy());
2342       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2343       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2344         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2345                                   DAG.getIntPtrConstant(Offset));
2346         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2347                                      &X86::GR64RegClass);
2348         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2349         SDValue Store =
2350           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2351                        MachinePointerInfo::getFixedStack(
2352                          FuncInfo->getRegSaveFrameIndex(), Offset),
2353                        false, false, 0);
2354         MemOps.push_back(Store);
2355         Offset += 8;
2356       }
2357
2358       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2359         // Now store the XMM (fp + vector) parameter registers.
2360         SmallVector<SDValue, 11> SaveXMMOps;
2361         SaveXMMOps.push_back(Chain);
2362
2363         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2364         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2365         SaveXMMOps.push_back(ALVal);
2366
2367         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2368                                FuncInfo->getRegSaveFrameIndex()));
2369         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2370                                FuncInfo->getVarArgsFPOffset()));
2371
2372         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2373           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2374                                        &X86::VR128RegClass);
2375           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2376           SaveXMMOps.push_back(Val);
2377         }
2378         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2379                                      MVT::Other,
2380                                      &SaveXMMOps[0], SaveXMMOps.size()));
2381       }
2382
2383       if (!MemOps.empty())
2384         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2385                             &MemOps[0], MemOps.size());
2386     }
2387   }
2388
2389   // Some CCs need callee pop.
2390   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2391                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2392     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2393   } else {
2394     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2395     // If this is an sret function, the return should pop the hidden pointer.
2396     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2397         argsAreStructReturn(Ins) == StackStructReturn)
2398       FuncInfo->setBytesToPopOnReturn(4);
2399   }
2400
2401   if (!Is64Bit) {
2402     // RegSaveFrameIndex is X86-64 only.
2403     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2404     if (CallConv == CallingConv::X86_FastCall ||
2405         CallConv == CallingConv::X86_ThisCall)
2406       // fastcc functions can't have varargs.
2407       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2408   }
2409
2410   FuncInfo->setArgumentStackSize(StackSize);
2411
2412   return Chain;
2413 }
2414
2415 SDValue
2416 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2417                                     SDValue StackPtr, SDValue Arg,
2418                                     SDLoc dl, SelectionDAG &DAG,
2419                                     const CCValAssign &VA,
2420                                     ISD::ArgFlagsTy Flags) const {
2421   unsigned LocMemOffset = VA.getLocMemOffset();
2422   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2423   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2424   if (Flags.isByVal())
2425     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2426
2427   return DAG.getStore(Chain, dl, Arg, PtrOff,
2428                       MachinePointerInfo::getStack(LocMemOffset),
2429                       false, false, 0);
2430 }
2431
2432 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2433 /// optimization is performed and it is required.
2434 SDValue
2435 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2436                                            SDValue &OutRetAddr, SDValue Chain,
2437                                            bool IsTailCall, bool Is64Bit,
2438                                            int FPDiff, SDLoc dl) const {
2439   // Adjust the Return address stack slot.
2440   EVT VT = getPointerTy();
2441   OutRetAddr = getReturnAddressFrameIndex(DAG);
2442
2443   // Load the "old" Return address.
2444   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2445                            false, false, false, 0);
2446   return SDValue(OutRetAddr.getNode(), 1);
2447 }
2448
2449 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2450 /// optimization is performed and it is required (FPDiff!=0).
2451 static SDValue
2452 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2453                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2454                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2455   // Store the return address to the appropriate stack slot.
2456   if (!FPDiff) return Chain;
2457   // Calculate the new stack slot for the return address.
2458   int NewReturnAddrFI =
2459     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2460                                          false);
2461   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2462   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2463                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2464                        false, false, 0);
2465   return Chain;
2466 }
2467
2468 SDValue
2469 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2470                              SmallVectorImpl<SDValue> &InVals) const {
2471   SelectionDAG &DAG                     = CLI.DAG;
2472   SDLoc &dl                             = CLI.DL;
2473   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2474   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2475   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2476   SDValue Chain                         = CLI.Chain;
2477   SDValue Callee                        = CLI.Callee;
2478   CallingConv::ID CallConv              = CLI.CallConv;
2479   bool &isTailCall                      = CLI.IsTailCall;
2480   bool isVarArg                         = CLI.IsVarArg;
2481
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   bool Is64Bit        = Subtarget->is64Bit();
2484   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2485   bool IsWindows      = Subtarget->isTargetWindows();
2486   StructReturnType SR = callIsStructReturn(Outs);
2487   bool IsSibcall      = false;
2488
2489   if (MF.getTarget().Options.DisableTailCalls)
2490     isTailCall = false;
2491
2492   if (isTailCall) {
2493     // Check if it's really possible to do a tail call.
2494     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2495                     isVarArg, SR != NotStructReturn,
2496                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2497                     Outs, OutVals, Ins, DAG);
2498
2499     // Sibcalls are automatically detected tailcalls which do not require
2500     // ABI changes.
2501     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2502       IsSibcall = true;
2503
2504     if (isTailCall)
2505       ++NumTailCalls;
2506   }
2507
2508   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2509          "Var args not supported with calling convention fastcc, ghc or hipe");
2510
2511   // Analyze operands of the call, assigning locations to each operand.
2512   SmallVector<CCValAssign, 16> ArgLocs;
2513   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2514                  ArgLocs, *DAG.getContext());
2515
2516   // Allocate shadow area for Win64
2517   if (IsWin64)
2518     CCInfo.AllocateStack(32, 8);
2519
2520   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2521
2522   // Get a count of how many bytes are to be pushed on the stack.
2523   unsigned NumBytes = CCInfo.getNextStackOffset();
2524   if (IsSibcall)
2525     // This is a sibcall. The memory operands are available in caller's
2526     // own caller's stack.
2527     NumBytes = 0;
2528   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2529            IsTailCallConvention(CallConv))
2530     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2531
2532   int FPDiff = 0;
2533   if (isTailCall && !IsSibcall) {
2534     // Lower arguments at fp - stackoffset + fpdiff.
2535     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2536     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2537
2538     FPDiff = NumBytesCallerPushed - NumBytes;
2539
2540     // Set the delta of movement of the returnaddr stackslot.
2541     // But only set if delta is greater than previous delta.
2542     if (FPDiff < X86Info->getTCReturnAddrDelta())
2543       X86Info->setTCReturnAddrDelta(FPDiff);
2544   }
2545
2546   if (!IsSibcall)
2547     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2548                                  dl);
2549
2550   SDValue RetAddrFrIdx;
2551   // Load return address for tail calls.
2552   if (isTailCall && FPDiff)
2553     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2554                                     Is64Bit, FPDiff, dl);
2555
2556   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2557   SmallVector<SDValue, 8> MemOpChains;
2558   SDValue StackPtr;
2559
2560   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2561   // of tail call optimization arguments are handle later.
2562   const X86RegisterInfo *RegInfo =
2563     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2564   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2565     CCValAssign &VA = ArgLocs[i];
2566     EVT RegVT = VA.getLocVT();
2567     SDValue Arg = OutVals[i];
2568     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2569     bool isByVal = Flags.isByVal();
2570
2571     // Promote the value if needed.
2572     switch (VA.getLocInfo()) {
2573     default: llvm_unreachable("Unknown loc info!");
2574     case CCValAssign::Full: break;
2575     case CCValAssign::SExt:
2576       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2577       break;
2578     case CCValAssign::ZExt:
2579       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2580       break;
2581     case CCValAssign::AExt:
2582       if (RegVT.is128BitVector()) {
2583         // Special case: passing MMX values in XMM registers.
2584         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2585         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2586         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2587       } else
2588         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2589       break;
2590     case CCValAssign::BCvt:
2591       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2592       break;
2593     case CCValAssign::Indirect: {
2594       // Store the argument.
2595       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2596       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2597       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2598                            MachinePointerInfo::getFixedStack(FI),
2599                            false, false, 0);
2600       Arg = SpillSlot;
2601       break;
2602     }
2603     }
2604
2605     if (VA.isRegLoc()) {
2606       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2607       if (isVarArg && IsWin64) {
2608         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2609         // shadow reg if callee is a varargs function.
2610         unsigned ShadowReg = 0;
2611         switch (VA.getLocReg()) {
2612         case X86::XMM0: ShadowReg = X86::RCX; break;
2613         case X86::XMM1: ShadowReg = X86::RDX; break;
2614         case X86::XMM2: ShadowReg = X86::R8; break;
2615         case X86::XMM3: ShadowReg = X86::R9; break;
2616         }
2617         if (ShadowReg)
2618           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2619       }
2620     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2621       assert(VA.isMemLoc());
2622       if (StackPtr.getNode() == 0)
2623         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2624                                       getPointerTy());
2625       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2626                                              dl, DAG, VA, Flags));
2627     }
2628   }
2629
2630   if (!MemOpChains.empty())
2631     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2632                         &MemOpChains[0], MemOpChains.size());
2633
2634   if (Subtarget->isPICStyleGOT()) {
2635     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2636     // GOT pointer.
2637     if (!isTailCall) {
2638       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2639                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2640     } else {
2641       // If we are tail calling and generating PIC/GOT style code load the
2642       // address of the callee into ECX. The value in ecx is used as target of
2643       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2644       // for tail calls on PIC/GOT architectures. Normally we would just put the
2645       // address of GOT into ebx and then call target@PLT. But for tail calls
2646       // ebx would be restored (since ebx is callee saved) before jumping to the
2647       // target@PLT.
2648
2649       // Note: The actual moving to ECX is done further down.
2650       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2651       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2652           !G->getGlobal()->hasProtectedVisibility())
2653         Callee = LowerGlobalAddress(Callee, DAG);
2654       else if (isa<ExternalSymbolSDNode>(Callee))
2655         Callee = LowerExternalSymbol(Callee, DAG);
2656     }
2657   }
2658
2659   if (Is64Bit && isVarArg && !IsWin64) {
2660     // From AMD64 ABI document:
2661     // For calls that may call functions that use varargs or stdargs
2662     // (prototype-less calls or calls to functions containing ellipsis (...) in
2663     // the declaration) %al is used as hidden argument to specify the number
2664     // of SSE registers used. The contents of %al do not need to match exactly
2665     // the number of registers, but must be an ubound on the number of SSE
2666     // registers used and is in the range 0 - 8 inclusive.
2667
2668     // Count the number of XMM registers allocated.
2669     static const uint16_t XMMArgRegs[] = {
2670       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2671       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2672     };
2673     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2674     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2675            && "SSE registers cannot be used when SSE is disabled");
2676
2677     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2678                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2679   }
2680
2681   // For tail calls lower the arguments to the 'real' stack slot.
2682   if (isTailCall) {
2683     // Force all the incoming stack arguments to be loaded from the stack
2684     // before any new outgoing arguments are stored to the stack, because the
2685     // outgoing stack slots may alias the incoming argument stack slots, and
2686     // the alias isn't otherwise explicit. This is slightly more conservative
2687     // than necessary, because it means that each store effectively depends
2688     // on every argument instead of just those arguments it would clobber.
2689     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2690
2691     SmallVector<SDValue, 8> MemOpChains2;
2692     SDValue FIN;
2693     int FI = 0;
2694     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2695       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696         CCValAssign &VA = ArgLocs[i];
2697         if (VA.isRegLoc())
2698           continue;
2699         assert(VA.isMemLoc());
2700         SDValue Arg = OutVals[i];
2701         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2702         // Create frame index.
2703         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2704         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2705         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2706         FIN = DAG.getFrameIndex(FI, getPointerTy());
2707
2708         if (Flags.isByVal()) {
2709           // Copy relative to framepointer.
2710           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2711           if (StackPtr.getNode() == 0)
2712             StackPtr = DAG.getCopyFromReg(Chain, dl,
2713                                           RegInfo->getStackRegister(),
2714                                           getPointerTy());
2715           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2716
2717           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2718                                                            ArgChain,
2719                                                            Flags, DAG, dl));
2720         } else {
2721           // Store relative to framepointer.
2722           MemOpChains2.push_back(
2723             DAG.getStore(ArgChain, dl, Arg, FIN,
2724                          MachinePointerInfo::getFixedStack(FI),
2725                          false, false, 0));
2726         }
2727       }
2728     }
2729
2730     if (!MemOpChains2.empty())
2731       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2732                           &MemOpChains2[0], MemOpChains2.size());
2733
2734     // Store the return address to the appropriate stack slot.
2735     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2736                                      getPointerTy(), RegInfo->getSlotSize(),
2737                                      FPDiff, dl);
2738   }
2739
2740   // Build a sequence of copy-to-reg nodes chained together with token chain
2741   // and flag operands which copy the outgoing args into registers.
2742   SDValue InFlag;
2743   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2744     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2745                              RegsToPass[i].second, InFlag);
2746     InFlag = Chain.getValue(1);
2747   }
2748
2749   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2750     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2751     // In the 64-bit large code model, we have to make all calls
2752     // through a register, since the call instruction's 32-bit
2753     // pc-relative offset may not be large enough to hold the whole
2754     // address.
2755   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2756     // If the callee is a GlobalAddress node (quite common, every direct call
2757     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2758     // it.
2759
2760     // We should use extra load for direct calls to dllimported functions in
2761     // non-JIT mode.
2762     const GlobalValue *GV = G->getGlobal();
2763     if (!GV->hasDLLImportLinkage()) {
2764       unsigned char OpFlags = 0;
2765       bool ExtraLoad = false;
2766       unsigned WrapperKind = ISD::DELETED_NODE;
2767
2768       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2769       // external symbols most go through the PLT in PIC mode.  If the symbol
2770       // has hidden or protected visibility, or if it is static or local, then
2771       // we don't need to use the PLT - we can directly call it.
2772       if (Subtarget->isTargetELF() &&
2773           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2774           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2775         OpFlags = X86II::MO_PLT;
2776       } else if (Subtarget->isPICStyleStubAny() &&
2777                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2778                  (!Subtarget->getTargetTriple().isMacOSX() ||
2779                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2780         // PC-relative references to external symbols should go through $stub,
2781         // unless we're building with the leopard linker or later, which
2782         // automatically synthesizes these stubs.
2783         OpFlags = X86II::MO_DARWIN_STUB;
2784       } else if (Subtarget->isPICStyleRIPRel() &&
2785                  isa<Function>(GV) &&
2786                  cast<Function>(GV)->getAttributes().
2787                    hasAttribute(AttributeSet::FunctionIndex,
2788                                 Attribute::NonLazyBind)) {
2789         // If the function is marked as non-lazy, generate an indirect call
2790         // which loads from the GOT directly. This avoids runtime overhead
2791         // at the cost of eager binding (and one extra byte of encoding).
2792         OpFlags = X86II::MO_GOTPCREL;
2793         WrapperKind = X86ISD::WrapperRIP;
2794         ExtraLoad = true;
2795       }
2796
2797       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2798                                           G->getOffset(), OpFlags);
2799
2800       // Add a wrapper if needed.
2801       if (WrapperKind != ISD::DELETED_NODE)
2802         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2803       // Add extra indirection if needed.
2804       if (ExtraLoad)
2805         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2806                              MachinePointerInfo::getGOT(),
2807                              false, false, false, 0);
2808     }
2809   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2810     unsigned char OpFlags = 0;
2811
2812     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2813     // external symbols should go through the PLT.
2814     if (Subtarget->isTargetELF() &&
2815         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2816       OpFlags = X86II::MO_PLT;
2817     } else if (Subtarget->isPICStyleStubAny() &&
2818                (!Subtarget->getTargetTriple().isMacOSX() ||
2819                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2820       // PC-relative references to external symbols should go through $stub,
2821       // unless we're building with the leopard linker or later, which
2822       // automatically synthesizes these stubs.
2823       OpFlags = X86II::MO_DARWIN_STUB;
2824     }
2825
2826     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2827                                          OpFlags);
2828   }
2829
2830   // Returns a chain & a flag for retval copy to use.
2831   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2832   SmallVector<SDValue, 8> Ops;
2833
2834   if (!IsSibcall && isTailCall) {
2835     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2836                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2837     InFlag = Chain.getValue(1);
2838   }
2839
2840   Ops.push_back(Chain);
2841   Ops.push_back(Callee);
2842
2843   if (isTailCall)
2844     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2845
2846   // Add argument registers to the end of the list so that they are known live
2847   // into the call.
2848   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2849     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2850                                   RegsToPass[i].second.getValueType()));
2851
2852   // Add a register mask operand representing the call-preserved registers.
2853   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2854   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2855   assert(Mask && "Missing call preserved mask for calling convention");
2856   Ops.push_back(DAG.getRegisterMask(Mask));
2857
2858   if (InFlag.getNode())
2859     Ops.push_back(InFlag);
2860
2861   if (isTailCall) {
2862     // We used to do:
2863     //// If this is the first return lowered for this function, add the regs
2864     //// to the liveout set for the function.
2865     // This isn't right, although it's probably harmless on x86; liveouts
2866     // should be computed from returns not tail calls.  Consider a void
2867     // function making a tail call to a function returning int.
2868     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2869   }
2870
2871   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2872   InFlag = Chain.getValue(1);
2873
2874   // Create the CALLSEQ_END node.
2875   unsigned NumBytesForCalleeToPush;
2876   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2877                        getTargetMachine().Options.GuaranteedTailCallOpt))
2878     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2879   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2880            SR == StackStructReturn)
2881     // If this is a call to a struct-return function, the callee
2882     // pops the hidden struct pointer, so we have to push it back.
2883     // This is common for Darwin/X86, Linux & Mingw32 targets.
2884     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2885     NumBytesForCalleeToPush = 4;
2886   else
2887     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2888
2889   // Returns a flag for retval copy to use.
2890   if (!IsSibcall) {
2891     Chain = DAG.getCALLSEQ_END(Chain,
2892                                DAG.getIntPtrConstant(NumBytes, true),
2893                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2894                                                      true),
2895                                InFlag, dl);
2896     InFlag = Chain.getValue(1);
2897   }
2898
2899   // Handle result values, copying them out of physregs into vregs that we
2900   // return.
2901   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2902                          Ins, dl, DAG, InVals);
2903 }
2904
2905 //===----------------------------------------------------------------------===//
2906 //                Fast Calling Convention (tail call) implementation
2907 //===----------------------------------------------------------------------===//
2908
2909 //  Like std call, callee cleans arguments, convention except that ECX is
2910 //  reserved for storing the tail called function address. Only 2 registers are
2911 //  free for argument passing (inreg). Tail call optimization is performed
2912 //  provided:
2913 //                * tailcallopt is enabled
2914 //                * caller/callee are fastcc
2915 //  On X86_64 architecture with GOT-style position independent code only local
2916 //  (within module) calls are supported at the moment.
2917 //  To keep the stack aligned according to platform abi the function
2918 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2919 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2920 //  If a tail called function callee has more arguments than the caller the
2921 //  caller needs to make sure that there is room to move the RETADDR to. This is
2922 //  achieved by reserving an area the size of the argument delta right after the
2923 //  original REtADDR, but before the saved framepointer or the spilled registers
2924 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2925 //  stack layout:
2926 //    arg1
2927 //    arg2
2928 //    RETADDR
2929 //    [ new RETADDR
2930 //      move area ]
2931 //    (possible EBP)
2932 //    ESI
2933 //    EDI
2934 //    local1 ..
2935
2936 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2937 /// for a 16 byte align requirement.
2938 unsigned
2939 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2940                                                SelectionDAG& DAG) const {
2941   MachineFunction &MF = DAG.getMachineFunction();
2942   const TargetMachine &TM = MF.getTarget();
2943   const X86RegisterInfo *RegInfo =
2944     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2945   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2946   unsigned StackAlignment = TFI.getStackAlignment();
2947   uint64_t AlignMask = StackAlignment - 1;
2948   int64_t Offset = StackSize;
2949   unsigned SlotSize = RegInfo->getSlotSize();
2950   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2951     // Number smaller than 12 so just add the difference.
2952     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2953   } else {
2954     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2955     Offset = ((~AlignMask) & Offset) + StackAlignment +
2956       (StackAlignment-SlotSize);
2957   }
2958   return Offset;
2959 }
2960
2961 /// MatchingStackOffset - Return true if the given stack call argument is
2962 /// already available in the same position (relatively) of the caller's
2963 /// incoming argument stack.
2964 static
2965 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2966                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2967                          const X86InstrInfo *TII) {
2968   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2969   int FI = INT_MAX;
2970   if (Arg.getOpcode() == ISD::CopyFromReg) {
2971     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2972     if (!TargetRegisterInfo::isVirtualRegister(VR))
2973       return false;
2974     MachineInstr *Def = MRI->getVRegDef(VR);
2975     if (!Def)
2976       return false;
2977     if (!Flags.isByVal()) {
2978       if (!TII->isLoadFromStackSlot(Def, FI))
2979         return false;
2980     } else {
2981       unsigned Opcode = Def->getOpcode();
2982       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2983           Def->getOperand(1).isFI()) {
2984         FI = Def->getOperand(1).getIndex();
2985         Bytes = Flags.getByValSize();
2986       } else
2987         return false;
2988     }
2989   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2990     if (Flags.isByVal())
2991       // ByVal argument is passed in as a pointer but it's now being
2992       // dereferenced. e.g.
2993       // define @foo(%struct.X* %A) {
2994       //   tail call @bar(%struct.X* byval %A)
2995       // }
2996       return false;
2997     SDValue Ptr = Ld->getBasePtr();
2998     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2999     if (!FINode)
3000       return false;
3001     FI = FINode->getIndex();
3002   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3003     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3004     FI = FINode->getIndex();
3005     Bytes = Flags.getByValSize();
3006   } else
3007     return false;
3008
3009   assert(FI != INT_MAX);
3010   if (!MFI->isFixedObjectIndex(FI))
3011     return false;
3012   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3013 }
3014
3015 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3016 /// for tail call optimization. Targets which want to do tail call
3017 /// optimization should implement this function.
3018 bool
3019 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3020                                                      CallingConv::ID CalleeCC,
3021                                                      bool isVarArg,
3022                                                      bool isCalleeStructRet,
3023                                                      bool isCallerStructRet,
3024                                                      Type *RetTy,
3025                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3026                                     const SmallVectorImpl<SDValue> &OutVals,
3027                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3028                                                      SelectionDAG &DAG) const {
3029   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3030     return false;
3031
3032   // If -tailcallopt is specified, make fastcc functions tail-callable.
3033   const MachineFunction &MF = DAG.getMachineFunction();
3034   const Function *CallerF = MF.getFunction();
3035
3036   // If the function return type is x86_fp80 and the callee return type is not,
3037   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3038   // perform a tailcall optimization here.
3039   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3040     return false;
3041
3042   CallingConv::ID CallerCC = CallerF->getCallingConv();
3043   bool CCMatch = CallerCC == CalleeCC;
3044   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3045   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3046
3047   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3048     if (IsTailCallConvention(CalleeCC) && CCMatch)
3049       return true;
3050     return false;
3051   }
3052
3053   // Look for obvious safe cases to perform tail call optimization that do not
3054   // require ABI changes. This is what gcc calls sibcall.
3055
3056   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3057   // emit a special epilogue.
3058   const X86RegisterInfo *RegInfo =
3059     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3060   if (RegInfo->needsStackRealignment(MF))
3061     return false;
3062
3063   // Also avoid sibcall optimization if either caller or callee uses struct
3064   // return semantics.
3065   if (isCalleeStructRet || isCallerStructRet)
3066     return false;
3067
3068   // An stdcall caller is expected to clean up its arguments; the callee
3069   // isn't going to do that.
3070   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
3071     return false;
3072
3073   // Do not sibcall optimize vararg calls unless all arguments are passed via
3074   // registers.
3075   if (isVarArg && !Outs.empty()) {
3076
3077     // Optimizing for varargs on Win64 is unlikely to be safe without
3078     // additional testing.
3079     if (IsCalleeWin64 || IsCallerWin64)
3080       return false;
3081
3082     SmallVector<CCValAssign, 16> ArgLocs;
3083     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3084                    getTargetMachine(), ArgLocs, *DAG.getContext());
3085
3086     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3087     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3088       if (!ArgLocs[i].isRegLoc())
3089         return false;
3090   }
3091
3092   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3093   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3094   // this into a sibcall.
3095   bool Unused = false;
3096   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3097     if (!Ins[i].Used) {
3098       Unused = true;
3099       break;
3100     }
3101   }
3102   if (Unused) {
3103     SmallVector<CCValAssign, 16> RVLocs;
3104     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3105                    getTargetMachine(), RVLocs, *DAG.getContext());
3106     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3107     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3108       CCValAssign &VA = RVLocs[i];
3109       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3110         return false;
3111     }
3112   }
3113
3114   // If the calling conventions do not match, then we'd better make sure the
3115   // results are returned in the same way as what the caller expects.
3116   if (!CCMatch) {
3117     SmallVector<CCValAssign, 16> RVLocs1;
3118     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3119                     getTargetMachine(), RVLocs1, *DAG.getContext());
3120     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3121
3122     SmallVector<CCValAssign, 16> RVLocs2;
3123     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3124                     getTargetMachine(), RVLocs2, *DAG.getContext());
3125     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3126
3127     if (RVLocs1.size() != RVLocs2.size())
3128       return false;
3129     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3130       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3131         return false;
3132       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3133         return false;
3134       if (RVLocs1[i].isRegLoc()) {
3135         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3136           return false;
3137       } else {
3138         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3139           return false;
3140       }
3141     }
3142   }
3143
3144   // If the callee takes no arguments then go on to check the results of the
3145   // call.
3146   if (!Outs.empty()) {
3147     // Check if stack adjustment is needed. For now, do not do this if any
3148     // argument is passed on the stack.
3149     SmallVector<CCValAssign, 16> ArgLocs;
3150     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3151                    getTargetMachine(), ArgLocs, *DAG.getContext());
3152
3153     // Allocate shadow area for Win64
3154     if (IsCalleeWin64)
3155       CCInfo.AllocateStack(32, 8);
3156
3157     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3158     if (CCInfo.getNextStackOffset()) {
3159       MachineFunction &MF = DAG.getMachineFunction();
3160       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3161         return false;
3162
3163       // Check if the arguments are already laid out in the right way as
3164       // the caller's fixed stack objects.
3165       MachineFrameInfo *MFI = MF.getFrameInfo();
3166       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3167       const X86InstrInfo *TII =
3168         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3169       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3170         CCValAssign &VA = ArgLocs[i];
3171         SDValue Arg = OutVals[i];
3172         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3173         if (VA.getLocInfo() == CCValAssign::Indirect)
3174           return false;
3175         if (!VA.isRegLoc()) {
3176           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3177                                    MFI, MRI, TII))
3178             return false;
3179         }
3180       }
3181     }
3182
3183     // If the tailcall address may be in a register, then make sure it's
3184     // possible to register allocate for it. In 32-bit, the call address can
3185     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3186     // callee-saved registers are restored. These happen to be the same
3187     // registers used to pass 'inreg' arguments so watch out for those.
3188     if (!Subtarget->is64Bit() &&
3189         ((!isa<GlobalAddressSDNode>(Callee) &&
3190           !isa<ExternalSymbolSDNode>(Callee)) ||
3191          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3192       unsigned NumInRegs = 0;
3193       // In PIC we need an extra register to formulate the address computation
3194       // for the callee.
3195       unsigned MaxInRegs =
3196           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3197
3198       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3199         CCValAssign &VA = ArgLocs[i];
3200         if (!VA.isRegLoc())
3201           continue;
3202         unsigned Reg = VA.getLocReg();
3203         switch (Reg) {
3204         default: break;
3205         case X86::EAX: case X86::EDX: case X86::ECX:
3206           if (++NumInRegs == MaxInRegs)
3207             return false;
3208           break;
3209         }
3210       }
3211     }
3212   }
3213
3214   return true;
3215 }
3216
3217 FastISel *
3218 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3219                                   const TargetLibraryInfo *libInfo) const {
3220   return X86::createFastISel(funcInfo, libInfo);
3221 }
3222
3223 //===----------------------------------------------------------------------===//
3224 //                           Other Lowering Hooks
3225 //===----------------------------------------------------------------------===//
3226
3227 static bool MayFoldLoad(SDValue Op) {
3228   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3229 }
3230
3231 static bool MayFoldIntoStore(SDValue Op) {
3232   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3233 }
3234
3235 static bool isTargetShuffle(unsigned Opcode) {
3236   switch(Opcode) {
3237   default: return false;
3238   case X86ISD::PSHUFD:
3239   case X86ISD::PSHUFHW:
3240   case X86ISD::PSHUFLW:
3241   case X86ISD::SHUFP:
3242   case X86ISD::PALIGNR:
3243   case X86ISD::MOVLHPS:
3244   case X86ISD::MOVLHPD:
3245   case X86ISD::MOVHLPS:
3246   case X86ISD::MOVLPS:
3247   case X86ISD::MOVLPD:
3248   case X86ISD::MOVSHDUP:
3249   case X86ISD::MOVSLDUP:
3250   case X86ISD::MOVDDUP:
3251   case X86ISD::MOVSS:
3252   case X86ISD::MOVSD:
3253   case X86ISD::UNPCKL:
3254   case X86ISD::UNPCKH:
3255   case X86ISD::VPERMILP:
3256   case X86ISD::VPERM2X128:
3257   case X86ISD::VPERMI:
3258     return true;
3259   }
3260 }
3261
3262 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3263                                     SDValue V1, SelectionDAG &DAG) {
3264   switch(Opc) {
3265   default: llvm_unreachable("Unknown x86 shuffle node");
3266   case X86ISD::MOVSHDUP:
3267   case X86ISD::MOVSLDUP:
3268   case X86ISD::MOVDDUP:
3269     return DAG.getNode(Opc, dl, VT, V1);
3270   }
3271 }
3272
3273 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3274                                     SDValue V1, unsigned TargetMask,
3275                                     SelectionDAG &DAG) {
3276   switch(Opc) {
3277   default: llvm_unreachable("Unknown x86 shuffle node");
3278   case X86ISD::PSHUFD:
3279   case X86ISD::PSHUFHW:
3280   case X86ISD::PSHUFLW:
3281   case X86ISD::VPERMILP:
3282   case X86ISD::VPERMI:
3283     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3284   }
3285 }
3286
3287 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3288                                     SDValue V1, SDValue V2, unsigned TargetMask,
3289                                     SelectionDAG &DAG) {
3290   switch(Opc) {
3291   default: llvm_unreachable("Unknown x86 shuffle node");
3292   case X86ISD::PALIGNR:
3293   case X86ISD::SHUFP:
3294   case X86ISD::VPERM2X128:
3295     return DAG.getNode(Opc, dl, VT, V1, V2,
3296                        DAG.getConstant(TargetMask, MVT::i8));
3297   }
3298 }
3299
3300 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3301                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3302   switch(Opc) {
3303   default: llvm_unreachable("Unknown x86 shuffle node");
3304   case X86ISD::MOVLHPS:
3305   case X86ISD::MOVLHPD:
3306   case X86ISD::MOVHLPS:
3307   case X86ISD::MOVLPS:
3308   case X86ISD::MOVLPD:
3309   case X86ISD::MOVSS:
3310   case X86ISD::MOVSD:
3311   case X86ISD::UNPCKL:
3312   case X86ISD::UNPCKH:
3313     return DAG.getNode(Opc, dl, VT, V1, V2);
3314   }
3315 }
3316
3317 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3318   MachineFunction &MF = DAG.getMachineFunction();
3319   const X86RegisterInfo *RegInfo =
3320     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3321   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3322   int ReturnAddrIndex = FuncInfo->getRAIndex();
3323
3324   if (ReturnAddrIndex == 0) {
3325     // Set up a frame object for the return address.
3326     unsigned SlotSize = RegInfo->getSlotSize();
3327     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3328                                                            -(int64_t)SlotSize,
3329                                                            false);
3330     FuncInfo->setRAIndex(ReturnAddrIndex);
3331   }
3332
3333   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3334 }
3335
3336 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3337                                        bool hasSymbolicDisplacement) {
3338   // Offset should fit into 32 bit immediate field.
3339   if (!isInt<32>(Offset))
3340     return false;
3341
3342   // If we don't have a symbolic displacement - we don't have any extra
3343   // restrictions.
3344   if (!hasSymbolicDisplacement)
3345     return true;
3346
3347   // FIXME: Some tweaks might be needed for medium code model.
3348   if (M != CodeModel::Small && M != CodeModel::Kernel)
3349     return false;
3350
3351   // For small code model we assume that latest object is 16MB before end of 31
3352   // bits boundary. We may also accept pretty large negative constants knowing
3353   // that all objects are in the positive half of address space.
3354   if (M == CodeModel::Small && Offset < 16*1024*1024)
3355     return true;
3356
3357   // For kernel code model we know that all object resist in the negative half
3358   // of 32bits address space. We may not accept negative offsets, since they may
3359   // be just off and we may accept pretty large positive ones.
3360   if (M == CodeModel::Kernel && Offset > 0)
3361     return true;
3362
3363   return false;
3364 }
3365
3366 /// isCalleePop - Determines whether the callee is required to pop its
3367 /// own arguments. Callee pop is necessary to support tail calls.
3368 bool X86::isCalleePop(CallingConv::ID CallingConv,
3369                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3370   if (IsVarArg)
3371     return false;
3372
3373   switch (CallingConv) {
3374   default:
3375     return false;
3376   case CallingConv::X86_StdCall:
3377     return !is64Bit;
3378   case CallingConv::X86_FastCall:
3379     return !is64Bit;
3380   case CallingConv::X86_ThisCall:
3381     return !is64Bit;
3382   case CallingConv::Fast:
3383     return TailCallOpt;
3384   case CallingConv::GHC:
3385     return TailCallOpt;
3386   case CallingConv::HiPE:
3387     return TailCallOpt;
3388   }
3389 }
3390
3391 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3392 /// specific condition code, returning the condition code and the LHS/RHS of the
3393 /// comparison to make.
3394 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3395                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3396   if (!isFP) {
3397     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3398       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3399         // X > -1   -> X == 0, jump !sign.
3400         RHS = DAG.getConstant(0, RHS.getValueType());
3401         return X86::COND_NS;
3402       }
3403       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3404         // X < 0   -> X == 0, jump on sign.
3405         return X86::COND_S;
3406       }
3407       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3408         // X < 1   -> X <= 0
3409         RHS = DAG.getConstant(0, RHS.getValueType());
3410         return X86::COND_LE;
3411       }
3412     }
3413
3414     switch (SetCCOpcode) {
3415     default: llvm_unreachable("Invalid integer condition!");
3416     case ISD::SETEQ:  return X86::COND_E;
3417     case ISD::SETGT:  return X86::COND_G;
3418     case ISD::SETGE:  return X86::COND_GE;
3419     case ISD::SETLT:  return X86::COND_L;
3420     case ISD::SETLE:  return X86::COND_LE;
3421     case ISD::SETNE:  return X86::COND_NE;
3422     case ISD::SETULT: return X86::COND_B;
3423     case ISD::SETUGT: return X86::COND_A;
3424     case ISD::SETULE: return X86::COND_BE;
3425     case ISD::SETUGE: return X86::COND_AE;
3426     }
3427   }
3428
3429   // First determine if it is required or is profitable to flip the operands.
3430
3431   // If LHS is a foldable load, but RHS is not, flip the condition.
3432   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3433       !ISD::isNON_EXTLoad(RHS.getNode())) {
3434     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3435     std::swap(LHS, RHS);
3436   }
3437
3438   switch (SetCCOpcode) {
3439   default: break;
3440   case ISD::SETOLT:
3441   case ISD::SETOLE:
3442   case ISD::SETUGT:
3443   case ISD::SETUGE:
3444     std::swap(LHS, RHS);
3445     break;
3446   }
3447
3448   // On a floating point condition, the flags are set as follows:
3449   // ZF  PF  CF   op
3450   //  0 | 0 | 0 | X > Y
3451   //  0 | 0 | 1 | X < Y
3452   //  1 | 0 | 0 | X == Y
3453   //  1 | 1 | 1 | unordered
3454   switch (SetCCOpcode) {
3455   default: llvm_unreachable("Condcode should be pre-legalized away");
3456   case ISD::SETUEQ:
3457   case ISD::SETEQ:   return X86::COND_E;
3458   case ISD::SETOLT:              // flipped
3459   case ISD::SETOGT:
3460   case ISD::SETGT:   return X86::COND_A;
3461   case ISD::SETOLE:              // flipped
3462   case ISD::SETOGE:
3463   case ISD::SETGE:   return X86::COND_AE;
3464   case ISD::SETUGT:              // flipped
3465   case ISD::SETULT:
3466   case ISD::SETLT:   return X86::COND_B;
3467   case ISD::SETUGE:              // flipped
3468   case ISD::SETULE:
3469   case ISD::SETLE:   return X86::COND_BE;
3470   case ISD::SETONE:
3471   case ISD::SETNE:   return X86::COND_NE;
3472   case ISD::SETUO:   return X86::COND_P;
3473   case ISD::SETO:    return X86::COND_NP;
3474   case ISD::SETOEQ:
3475   case ISD::SETUNE:  return X86::COND_INVALID;
3476   }
3477 }
3478
3479 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3480 /// code. Current x86 isa includes the following FP cmov instructions:
3481 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3482 static bool hasFPCMov(unsigned X86CC) {
3483   switch (X86CC) {
3484   default:
3485     return false;
3486   case X86::COND_B:
3487   case X86::COND_BE:
3488   case X86::COND_E:
3489   case X86::COND_P:
3490   case X86::COND_A:
3491   case X86::COND_AE:
3492   case X86::COND_NE:
3493   case X86::COND_NP:
3494     return true;
3495   }
3496 }
3497
3498 /// isFPImmLegal - Returns true if the target can instruction select the
3499 /// specified FP immediate natively. If false, the legalizer will
3500 /// materialize the FP immediate as a load from a constant pool.
3501 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3502   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3503     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3504       return true;
3505   }
3506   return false;
3507 }
3508
3509 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3510 /// the specified range (L, H].
3511 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3512   return (Val < 0) || (Val >= Low && Val < Hi);
3513 }
3514
3515 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3516 /// specified value.
3517 static bool isUndefOrEqual(int Val, int CmpVal) {
3518   return (Val < 0 || Val == CmpVal);
3519 }
3520
3521 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3522 /// from position Pos and ending in Pos+Size, falls within the specified
3523 /// sequential range (L, L+Pos]. or is undef.
3524 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3525                                        unsigned Pos, unsigned Size, int Low) {
3526   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3527     if (!isUndefOrEqual(Mask[i], Low))
3528       return false;
3529   return true;
3530 }
3531
3532 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3533 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3534 /// the second operand.
3535 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3536   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3537     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3538   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3539     return (Mask[0] < 2 && Mask[1] < 2);
3540   return false;
3541 }
3542
3543 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3544 /// is suitable for input to PSHUFHW.
3545 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3546   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3547     return false;
3548
3549   // Lower quadword copied in order or undef.
3550   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3551     return false;
3552
3553   // Upper quadword shuffled.
3554   for (unsigned i = 4; i != 8; ++i)
3555     if (!isUndefOrInRange(Mask[i], 4, 8))
3556       return false;
3557
3558   if (VT == MVT::v16i16) {
3559     // Lower quadword copied in order or undef.
3560     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3561       return false;
3562
3563     // Upper quadword shuffled.
3564     for (unsigned i = 12; i != 16; ++i)
3565       if (!isUndefOrInRange(Mask[i], 12, 16))
3566         return false;
3567   }
3568
3569   return true;
3570 }
3571
3572 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3573 /// is suitable for input to PSHUFLW.
3574 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3575   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3576     return false;
3577
3578   // Upper quadword copied in order.
3579   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3580     return false;
3581
3582   // Lower quadword shuffled.
3583   for (unsigned i = 0; i != 4; ++i)
3584     if (!isUndefOrInRange(Mask[i], 0, 4))
3585       return false;
3586
3587   if (VT == MVT::v16i16) {
3588     // Upper quadword copied in order.
3589     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3590       return false;
3591
3592     // Lower quadword shuffled.
3593     for (unsigned i = 8; i != 12; ++i)
3594       if (!isUndefOrInRange(Mask[i], 8, 12))
3595         return false;
3596   }
3597
3598   return true;
3599 }
3600
3601 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3602 /// is suitable for input to PALIGNR.
3603 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3604                           const X86Subtarget *Subtarget) {
3605   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3606       (VT.is256BitVector() && !Subtarget->hasInt256()))
3607     return false;
3608
3609   unsigned NumElts = VT.getVectorNumElements();
3610   unsigned NumLanes = VT.getSizeInBits()/128;
3611   unsigned NumLaneElts = NumElts/NumLanes;
3612
3613   // Do not handle 64-bit element shuffles with palignr.
3614   if (NumLaneElts == 2)
3615     return false;
3616
3617   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3618     unsigned i;
3619     for (i = 0; i != NumLaneElts; ++i) {
3620       if (Mask[i+l] >= 0)
3621         break;
3622     }
3623
3624     // Lane is all undef, go to next lane
3625     if (i == NumLaneElts)
3626       continue;
3627
3628     int Start = Mask[i+l];
3629
3630     // Make sure its in this lane in one of the sources
3631     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3632         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3633       return false;
3634
3635     // If not lane 0, then we must match lane 0
3636     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3637       return false;
3638
3639     // Correct second source to be contiguous with first source
3640     if (Start >= (int)NumElts)
3641       Start -= NumElts - NumLaneElts;
3642
3643     // Make sure we're shifting in the right direction.
3644     if (Start <= (int)(i+l))
3645       return false;
3646
3647     Start -= i;
3648
3649     // Check the rest of the elements to see if they are consecutive.
3650     for (++i; i != NumLaneElts; ++i) {
3651       int Idx = Mask[i+l];
3652
3653       // Make sure its in this lane
3654       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3655           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3656         return false;
3657
3658       // If not lane 0, then we must match lane 0
3659       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3660         return false;
3661
3662       if (Idx >= (int)NumElts)
3663         Idx -= NumElts - NumLaneElts;
3664
3665       if (!isUndefOrEqual(Idx, Start+i))
3666         return false;
3667
3668     }
3669   }
3670
3671   return true;
3672 }
3673
3674 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3675 /// the two vector operands have swapped position.
3676 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3677                                      unsigned NumElems) {
3678   for (unsigned i = 0; i != NumElems; ++i) {
3679     int idx = Mask[i];
3680     if (idx < 0)
3681       continue;
3682     else if (idx < (int)NumElems)
3683       Mask[i] = idx + NumElems;
3684     else
3685       Mask[i] = idx - NumElems;
3686   }
3687 }
3688
3689 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3690 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3691 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3692 /// reverse of what x86 shuffles want.
3693 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3694                         bool Commuted = false) {
3695   if (!HasFp256 && VT.is256BitVector())
3696     return false;
3697
3698   unsigned NumElems = VT.getVectorNumElements();
3699   unsigned NumLanes = VT.getSizeInBits()/128;
3700   unsigned NumLaneElems = NumElems/NumLanes;
3701
3702   if (NumLaneElems != 2 && NumLaneElems != 4)
3703     return false;
3704
3705   // VSHUFPSY divides the resulting vector into 4 chunks.
3706   // The sources are also splitted into 4 chunks, and each destination
3707   // chunk must come from a different source chunk.
3708   //
3709   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3710   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3711   //
3712   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3713   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3714   //
3715   // VSHUFPDY divides the resulting vector into 4 chunks.
3716   // The sources are also splitted into 4 chunks, and each destination
3717   // chunk must come from a different source chunk.
3718   //
3719   //  SRC1 =>      X3       X2       X1       X0
3720   //  SRC2 =>      Y3       Y2       Y1       Y0
3721   //
3722   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3723   //
3724   unsigned HalfLaneElems = NumLaneElems/2;
3725   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3726     for (unsigned i = 0; i != NumLaneElems; ++i) {
3727       int Idx = Mask[i+l];
3728       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3729       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3730         return false;
3731       // For VSHUFPSY, the mask of the second half must be the same as the
3732       // first but with the appropriate offsets. This works in the same way as
3733       // VPERMILPS works with masks.
3734       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3735         continue;
3736       if (!isUndefOrEqual(Idx, Mask[i]+l))
3737         return false;
3738     }
3739   }
3740
3741   return true;
3742 }
3743
3744 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3745 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3746 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3747   if (!VT.is128BitVector())
3748     return false;
3749
3750   unsigned NumElems = VT.getVectorNumElements();
3751
3752   if (NumElems != 4)
3753     return false;
3754
3755   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3756   return isUndefOrEqual(Mask[0], 6) &&
3757          isUndefOrEqual(Mask[1], 7) &&
3758          isUndefOrEqual(Mask[2], 2) &&
3759          isUndefOrEqual(Mask[3], 3);
3760 }
3761
3762 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3763 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3764 /// <2, 3, 2, 3>
3765 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3766   if (!VT.is128BitVector())
3767     return false;
3768
3769   unsigned NumElems = VT.getVectorNumElements();
3770
3771   if (NumElems != 4)
3772     return false;
3773
3774   return isUndefOrEqual(Mask[0], 2) &&
3775          isUndefOrEqual(Mask[1], 3) &&
3776          isUndefOrEqual(Mask[2], 2) &&
3777          isUndefOrEqual(Mask[3], 3);
3778 }
3779
3780 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3781 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3782 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3783   if (!VT.is128BitVector())
3784     return false;
3785
3786   unsigned NumElems = VT.getVectorNumElements();
3787
3788   if (NumElems != 2 && NumElems != 4)
3789     return false;
3790
3791   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3792     if (!isUndefOrEqual(Mask[i], i + NumElems))
3793       return false;
3794
3795   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3796     if (!isUndefOrEqual(Mask[i], i))
3797       return false;
3798
3799   return true;
3800 }
3801
3802 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3803 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3804 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3805   if (!VT.is128BitVector())
3806     return false;
3807
3808   unsigned NumElems = VT.getVectorNumElements();
3809
3810   if (NumElems != 2 && NumElems != 4)
3811     return false;
3812
3813   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3814     if (!isUndefOrEqual(Mask[i], i))
3815       return false;
3816
3817   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3818     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3819       return false;
3820
3821   return true;
3822 }
3823
3824 //
3825 // Some special combinations that can be optimized.
3826 //
3827 static
3828 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3829                                SelectionDAG &DAG) {
3830   MVT VT = SVOp->getValueType(0).getSimpleVT();
3831   SDLoc dl(SVOp);
3832
3833   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3834     return SDValue();
3835
3836   ArrayRef<int> Mask = SVOp->getMask();
3837
3838   // These are the special masks that may be optimized.
3839   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3840   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3841   bool MatchEvenMask = true;
3842   bool MatchOddMask  = true;
3843   for (int i=0; i<8; ++i) {
3844     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3845       MatchEvenMask = false;
3846     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3847       MatchOddMask = false;
3848   }
3849
3850   if (!MatchEvenMask && !MatchOddMask)
3851     return SDValue();
3852
3853   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3854
3855   SDValue Op0 = SVOp->getOperand(0);
3856   SDValue Op1 = SVOp->getOperand(1);
3857
3858   if (MatchEvenMask) {
3859     // Shift the second operand right to 32 bits.
3860     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3861     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3862   } else {
3863     // Shift the first operand left to 32 bits.
3864     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3865     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3866   }
3867   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3868   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3869 }
3870
3871 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3872 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3873 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3874                          bool HasInt256, bool V2IsSplat = false) {
3875   unsigned NumElts = VT.getVectorNumElements();
3876
3877   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3878          "Unsupported vector type for unpckh");
3879
3880   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3881       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3882     return false;
3883
3884   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3885   // independently on 128-bit lanes.
3886   unsigned NumLanes = VT.getSizeInBits()/128;
3887   unsigned NumLaneElts = NumElts/NumLanes;
3888
3889   for (unsigned l = 0; l != NumLanes; ++l) {
3890     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3891          i != (l+1)*NumLaneElts;
3892          i += 2, ++j) {
3893       int BitI  = Mask[i];
3894       int BitI1 = Mask[i+1];
3895       if (!isUndefOrEqual(BitI, j))
3896         return false;
3897       if (V2IsSplat) {
3898         if (!isUndefOrEqual(BitI1, NumElts))
3899           return false;
3900       } else {
3901         if (!isUndefOrEqual(BitI1, j + NumElts))
3902           return false;
3903       }
3904     }
3905   }
3906
3907   return true;
3908 }
3909
3910 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3912 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3913                          bool HasInt256, bool V2IsSplat = false) {
3914   unsigned NumElts = VT.getVectorNumElements();
3915
3916   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3917          "Unsupported vector type for unpckh");
3918
3919   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3920       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3921     return false;
3922
3923   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3924   // independently on 128-bit lanes.
3925   unsigned NumLanes = VT.getSizeInBits()/128;
3926   unsigned NumLaneElts = NumElts/NumLanes;
3927
3928   for (unsigned l = 0; l != NumLanes; ++l) {
3929     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3930          i != (l+1)*NumLaneElts; i += 2, ++j) {
3931       int BitI  = Mask[i];
3932       int BitI1 = Mask[i+1];
3933       if (!isUndefOrEqual(BitI, j))
3934         return false;
3935       if (V2IsSplat) {
3936         if (isUndefOrEqual(BitI1, NumElts))
3937           return false;
3938       } else {
3939         if (!isUndefOrEqual(BitI1, j+NumElts))
3940           return false;
3941       }
3942     }
3943   }
3944   return true;
3945 }
3946
3947 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3948 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3949 /// <0, 0, 1, 1>
3950 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3951   unsigned NumElts = VT.getVectorNumElements();
3952   bool Is256BitVec = VT.is256BitVector();
3953
3954   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3955          "Unsupported vector type for unpckh");
3956
3957   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3958       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3959     return false;
3960
3961   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3962   // FIXME: Need a better way to get rid of this, there's no latency difference
3963   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3964   // the former later. We should also remove the "_undef" special mask.
3965   if (NumElts == 4 && Is256BitVec)
3966     return false;
3967
3968   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3969   // independently on 128-bit lanes.
3970   unsigned NumLanes = VT.getSizeInBits()/128;
3971   unsigned NumLaneElts = NumElts/NumLanes;
3972
3973   for (unsigned l = 0; l != NumLanes; ++l) {
3974     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3975          i != (l+1)*NumLaneElts;
3976          i += 2, ++j) {
3977       int BitI  = Mask[i];
3978       int BitI1 = Mask[i+1];
3979
3980       if (!isUndefOrEqual(BitI, j))
3981         return false;
3982       if (!isUndefOrEqual(BitI1, j))
3983         return false;
3984     }
3985   }
3986
3987   return true;
3988 }
3989
3990 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3991 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3992 /// <2, 2, 3, 3>
3993 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3994   unsigned NumElts = VT.getVectorNumElements();
3995
3996   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3997          "Unsupported vector type for unpckh");
3998
3999   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4000       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4001     return false;
4002
4003   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4004   // independently on 128-bit lanes.
4005   unsigned NumLanes = VT.getSizeInBits()/128;
4006   unsigned NumLaneElts = NumElts/NumLanes;
4007
4008   for (unsigned l = 0; l != NumLanes; ++l) {
4009     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
4010          i != (l+1)*NumLaneElts; i += 2, ++j) {
4011       int BitI  = Mask[i];
4012       int BitI1 = Mask[i+1];
4013       if (!isUndefOrEqual(BitI, j))
4014         return false;
4015       if (!isUndefOrEqual(BitI1, j))
4016         return false;
4017     }
4018   }
4019   return true;
4020 }
4021
4022 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4023 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4024 /// MOVSD, and MOVD, i.e. setting the lowest element.
4025 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4026   if (VT.getVectorElementType().getSizeInBits() < 32)
4027     return false;
4028   if (!VT.is128BitVector())
4029     return false;
4030
4031   unsigned NumElts = VT.getVectorNumElements();
4032
4033   if (!isUndefOrEqual(Mask[0], NumElts))
4034     return false;
4035
4036   for (unsigned i = 1; i != NumElts; ++i)
4037     if (!isUndefOrEqual(Mask[i], i))
4038       return false;
4039
4040   return true;
4041 }
4042
4043 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4044 /// as permutations between 128-bit chunks or halves. As an example: this
4045 /// shuffle bellow:
4046 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4047 /// The first half comes from the second half of V1 and the second half from the
4048 /// the second half of V2.
4049 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4050   if (!HasFp256 || !VT.is256BitVector())
4051     return false;
4052
4053   // The shuffle result is divided into half A and half B. In total the two
4054   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4055   // B must come from C, D, E or F.
4056   unsigned HalfSize = VT.getVectorNumElements()/2;
4057   bool MatchA = false, MatchB = false;
4058
4059   // Check if A comes from one of C, D, E, F.
4060   for (unsigned Half = 0; Half != 4; ++Half) {
4061     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4062       MatchA = true;
4063       break;
4064     }
4065   }
4066
4067   // Check if B comes from one of C, D, E, F.
4068   for (unsigned Half = 0; Half != 4; ++Half) {
4069     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4070       MatchB = true;
4071       break;
4072     }
4073   }
4074
4075   return MatchA && MatchB;
4076 }
4077
4078 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4079 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4080 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4081   MVT VT = SVOp->getValueType(0).getSimpleVT();
4082
4083   unsigned HalfSize = VT.getVectorNumElements()/2;
4084
4085   unsigned FstHalf = 0, SndHalf = 0;
4086   for (unsigned i = 0; i < HalfSize; ++i) {
4087     if (SVOp->getMaskElt(i) > 0) {
4088       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4089       break;
4090     }
4091   }
4092   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4093     if (SVOp->getMaskElt(i) > 0) {
4094       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4095       break;
4096     }
4097   }
4098
4099   return (FstHalf | (SndHalf << 4));
4100 }
4101
4102 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4103 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4104 /// Note that VPERMIL mask matching is different depending whether theunderlying
4105 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4106 /// to the same elements of the low, but to the higher half of the source.
4107 /// In VPERMILPD the two lanes could be shuffled independently of each other
4108 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4109 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4110   if (!HasFp256)
4111     return false;
4112
4113   unsigned NumElts = VT.getVectorNumElements();
4114   // Only match 256-bit with 32/64-bit types
4115   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
4116     return false;
4117
4118   unsigned NumLanes = VT.getSizeInBits()/128;
4119   unsigned LaneSize = NumElts/NumLanes;
4120   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4121     for (unsigned i = 0; i != LaneSize; ++i) {
4122       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4123         return false;
4124       if (NumElts != 8 || l == 0)
4125         continue;
4126       // VPERMILPS handling
4127       if (Mask[i] < 0)
4128         continue;
4129       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
4130         return false;
4131     }
4132   }
4133
4134   return true;
4135 }
4136
4137 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4138 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4139 /// element of vector 2 and the other elements to come from vector 1 in order.
4140 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
4141                                bool V2IsSplat = false, bool V2IsUndef = false) {
4142   if (!VT.is128BitVector())
4143     return false;
4144
4145   unsigned NumOps = VT.getVectorNumElements();
4146   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4147     return false;
4148
4149   if (!isUndefOrEqual(Mask[0], 0))
4150     return false;
4151
4152   for (unsigned i = 1; i != NumOps; ++i)
4153     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4154           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4155           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4156       return false;
4157
4158   return true;
4159 }
4160
4161 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4162 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4163 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4164 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
4165                            const X86Subtarget *Subtarget) {
4166   if (!Subtarget->hasSSE3())
4167     return false;
4168
4169   unsigned NumElems = VT.getVectorNumElements();
4170
4171   if ((VT.is128BitVector() && NumElems != 4) ||
4172       (VT.is256BitVector() && NumElems != 8))
4173     return false;
4174
4175   // "i+1" is the value the indexed mask element must have
4176   for (unsigned i = 0; i != NumElems; i += 2)
4177     if (!isUndefOrEqual(Mask[i], i+1) ||
4178         !isUndefOrEqual(Mask[i+1], i+1))
4179       return false;
4180
4181   return true;
4182 }
4183
4184 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4185 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4186 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4187 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
4188                            const X86Subtarget *Subtarget) {
4189   if (!Subtarget->hasSSE3())
4190     return false;
4191
4192   unsigned NumElems = VT.getVectorNumElements();
4193
4194   if ((VT.is128BitVector() && NumElems != 4) ||
4195       (VT.is256BitVector() && NumElems != 8))
4196     return false;
4197
4198   // "i" is the value the indexed mask element must have
4199   for (unsigned i = 0; i != NumElems; i += 2)
4200     if (!isUndefOrEqual(Mask[i], i) ||
4201         !isUndefOrEqual(Mask[i+1], i))
4202       return false;
4203
4204   return true;
4205 }
4206
4207 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4208 /// specifies a shuffle of elements that is suitable for input to 256-bit
4209 /// version of MOVDDUP.
4210 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4211   if (!HasFp256 || !VT.is256BitVector())
4212     return false;
4213
4214   unsigned NumElts = VT.getVectorNumElements();
4215   if (NumElts != 4)
4216     return false;
4217
4218   for (unsigned i = 0; i != NumElts/2; ++i)
4219     if (!isUndefOrEqual(Mask[i], 0))
4220       return false;
4221   for (unsigned i = NumElts/2; i != NumElts; ++i)
4222     if (!isUndefOrEqual(Mask[i], NumElts/2))
4223       return false;
4224   return true;
4225 }
4226
4227 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4228 /// specifies a shuffle of elements that is suitable for input to 128-bit
4229 /// version of MOVDDUP.
4230 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4231   if (!VT.is128BitVector())
4232     return false;
4233
4234   unsigned e = VT.getVectorNumElements() / 2;
4235   for (unsigned i = 0; i != e; ++i)
4236     if (!isUndefOrEqual(Mask[i], i))
4237       return false;
4238   for (unsigned i = 0; i != e; ++i)
4239     if (!isUndefOrEqual(Mask[e+i], i))
4240       return false;
4241   return true;
4242 }
4243
4244 /// isVEXTRACTIndex - Return true if the specified
4245 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4246 /// suitable for instruction that extract 128 or 256 bit vectors
4247 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4248   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4249   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4250     return false;
4251
4252   // The index should be aligned on a vecWidth-bit boundary.
4253   uint64_t Index =
4254     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4255
4256   MVT VT = N->getValueType(0).getSimpleVT();
4257   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4258   bool Result = (Index * ElSize) % vecWidth == 0;
4259
4260   return Result;
4261 }
4262
4263 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4264 /// operand specifies a subvector insert that is suitable for input to
4265 /// insertion of 128 or 256-bit subvectors
4266 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4267   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4268   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4269     return false;
4270   // The index should be aligned on a vecWidth-bit boundary.
4271   uint64_t Index =
4272     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4273
4274   MVT VT = N->getValueType(0).getSimpleVT();
4275   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4276   bool Result = (Index * ElSize) % vecWidth == 0;
4277
4278   return Result;
4279 }
4280
4281 bool X86::isVINSERT128Index(SDNode *N) {
4282   return isVINSERTIndex(N, 128);
4283 }
4284
4285 bool X86::isVINSERT256Index(SDNode *N) {
4286   return isVINSERTIndex(N, 256);
4287 }
4288
4289 bool X86::isVEXTRACT128Index(SDNode *N) {
4290   return isVEXTRACTIndex(N, 128);
4291 }
4292
4293 bool X86::isVEXTRACT256Index(SDNode *N) {
4294   return isVEXTRACTIndex(N, 256);
4295 }
4296
4297 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4298 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4299 /// Handles 128-bit and 256-bit.
4300 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4301   MVT VT = N->getValueType(0).getSimpleVT();
4302
4303   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4304          "Unsupported vector type for PSHUF/SHUFP");
4305
4306   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4307   // independently on 128-bit lanes.
4308   unsigned NumElts = VT.getVectorNumElements();
4309   unsigned NumLanes = VT.getSizeInBits()/128;
4310   unsigned NumLaneElts = NumElts/NumLanes;
4311
4312   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4313          "Only supports 2 or 4 elements per lane");
4314
4315   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4316   unsigned Mask = 0;
4317   for (unsigned i = 0; i != NumElts; ++i) {
4318     int Elt = N->getMaskElt(i);
4319     if (Elt < 0) continue;
4320     Elt &= NumLaneElts - 1;
4321     unsigned ShAmt = (i << Shift) % 8;
4322     Mask |= Elt << ShAmt;
4323   }
4324
4325   return Mask;
4326 }
4327
4328 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4329 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4330 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4331   MVT VT = N->getValueType(0).getSimpleVT();
4332
4333   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4334          "Unsupported vector type for PSHUFHW");
4335
4336   unsigned NumElts = VT.getVectorNumElements();
4337
4338   unsigned Mask = 0;
4339   for (unsigned l = 0; l != NumElts; l += 8) {
4340     // 8 nodes per lane, but we only care about the last 4.
4341     for (unsigned i = 0; i < 4; ++i) {
4342       int Elt = N->getMaskElt(l+i+4);
4343       if (Elt < 0) continue;
4344       Elt &= 0x3; // only 2-bits.
4345       Mask |= Elt << (i * 2);
4346     }
4347   }
4348
4349   return Mask;
4350 }
4351
4352 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4353 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4354 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4355   MVT VT = N->getValueType(0).getSimpleVT();
4356
4357   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4358          "Unsupported vector type for PSHUFHW");
4359
4360   unsigned NumElts = VT.getVectorNumElements();
4361
4362   unsigned Mask = 0;
4363   for (unsigned l = 0; l != NumElts; l += 8) {
4364     // 8 nodes per lane, but we only care about the first 4.
4365     for (unsigned i = 0; i < 4; ++i) {
4366       int Elt = N->getMaskElt(l+i);
4367       if (Elt < 0) continue;
4368       Elt &= 0x3; // only 2-bits
4369       Mask |= Elt << (i * 2);
4370     }
4371   }
4372
4373   return Mask;
4374 }
4375
4376 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4377 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4378 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4379   MVT VT = SVOp->getValueType(0).getSimpleVT();
4380   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4381
4382   unsigned NumElts = VT.getVectorNumElements();
4383   unsigned NumLanes = VT.getSizeInBits()/128;
4384   unsigned NumLaneElts = NumElts/NumLanes;
4385
4386   int Val = 0;
4387   unsigned i;
4388   for (i = 0; i != NumElts; ++i) {
4389     Val = SVOp->getMaskElt(i);
4390     if (Val >= 0)
4391       break;
4392   }
4393   if (Val >= (int)NumElts)
4394     Val -= NumElts - NumLaneElts;
4395
4396   assert(Val - i > 0 && "PALIGNR imm should be positive");
4397   return (Val - i) * EltSize;
4398 }
4399
4400 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4401   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4402   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4403     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4404
4405   uint64_t Index =
4406     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4407
4408   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4409   MVT ElVT = VecVT.getVectorElementType();
4410
4411   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4412   return Index / NumElemsPerChunk;
4413 }
4414
4415 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4416   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4417   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4418     llvm_unreachable("Illegal insert subvector for VINSERT");
4419
4420   uint64_t Index =
4421     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4422
4423   MVT VecVT = N->getValueType(0).getSimpleVT();
4424   MVT ElVT = VecVT.getVectorElementType();
4425
4426   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4427   return Index / NumElemsPerChunk;
4428 }
4429
4430 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4431 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4432 /// and VINSERTI128 instructions.
4433 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4434   return getExtractVEXTRACTImmediate(N, 128);
4435 }
4436
4437 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4438 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4439 /// and VINSERTI64x4 instructions.
4440 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4441   return getExtractVEXTRACTImmediate(N, 256);
4442 }
4443
4444 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4445 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4446 /// and VINSERTI128 instructions.
4447 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4448   return getInsertVINSERTImmediate(N, 128);
4449 }
4450
4451 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4452 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4453 /// and VINSERTI64x4 instructions.
4454 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4455   return getInsertVINSERTImmediate(N, 256);
4456 }
4457
4458 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4459 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4460 /// Handles 256-bit.
4461 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4462   MVT VT = N->getValueType(0).getSimpleVT();
4463
4464   unsigned NumElts = VT.getVectorNumElements();
4465
4466   assert((VT.is256BitVector() && NumElts == 4) &&
4467          "Unsupported vector type for VPERMQ/VPERMPD");
4468
4469   unsigned Mask = 0;
4470   for (unsigned i = 0; i != NumElts; ++i) {
4471     int Elt = N->getMaskElt(i);
4472     if (Elt < 0)
4473       continue;
4474     Mask |= Elt << (i*2);
4475   }
4476
4477   return Mask;
4478 }
4479 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4480 /// constant +0.0.
4481 bool X86::isZeroNode(SDValue Elt) {
4482   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4483     return CN->isNullValue();
4484   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4485     return CFP->getValueAPF().isPosZero();
4486   return false;
4487 }
4488
4489 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4490 /// their permute mask.
4491 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4492                                     SelectionDAG &DAG) {
4493   MVT VT = SVOp->getValueType(0).getSimpleVT();
4494   unsigned NumElems = VT.getVectorNumElements();
4495   SmallVector<int, 8> MaskVec;
4496
4497   for (unsigned i = 0; i != NumElems; ++i) {
4498     int Idx = SVOp->getMaskElt(i);
4499     if (Idx >= 0) {
4500       if (Idx < (int)NumElems)
4501         Idx += NumElems;
4502       else
4503         Idx -= NumElems;
4504     }
4505     MaskVec.push_back(Idx);
4506   }
4507   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4508                               SVOp->getOperand(0), &MaskVec[0]);
4509 }
4510
4511 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4512 /// match movhlps. The lower half elements should come from upper half of
4513 /// V1 (and in order), and the upper half elements should come from the upper
4514 /// half of V2 (and in order).
4515 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4516   if (!VT.is128BitVector())
4517     return false;
4518   if (VT.getVectorNumElements() != 4)
4519     return false;
4520   for (unsigned i = 0, e = 2; i != e; ++i)
4521     if (!isUndefOrEqual(Mask[i], i+2))
4522       return false;
4523   for (unsigned i = 2; i != 4; ++i)
4524     if (!isUndefOrEqual(Mask[i], i+4))
4525       return false;
4526   return true;
4527 }
4528
4529 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4530 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4531 /// required.
4532 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4533   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4534     return false;
4535   N = N->getOperand(0).getNode();
4536   if (!ISD::isNON_EXTLoad(N))
4537     return false;
4538   if (LD)
4539     *LD = cast<LoadSDNode>(N);
4540   return true;
4541 }
4542
4543 // Test whether the given value is a vector value which will be legalized
4544 // into a load.
4545 static bool WillBeConstantPoolLoad(SDNode *N) {
4546   if (N->getOpcode() != ISD::BUILD_VECTOR)
4547     return false;
4548
4549   // Check for any non-constant elements.
4550   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4551     switch (N->getOperand(i).getNode()->getOpcode()) {
4552     case ISD::UNDEF:
4553     case ISD::ConstantFP:
4554     case ISD::Constant:
4555       break;
4556     default:
4557       return false;
4558     }
4559
4560   // Vectors of all-zeros and all-ones are materialized with special
4561   // instructions rather than being loaded.
4562   return !ISD::isBuildVectorAllZeros(N) &&
4563          !ISD::isBuildVectorAllOnes(N);
4564 }
4565
4566 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4567 /// match movlp{s|d}. The lower half elements should come from lower half of
4568 /// V1 (and in order), and the upper half elements should come from the upper
4569 /// half of V2 (and in order). And since V1 will become the source of the
4570 /// MOVLP, it must be either a vector load or a scalar load to vector.
4571 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4572                                ArrayRef<int> Mask, EVT VT) {
4573   if (!VT.is128BitVector())
4574     return false;
4575
4576   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4577     return false;
4578   // Is V2 is a vector load, don't do this transformation. We will try to use
4579   // load folding shufps op.
4580   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4581     return false;
4582
4583   unsigned NumElems = VT.getVectorNumElements();
4584
4585   if (NumElems != 2 && NumElems != 4)
4586     return false;
4587   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4588     if (!isUndefOrEqual(Mask[i], i))
4589       return false;
4590   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4591     if (!isUndefOrEqual(Mask[i], i+NumElems))
4592       return false;
4593   return true;
4594 }
4595
4596 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4597 /// all the same.
4598 static bool isSplatVector(SDNode *N) {
4599   if (N->getOpcode() != ISD::BUILD_VECTOR)
4600     return false;
4601
4602   SDValue SplatValue = N->getOperand(0);
4603   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4604     if (N->getOperand(i) != SplatValue)
4605       return false;
4606   return true;
4607 }
4608
4609 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4610 /// to an zero vector.
4611 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4612 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4613   SDValue V1 = N->getOperand(0);
4614   SDValue V2 = N->getOperand(1);
4615   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4616   for (unsigned i = 0; i != NumElems; ++i) {
4617     int Idx = N->getMaskElt(i);
4618     if (Idx >= (int)NumElems) {
4619       unsigned Opc = V2.getOpcode();
4620       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4621         continue;
4622       if (Opc != ISD::BUILD_VECTOR ||
4623           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4624         return false;
4625     } else if (Idx >= 0) {
4626       unsigned Opc = V1.getOpcode();
4627       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4628         continue;
4629       if (Opc != ISD::BUILD_VECTOR ||
4630           !X86::isZeroNode(V1.getOperand(Idx)))
4631         return false;
4632     }
4633   }
4634   return true;
4635 }
4636
4637 /// getZeroVector - Returns a vector of specified type with all zero elements.
4638 ///
4639 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4640                              SelectionDAG &DAG, SDLoc dl) {
4641   assert(VT.isVector() && "Expected a vector type");
4642
4643   // Always build SSE zero vectors as <4 x i32> bitcasted
4644   // to their dest type. This ensures they get CSE'd.
4645   SDValue Vec;
4646   if (VT.is128BitVector()) {  // SSE
4647     if (Subtarget->hasSSE2()) {  // SSE2
4648       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4649       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4650     } else { // SSE1
4651       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4652       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4653     }
4654   } else if (VT.is256BitVector()) { // AVX
4655     if (Subtarget->hasInt256()) { // AVX2
4656       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4657       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4658       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4659                         array_lengthof(Ops));
4660     } else {
4661       // 256-bit logic and arithmetic instructions in AVX are all
4662       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4663       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4664       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4665       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4666                         array_lengthof(Ops));
4667     }
4668   } else
4669     llvm_unreachable("Unexpected vector type");
4670
4671   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4672 }
4673
4674 /// getOnesVector - Returns a vector of specified type with all bits set.
4675 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4676 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4677 /// Then bitcast to their original type, ensuring they get CSE'd.
4678 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4679                              SDLoc dl) {
4680   assert(VT.isVector() && "Expected a vector type");
4681
4682   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4683   SDValue Vec;
4684   if (VT.is256BitVector()) {
4685     if (HasInt256) { // AVX2
4686       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4687       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4688                         array_lengthof(Ops));
4689     } else { // AVX
4690       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4691       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4692     }
4693   } else if (VT.is128BitVector()) {
4694     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4695   } else
4696     llvm_unreachable("Unexpected vector type");
4697
4698   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4699 }
4700
4701 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4702 /// that point to V2 points to its first element.
4703 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4704   for (unsigned i = 0; i != NumElems; ++i) {
4705     if (Mask[i] > (int)NumElems) {
4706       Mask[i] = NumElems;
4707     }
4708   }
4709 }
4710
4711 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4712 /// operation of specified width.
4713 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4714                        SDValue V2) {
4715   unsigned NumElems = VT.getVectorNumElements();
4716   SmallVector<int, 8> Mask;
4717   Mask.push_back(NumElems);
4718   for (unsigned i = 1; i != NumElems; ++i)
4719     Mask.push_back(i);
4720   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4721 }
4722
4723 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4724 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4725                           SDValue V2) {
4726   unsigned NumElems = VT.getVectorNumElements();
4727   SmallVector<int, 8> Mask;
4728   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4729     Mask.push_back(i);
4730     Mask.push_back(i + NumElems);
4731   }
4732   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4733 }
4734
4735 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4736 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4737                           SDValue V2) {
4738   unsigned NumElems = VT.getVectorNumElements();
4739   SmallVector<int, 8> Mask;
4740   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4741     Mask.push_back(i + Half);
4742     Mask.push_back(i + NumElems + Half);
4743   }
4744   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4745 }
4746
4747 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4748 // a generic shuffle instruction because the target has no such instructions.
4749 // Generate shuffles which repeat i16 and i8 several times until they can be
4750 // represented by v4f32 and then be manipulated by target suported shuffles.
4751 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4752   EVT VT = V.getValueType();
4753   int NumElems = VT.getVectorNumElements();
4754   SDLoc dl(V);
4755
4756   while (NumElems > 4) {
4757     if (EltNo < NumElems/2) {
4758       V = getUnpackl(DAG, dl, VT, V, V);
4759     } else {
4760       V = getUnpackh(DAG, dl, VT, V, V);
4761       EltNo -= NumElems/2;
4762     }
4763     NumElems >>= 1;
4764   }
4765   return V;
4766 }
4767
4768 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4769 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4770   EVT VT = V.getValueType();
4771   SDLoc dl(V);
4772
4773   if (VT.is128BitVector()) {
4774     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4775     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4776     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4777                              &SplatMask[0]);
4778   } else if (VT.is256BitVector()) {
4779     // To use VPERMILPS to splat scalars, the second half of indicies must
4780     // refer to the higher part, which is a duplication of the lower one,
4781     // because VPERMILPS can only handle in-lane permutations.
4782     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4783                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4784
4785     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4786     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4787                              &SplatMask[0]);
4788   } else
4789     llvm_unreachable("Vector size not supported");
4790
4791   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4792 }
4793
4794 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4795 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4796   EVT SrcVT = SV->getValueType(0);
4797   SDValue V1 = SV->getOperand(0);
4798   SDLoc dl(SV);
4799
4800   int EltNo = SV->getSplatIndex();
4801   int NumElems = SrcVT.getVectorNumElements();
4802   bool Is256BitVec = SrcVT.is256BitVector();
4803
4804   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4805          "Unknown how to promote splat for type");
4806
4807   // Extract the 128-bit part containing the splat element and update
4808   // the splat element index when it refers to the higher register.
4809   if (Is256BitVec) {
4810     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4811     if (EltNo >= NumElems/2)
4812       EltNo -= NumElems/2;
4813   }
4814
4815   // All i16 and i8 vector types can't be used directly by a generic shuffle
4816   // instruction because the target has no such instruction. Generate shuffles
4817   // which repeat i16 and i8 several times until they fit in i32, and then can
4818   // be manipulated by target suported shuffles.
4819   EVT EltVT = SrcVT.getVectorElementType();
4820   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4821     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4822
4823   // Recreate the 256-bit vector and place the same 128-bit vector
4824   // into the low and high part. This is necessary because we want
4825   // to use VPERM* to shuffle the vectors
4826   if (Is256BitVec) {
4827     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4828   }
4829
4830   return getLegalSplat(DAG, V1, EltNo);
4831 }
4832
4833 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4834 /// vector of zero or undef vector.  This produces a shuffle where the low
4835 /// element of V2 is swizzled into the zero/undef vector, landing at element
4836 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4837 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4838                                            bool IsZero,
4839                                            const X86Subtarget *Subtarget,
4840                                            SelectionDAG &DAG) {
4841   EVT VT = V2.getValueType();
4842   SDValue V1 = IsZero
4843     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4844   unsigned NumElems = VT.getVectorNumElements();
4845   SmallVector<int, 16> MaskVec;
4846   for (unsigned i = 0; i != NumElems; ++i)
4847     // If this is the insertion idx, put the low elt of V2 here.
4848     MaskVec.push_back(i == Idx ? NumElems : i);
4849   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4850 }
4851
4852 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4853 /// target specific opcode. Returns true if the Mask could be calculated.
4854 /// Sets IsUnary to true if only uses one source.
4855 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4856                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4857   unsigned NumElems = VT.getVectorNumElements();
4858   SDValue ImmN;
4859
4860   IsUnary = false;
4861   switch(N->getOpcode()) {
4862   case X86ISD::SHUFP:
4863     ImmN = N->getOperand(N->getNumOperands()-1);
4864     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4865     break;
4866   case X86ISD::UNPCKH:
4867     DecodeUNPCKHMask(VT, Mask);
4868     break;
4869   case X86ISD::UNPCKL:
4870     DecodeUNPCKLMask(VT, Mask);
4871     break;
4872   case X86ISD::MOVHLPS:
4873     DecodeMOVHLPSMask(NumElems, Mask);
4874     break;
4875   case X86ISD::MOVLHPS:
4876     DecodeMOVLHPSMask(NumElems, Mask);
4877     break;
4878   case X86ISD::PALIGNR:
4879     ImmN = N->getOperand(N->getNumOperands()-1);
4880     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4881     break;
4882   case X86ISD::PSHUFD:
4883   case X86ISD::VPERMILP:
4884     ImmN = N->getOperand(N->getNumOperands()-1);
4885     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4886     IsUnary = true;
4887     break;
4888   case X86ISD::PSHUFHW:
4889     ImmN = N->getOperand(N->getNumOperands()-1);
4890     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4891     IsUnary = true;
4892     break;
4893   case X86ISD::PSHUFLW:
4894     ImmN = N->getOperand(N->getNumOperands()-1);
4895     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4896     IsUnary = true;
4897     break;
4898   case X86ISD::VPERMI:
4899     ImmN = N->getOperand(N->getNumOperands()-1);
4900     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4901     IsUnary = true;
4902     break;
4903   case X86ISD::MOVSS:
4904   case X86ISD::MOVSD: {
4905     // The index 0 always comes from the first element of the second source,
4906     // this is why MOVSS and MOVSD are used in the first place. The other
4907     // elements come from the other positions of the first source vector
4908     Mask.push_back(NumElems);
4909     for (unsigned i = 1; i != NumElems; ++i) {
4910       Mask.push_back(i);
4911     }
4912     break;
4913   }
4914   case X86ISD::VPERM2X128:
4915     ImmN = N->getOperand(N->getNumOperands()-1);
4916     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4917     if (Mask.empty()) return false;
4918     break;
4919   case X86ISD::MOVDDUP:
4920   case X86ISD::MOVLHPD:
4921   case X86ISD::MOVLPD:
4922   case X86ISD::MOVLPS:
4923   case X86ISD::MOVSHDUP:
4924   case X86ISD::MOVSLDUP:
4925     // Not yet implemented
4926     return false;
4927   default: llvm_unreachable("unknown target shuffle node");
4928   }
4929
4930   return true;
4931 }
4932
4933 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4934 /// element of the result of the vector shuffle.
4935 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4936                                    unsigned Depth) {
4937   if (Depth == 6)
4938     return SDValue();  // Limit search depth.
4939
4940   SDValue V = SDValue(N, 0);
4941   EVT VT = V.getValueType();
4942   unsigned Opcode = V.getOpcode();
4943
4944   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4945   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4946     int Elt = SV->getMaskElt(Index);
4947
4948     if (Elt < 0)
4949       return DAG.getUNDEF(VT.getVectorElementType());
4950
4951     unsigned NumElems = VT.getVectorNumElements();
4952     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4953                                          : SV->getOperand(1);
4954     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4955   }
4956
4957   // Recurse into target specific vector shuffles to find scalars.
4958   if (isTargetShuffle(Opcode)) {
4959     MVT ShufVT = V.getValueType().getSimpleVT();
4960     unsigned NumElems = ShufVT.getVectorNumElements();
4961     SmallVector<int, 16> ShuffleMask;
4962     bool IsUnary;
4963
4964     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4965       return SDValue();
4966
4967     int Elt = ShuffleMask[Index];
4968     if (Elt < 0)
4969       return DAG.getUNDEF(ShufVT.getVectorElementType());
4970
4971     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4972                                          : N->getOperand(1);
4973     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4974                                Depth+1);
4975   }
4976
4977   // Actual nodes that may contain scalar elements
4978   if (Opcode == ISD::BITCAST) {
4979     V = V.getOperand(0);
4980     EVT SrcVT = V.getValueType();
4981     unsigned NumElems = VT.getVectorNumElements();
4982
4983     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4984       return SDValue();
4985   }
4986
4987   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4988     return (Index == 0) ? V.getOperand(0)
4989                         : DAG.getUNDEF(VT.getVectorElementType());
4990
4991   if (V.getOpcode() == ISD::BUILD_VECTOR)
4992     return V.getOperand(Index);
4993
4994   return SDValue();
4995 }
4996
4997 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4998 /// shuffle operation which come from a consecutively from a zero. The
4999 /// search can start in two different directions, from left or right.
5000 /// We count undefs as zeros until PreferredNum is reached.
5001 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5002                                          unsigned NumElems, bool ZerosFromLeft,
5003                                          SelectionDAG &DAG,
5004                                          unsigned PreferredNum = -1U) {
5005   unsigned NumZeros = 0;
5006   for (unsigned i = 0; i != NumElems; ++i) {
5007     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5008     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5009     if (!Elt.getNode())
5010       break;
5011
5012     if (X86::isZeroNode(Elt))
5013       ++NumZeros;
5014     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5015       NumZeros = std::min(NumZeros + 1, PreferredNum);
5016     else
5017       break;
5018   }
5019
5020   return NumZeros;
5021 }
5022
5023 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5024 /// correspond consecutively to elements from one of the vector operands,
5025 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5026 static
5027 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5028                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5029                               unsigned NumElems, unsigned &OpNum) {
5030   bool SeenV1 = false;
5031   bool SeenV2 = false;
5032
5033   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5034     int Idx = SVOp->getMaskElt(i);
5035     // Ignore undef indicies
5036     if (Idx < 0)
5037       continue;
5038
5039     if (Idx < (int)NumElems)
5040       SeenV1 = true;
5041     else
5042       SeenV2 = true;
5043
5044     // Only accept consecutive elements from the same vector
5045     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5046       return false;
5047   }
5048
5049   OpNum = SeenV1 ? 0 : 1;
5050   return true;
5051 }
5052
5053 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5054 /// logical left shift of a vector.
5055 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5056                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5057   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5058   unsigned NumZeros = getNumOfConsecutiveZeros(
5059       SVOp, NumElems, false /* check zeros from right */, DAG,
5060       SVOp->getMaskElt(0));
5061   unsigned OpSrc;
5062
5063   if (!NumZeros)
5064     return false;
5065
5066   // Considering the elements in the mask that are not consecutive zeros,
5067   // check if they consecutively come from only one of the source vectors.
5068   //
5069   //               V1 = {X, A, B, C}     0
5070   //                         \  \  \    /
5071   //   vector_shuffle V1, V2 <1, 2, 3, X>
5072   //
5073   if (!isShuffleMaskConsecutive(SVOp,
5074             0,                   // Mask Start Index
5075             NumElems-NumZeros,   // Mask End Index(exclusive)
5076             NumZeros,            // Where to start looking in the src vector
5077             NumElems,            // Number of elements in vector
5078             OpSrc))              // Which source operand ?
5079     return false;
5080
5081   isLeft = false;
5082   ShAmt = NumZeros;
5083   ShVal = SVOp->getOperand(OpSrc);
5084   return true;
5085 }
5086
5087 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5088 /// logical left shift of a vector.
5089 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5090                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5091   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5092   unsigned NumZeros = getNumOfConsecutiveZeros(
5093       SVOp, NumElems, true /* check zeros from left */, DAG,
5094       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5095   unsigned OpSrc;
5096
5097   if (!NumZeros)
5098     return false;
5099
5100   // Considering the elements in the mask that are not consecutive zeros,
5101   // check if they consecutively come from only one of the source vectors.
5102   //
5103   //                           0    { A, B, X, X } = V2
5104   //                          / \    /  /
5105   //   vector_shuffle V1, V2 <X, X, 4, 5>
5106   //
5107   if (!isShuffleMaskConsecutive(SVOp,
5108             NumZeros,     // Mask Start Index
5109             NumElems,     // Mask End Index(exclusive)
5110             0,            // Where to start looking in the src vector
5111             NumElems,     // Number of elements in vector
5112             OpSrc))       // Which source operand ?
5113     return false;
5114
5115   isLeft = true;
5116   ShAmt = NumZeros;
5117   ShVal = SVOp->getOperand(OpSrc);
5118   return true;
5119 }
5120
5121 /// isVectorShift - Returns true if the shuffle can be implemented as a
5122 /// logical left or right shift of a vector.
5123 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5124                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5125   // Although the logic below support any bitwidth size, there are no
5126   // shift instructions which handle more than 128-bit vectors.
5127   if (!SVOp->getValueType(0).is128BitVector())
5128     return false;
5129
5130   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5131       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5132     return true;
5133
5134   return false;
5135 }
5136
5137 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5138 ///
5139 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5140                                        unsigned NumNonZero, unsigned NumZero,
5141                                        SelectionDAG &DAG,
5142                                        const X86Subtarget* Subtarget,
5143                                        const TargetLowering &TLI) {
5144   if (NumNonZero > 8)
5145     return SDValue();
5146
5147   SDLoc dl(Op);
5148   SDValue V(0, 0);
5149   bool First = true;
5150   for (unsigned i = 0; i < 16; ++i) {
5151     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5152     if (ThisIsNonZero && First) {
5153       if (NumZero)
5154         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5155       else
5156         V = DAG.getUNDEF(MVT::v8i16);
5157       First = false;
5158     }
5159
5160     if ((i & 1) != 0) {
5161       SDValue ThisElt(0, 0), LastElt(0, 0);
5162       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5163       if (LastIsNonZero) {
5164         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5165                               MVT::i16, Op.getOperand(i-1));
5166       }
5167       if (ThisIsNonZero) {
5168         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5169         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5170                               ThisElt, DAG.getConstant(8, MVT::i8));
5171         if (LastIsNonZero)
5172           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5173       } else
5174         ThisElt = LastElt;
5175
5176       if (ThisElt.getNode())
5177         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5178                         DAG.getIntPtrConstant(i/2));
5179     }
5180   }
5181
5182   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5183 }
5184
5185 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5186 ///
5187 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5188                                      unsigned NumNonZero, unsigned NumZero,
5189                                      SelectionDAG &DAG,
5190                                      const X86Subtarget* Subtarget,
5191                                      const TargetLowering &TLI) {
5192   if (NumNonZero > 4)
5193     return SDValue();
5194
5195   SDLoc dl(Op);
5196   SDValue V(0, 0);
5197   bool First = true;
5198   for (unsigned i = 0; i < 8; ++i) {
5199     bool isNonZero = (NonZeros & (1 << i)) != 0;
5200     if (isNonZero) {
5201       if (First) {
5202         if (NumZero)
5203           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5204         else
5205           V = DAG.getUNDEF(MVT::v8i16);
5206         First = false;
5207       }
5208       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5209                       MVT::v8i16, V, Op.getOperand(i),
5210                       DAG.getIntPtrConstant(i));
5211     }
5212   }
5213
5214   return V;
5215 }
5216
5217 /// getVShift - Return a vector logical shift node.
5218 ///
5219 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5220                          unsigned NumBits, SelectionDAG &DAG,
5221                          const TargetLowering &TLI, SDLoc dl) {
5222   assert(VT.is128BitVector() && "Unknown type for VShift");
5223   EVT ShVT = MVT::v2i64;
5224   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5225   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5226   return DAG.getNode(ISD::BITCAST, dl, VT,
5227                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5228                              DAG.getConstant(NumBits,
5229                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5230 }
5231
5232 SDValue
5233 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5234                                           SelectionDAG &DAG) const {
5235
5236   // Check if the scalar load can be widened into a vector load. And if
5237   // the address is "base + cst" see if the cst can be "absorbed" into
5238   // the shuffle mask.
5239   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5240     SDValue Ptr = LD->getBasePtr();
5241     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5242       return SDValue();
5243     EVT PVT = LD->getValueType(0);
5244     if (PVT != MVT::i32 && PVT != MVT::f32)
5245       return SDValue();
5246
5247     int FI = -1;
5248     int64_t Offset = 0;
5249     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5250       FI = FINode->getIndex();
5251       Offset = 0;
5252     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5253                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5254       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5255       Offset = Ptr.getConstantOperandVal(1);
5256       Ptr = Ptr.getOperand(0);
5257     } else {
5258       return SDValue();
5259     }
5260
5261     // FIXME: 256-bit vector instructions don't require a strict alignment,
5262     // improve this code to support it better.
5263     unsigned RequiredAlign = VT.getSizeInBits()/8;
5264     SDValue Chain = LD->getChain();
5265     // Make sure the stack object alignment is at least 16 or 32.
5266     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5267     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5268       if (MFI->isFixedObjectIndex(FI)) {
5269         // Can't change the alignment. FIXME: It's possible to compute
5270         // the exact stack offset and reference FI + adjust offset instead.
5271         // If someone *really* cares about this. That's the way to implement it.
5272         return SDValue();
5273       } else {
5274         MFI->setObjectAlignment(FI, RequiredAlign);
5275       }
5276     }
5277
5278     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5279     // Ptr + (Offset & ~15).
5280     if (Offset < 0)
5281       return SDValue();
5282     if ((Offset % RequiredAlign) & 3)
5283       return SDValue();
5284     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5285     if (StartOffset)
5286       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5287                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5288
5289     int EltNo = (Offset - StartOffset) >> 2;
5290     unsigned NumElems = VT.getVectorNumElements();
5291
5292     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5293     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5294                              LD->getPointerInfo().getWithOffset(StartOffset),
5295                              false, false, false, 0);
5296
5297     SmallVector<int, 8> Mask;
5298     for (unsigned i = 0; i != NumElems; ++i)
5299       Mask.push_back(EltNo);
5300
5301     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5302   }
5303
5304   return SDValue();
5305 }
5306
5307 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5308 /// vector of type 'VT', see if the elements can be replaced by a single large
5309 /// load which has the same value as a build_vector whose operands are 'elts'.
5310 ///
5311 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5312 ///
5313 /// FIXME: we'd also like to handle the case where the last elements are zero
5314 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5315 /// There's even a handy isZeroNode for that purpose.
5316 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5317                                         SDLoc &DL, SelectionDAG &DAG) {
5318   EVT EltVT = VT.getVectorElementType();
5319   unsigned NumElems = Elts.size();
5320
5321   LoadSDNode *LDBase = NULL;
5322   unsigned LastLoadedElt = -1U;
5323
5324   // For each element in the initializer, see if we've found a load or an undef.
5325   // If we don't find an initial load element, or later load elements are
5326   // non-consecutive, bail out.
5327   for (unsigned i = 0; i < NumElems; ++i) {
5328     SDValue Elt = Elts[i];
5329
5330     if (!Elt.getNode() ||
5331         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5332       return SDValue();
5333     if (!LDBase) {
5334       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5335         return SDValue();
5336       LDBase = cast<LoadSDNode>(Elt.getNode());
5337       LastLoadedElt = i;
5338       continue;
5339     }
5340     if (Elt.getOpcode() == ISD::UNDEF)
5341       continue;
5342
5343     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5344     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5345       return SDValue();
5346     LastLoadedElt = i;
5347   }
5348
5349   // If we have found an entire vector of loads and undefs, then return a large
5350   // load of the entire vector width starting at the base pointer.  If we found
5351   // consecutive loads for the low half, generate a vzext_load node.
5352   if (LastLoadedElt == NumElems - 1) {
5353     SDValue NewLd = SDValue();
5354     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5355       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5356                           LDBase->getPointerInfo(),
5357                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5358                           LDBase->isInvariant(), 0);
5359     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5360                         LDBase->getPointerInfo(),
5361                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5362                         LDBase->isInvariant(), LDBase->getAlignment());
5363
5364     if (LDBase->hasAnyUseOfValue(1)) {
5365       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5366                                      SDValue(LDBase, 1),
5367                                      SDValue(NewLd.getNode(), 1));
5368       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5369       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5370                              SDValue(NewLd.getNode(), 1));
5371     }
5372
5373     return NewLd;
5374   }
5375   if (NumElems == 4 && LastLoadedElt == 1 &&
5376       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5377     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5378     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5379     SDValue ResNode =
5380         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5381                                 array_lengthof(Ops), MVT::i64,
5382                                 LDBase->getPointerInfo(),
5383                                 LDBase->getAlignment(),
5384                                 false/*isVolatile*/, true/*ReadMem*/,
5385                                 false/*WriteMem*/);
5386
5387     // Make sure the newly-created LOAD is in the same position as LDBase in
5388     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5389     // update uses of LDBase's output chain to use the TokenFactor.
5390     if (LDBase->hasAnyUseOfValue(1)) {
5391       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5392                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5393       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5394       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5395                              SDValue(ResNode.getNode(), 1));
5396     }
5397
5398     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5399   }
5400   return SDValue();
5401 }
5402
5403 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5404 /// to generate a splat value for the following cases:
5405 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5406 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5407 /// a scalar load, or a constant.
5408 /// The VBROADCAST node is returned when a pattern is found,
5409 /// or SDValue() otherwise.
5410 SDValue
5411 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5412   if (!Subtarget->hasFp256())
5413     return SDValue();
5414
5415   MVT VT = Op.getValueType().getSimpleVT();
5416   SDLoc dl(Op);
5417
5418   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5419          "Unsupported vector type for broadcast.");
5420
5421   SDValue Ld;
5422   bool ConstSplatVal;
5423
5424   switch (Op.getOpcode()) {
5425     default:
5426       // Unknown pattern found.
5427       return SDValue();
5428
5429     case ISD::BUILD_VECTOR: {
5430       // The BUILD_VECTOR node must be a splat.
5431       if (!isSplatVector(Op.getNode()))
5432         return SDValue();
5433
5434       Ld = Op.getOperand(0);
5435       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5436                      Ld.getOpcode() == ISD::ConstantFP);
5437
5438       // The suspected load node has several users. Make sure that all
5439       // of its users are from the BUILD_VECTOR node.
5440       // Constants may have multiple users.
5441       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5442         return SDValue();
5443       break;
5444     }
5445
5446     case ISD::VECTOR_SHUFFLE: {
5447       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5448
5449       // Shuffles must have a splat mask where the first element is
5450       // broadcasted.
5451       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5452         return SDValue();
5453
5454       SDValue Sc = Op.getOperand(0);
5455       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5456           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5457
5458         if (!Subtarget->hasInt256())
5459           return SDValue();
5460
5461         // Use the register form of the broadcast instruction available on AVX2.
5462         if (VT.is256BitVector())
5463           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5464         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5465       }
5466
5467       Ld = Sc.getOperand(0);
5468       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5469                        Ld.getOpcode() == ISD::ConstantFP);
5470
5471       // The scalar_to_vector node and the suspected
5472       // load node must have exactly one user.
5473       // Constants may have multiple users.
5474       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5475         return SDValue();
5476       break;
5477     }
5478   }
5479
5480   bool Is256 = VT.is256BitVector();
5481
5482   // Handle the broadcasting a single constant scalar from the constant pool
5483   // into a vector. On Sandybridge it is still better to load a constant vector
5484   // from the constant pool and not to broadcast it from a scalar.
5485   if (ConstSplatVal && Subtarget->hasInt256()) {
5486     EVT CVT = Ld.getValueType();
5487     assert(!CVT.isVector() && "Must not broadcast a vector type");
5488     unsigned ScalarSize = CVT.getSizeInBits();
5489
5490     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5491       const Constant *C = 0;
5492       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5493         C = CI->getConstantIntValue();
5494       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5495         C = CF->getConstantFPValue();
5496
5497       assert(C && "Invalid constant type");
5498
5499       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5500       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5501       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5502                        MachinePointerInfo::getConstantPool(),
5503                        false, false, false, Alignment);
5504
5505       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5506     }
5507   }
5508
5509   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5510   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5511
5512   // Handle AVX2 in-register broadcasts.
5513   if (!IsLoad && Subtarget->hasInt256() &&
5514       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5515     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5516
5517   // The scalar source must be a normal load.
5518   if (!IsLoad)
5519     return SDValue();
5520
5521   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5522     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5523
5524   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5525   // double since there is no vbroadcastsd xmm
5526   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5527     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5528       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5529   }
5530
5531   // Unsupported broadcast.
5532   return SDValue();
5533 }
5534
5535 SDValue
5536 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5537   EVT VT = Op.getValueType();
5538
5539   // Skip if insert_vec_elt is not supported.
5540   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5541     return SDValue();
5542
5543   SDLoc DL(Op);
5544   unsigned NumElems = Op.getNumOperands();
5545
5546   SDValue VecIn1;
5547   SDValue VecIn2;
5548   SmallVector<unsigned, 4> InsertIndices;
5549   SmallVector<int, 8> Mask(NumElems, -1);
5550
5551   for (unsigned i = 0; i != NumElems; ++i) {
5552     unsigned Opc = Op.getOperand(i).getOpcode();
5553
5554     if (Opc == ISD::UNDEF)
5555       continue;
5556
5557     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5558       // Quit if more than 1 elements need inserting.
5559       if (InsertIndices.size() > 1)
5560         return SDValue();
5561
5562       InsertIndices.push_back(i);
5563       continue;
5564     }
5565
5566     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5567     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5568
5569     // Quit if extracted from vector of different type.
5570     if (ExtractedFromVec.getValueType() != VT)
5571       return SDValue();
5572
5573     // Quit if non-constant index.
5574     if (!isa<ConstantSDNode>(ExtIdx))
5575       return SDValue();
5576
5577     if (VecIn1.getNode() == 0)
5578       VecIn1 = ExtractedFromVec;
5579     else if (VecIn1 != ExtractedFromVec) {
5580       if (VecIn2.getNode() == 0)
5581         VecIn2 = ExtractedFromVec;
5582       else if (VecIn2 != ExtractedFromVec)
5583         // Quit if more than 2 vectors to shuffle
5584         return SDValue();
5585     }
5586
5587     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5588
5589     if (ExtractedFromVec == VecIn1)
5590       Mask[i] = Idx;
5591     else if (ExtractedFromVec == VecIn2)
5592       Mask[i] = Idx + NumElems;
5593   }
5594
5595   if (VecIn1.getNode() == 0)
5596     return SDValue();
5597
5598   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5599   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5600   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5601     unsigned Idx = InsertIndices[i];
5602     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5603                      DAG.getIntPtrConstant(Idx));
5604   }
5605
5606   return NV;
5607 }
5608
5609 SDValue
5610 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5611   SDLoc dl(Op);
5612
5613   MVT VT = Op.getValueType().getSimpleVT();
5614   MVT ExtVT = VT.getVectorElementType();
5615   unsigned NumElems = Op.getNumOperands();
5616
5617   // Vectors containing all zeros can be matched by pxor and xorps later
5618   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5619     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5620     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5621     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5622       return Op;
5623
5624     return getZeroVector(VT, Subtarget, DAG, dl);
5625   }
5626
5627   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5628   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5629   // vpcmpeqd on 256-bit vectors.
5630   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5631     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5632       return Op;
5633
5634     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5635   }
5636
5637   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5638   if (Broadcast.getNode())
5639     return Broadcast;
5640
5641   unsigned EVTBits = ExtVT.getSizeInBits();
5642
5643   unsigned NumZero  = 0;
5644   unsigned NumNonZero = 0;
5645   unsigned NonZeros = 0;
5646   bool IsAllConstants = true;
5647   SmallSet<SDValue, 8> Values;
5648   for (unsigned i = 0; i < NumElems; ++i) {
5649     SDValue Elt = Op.getOperand(i);
5650     if (Elt.getOpcode() == ISD::UNDEF)
5651       continue;
5652     Values.insert(Elt);
5653     if (Elt.getOpcode() != ISD::Constant &&
5654         Elt.getOpcode() != ISD::ConstantFP)
5655       IsAllConstants = false;
5656     if (X86::isZeroNode(Elt))
5657       NumZero++;
5658     else {
5659       NonZeros |= (1 << i);
5660       NumNonZero++;
5661     }
5662   }
5663
5664   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5665   if (NumNonZero == 0)
5666     return DAG.getUNDEF(VT);
5667
5668   // Special case for single non-zero, non-undef, element.
5669   if (NumNonZero == 1) {
5670     unsigned Idx = countTrailingZeros(NonZeros);
5671     SDValue Item = Op.getOperand(Idx);
5672
5673     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5674     // the value are obviously zero, truncate the value to i32 and do the
5675     // insertion that way.  Only do this if the value is non-constant or if the
5676     // value is a constant being inserted into element 0.  It is cheaper to do
5677     // a constant pool load than it is to do a movd + shuffle.
5678     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5679         (!IsAllConstants || Idx == 0)) {
5680       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5681         // Handle SSE only.
5682         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5683         EVT VecVT = MVT::v4i32;
5684         unsigned VecElts = 4;
5685
5686         // Truncate the value (which may itself be a constant) to i32, and
5687         // convert it to a vector with movd (S2V+shuffle to zero extend).
5688         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5689         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5690         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5691
5692         // Now we have our 32-bit value zero extended in the low element of
5693         // a vector.  If Idx != 0, swizzle it into place.
5694         if (Idx != 0) {
5695           SmallVector<int, 4> Mask;
5696           Mask.push_back(Idx);
5697           for (unsigned i = 1; i != VecElts; ++i)
5698             Mask.push_back(i);
5699           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5700                                       &Mask[0]);
5701         }
5702         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5703       }
5704     }
5705
5706     // If we have a constant or non-constant insertion into the low element of
5707     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5708     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5709     // depending on what the source datatype is.
5710     if (Idx == 0) {
5711       if (NumZero == 0)
5712         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5713
5714       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5715           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5716         if (VT.is256BitVector()) {
5717           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5718           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5719                              Item, DAG.getIntPtrConstant(0));
5720         }
5721         assert(VT.is128BitVector() && "Expected an SSE value type!");
5722         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5723         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5724         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5725       }
5726
5727       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5728         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5729         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5730         if (VT.is256BitVector()) {
5731           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5732           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5733         } else {
5734           assert(VT.is128BitVector() && "Expected an SSE value type!");
5735           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5736         }
5737         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5738       }
5739     }
5740
5741     // Is it a vector logical left shift?
5742     if (NumElems == 2 && Idx == 1 &&
5743         X86::isZeroNode(Op.getOperand(0)) &&
5744         !X86::isZeroNode(Op.getOperand(1))) {
5745       unsigned NumBits = VT.getSizeInBits();
5746       return getVShift(true, VT,
5747                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5748                                    VT, Op.getOperand(1)),
5749                        NumBits/2, DAG, *this, dl);
5750     }
5751
5752     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5753       return SDValue();
5754
5755     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5756     // is a non-constant being inserted into an element other than the low one,
5757     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5758     // movd/movss) to move this into the low element, then shuffle it into
5759     // place.
5760     if (EVTBits == 32) {
5761       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5762
5763       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5764       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5765       SmallVector<int, 8> MaskVec;
5766       for (unsigned i = 0; i != NumElems; ++i)
5767         MaskVec.push_back(i == Idx ? 0 : 1);
5768       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5769     }
5770   }
5771
5772   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5773   if (Values.size() == 1) {
5774     if (EVTBits == 32) {
5775       // Instead of a shuffle like this:
5776       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5777       // Check if it's possible to issue this instead.
5778       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5779       unsigned Idx = countTrailingZeros(NonZeros);
5780       SDValue Item = Op.getOperand(Idx);
5781       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5782         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5783     }
5784     return SDValue();
5785   }
5786
5787   // A vector full of immediates; various special cases are already
5788   // handled, so this is best done with a single constant-pool load.
5789   if (IsAllConstants)
5790     return SDValue();
5791
5792   // For AVX-length vectors, build the individual 128-bit pieces and use
5793   // shuffles to put them in place.
5794   if (VT.is256BitVector()) {
5795     SmallVector<SDValue, 32> V;
5796     for (unsigned i = 0; i != NumElems; ++i)
5797       V.push_back(Op.getOperand(i));
5798
5799     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5800
5801     // Build both the lower and upper subvector.
5802     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5803     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5804                                 NumElems/2);
5805
5806     // Recreate the wider vector with the lower and upper part.
5807     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5808   }
5809
5810   // Let legalizer expand 2-wide build_vectors.
5811   if (EVTBits == 64) {
5812     if (NumNonZero == 1) {
5813       // One half is zero or undef.
5814       unsigned Idx = countTrailingZeros(NonZeros);
5815       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5816                                  Op.getOperand(Idx));
5817       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5818     }
5819     return SDValue();
5820   }
5821
5822   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5823   if (EVTBits == 8 && NumElems == 16) {
5824     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5825                                         Subtarget, *this);
5826     if (V.getNode()) return V;
5827   }
5828
5829   if (EVTBits == 16 && NumElems == 8) {
5830     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5831                                       Subtarget, *this);
5832     if (V.getNode()) return V;
5833   }
5834
5835   // If element VT is == 32 bits, turn it into a number of shuffles.
5836   SmallVector<SDValue, 8> V(NumElems);
5837   if (NumElems == 4 && NumZero > 0) {
5838     for (unsigned i = 0; i < 4; ++i) {
5839       bool isZero = !(NonZeros & (1 << i));
5840       if (isZero)
5841         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5842       else
5843         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5844     }
5845
5846     for (unsigned i = 0; i < 2; ++i) {
5847       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5848         default: break;
5849         case 0:
5850           V[i] = V[i*2];  // Must be a zero vector.
5851           break;
5852         case 1:
5853           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5854           break;
5855         case 2:
5856           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5857           break;
5858         case 3:
5859           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5860           break;
5861       }
5862     }
5863
5864     bool Reverse1 = (NonZeros & 0x3) == 2;
5865     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5866     int MaskVec[] = {
5867       Reverse1 ? 1 : 0,
5868       Reverse1 ? 0 : 1,
5869       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5870       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5871     };
5872     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5873   }
5874
5875   if (Values.size() > 1 && VT.is128BitVector()) {
5876     // Check for a build vector of consecutive loads.
5877     for (unsigned i = 0; i < NumElems; ++i)
5878       V[i] = Op.getOperand(i);
5879
5880     // Check for elements which are consecutive loads.
5881     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5882     if (LD.getNode())
5883       return LD;
5884
5885     // Check for a build vector from mostly shuffle plus few inserting.
5886     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5887     if (Sh.getNode())
5888       return Sh;
5889
5890     // For SSE 4.1, use insertps to put the high elements into the low element.
5891     if (getSubtarget()->hasSSE41()) {
5892       SDValue Result;
5893       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5894         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5895       else
5896         Result = DAG.getUNDEF(VT);
5897
5898       for (unsigned i = 1; i < NumElems; ++i) {
5899         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5900         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5901                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5902       }
5903       return Result;
5904     }
5905
5906     // Otherwise, expand into a number of unpckl*, start by extending each of
5907     // our (non-undef) elements to the full vector width with the element in the
5908     // bottom slot of the vector (which generates no code for SSE).
5909     for (unsigned i = 0; i < NumElems; ++i) {
5910       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5911         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5912       else
5913         V[i] = DAG.getUNDEF(VT);
5914     }
5915
5916     // Next, we iteratively mix elements, e.g. for v4f32:
5917     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5918     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5919     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5920     unsigned EltStride = NumElems >> 1;
5921     while (EltStride != 0) {
5922       for (unsigned i = 0; i < EltStride; ++i) {
5923         // If V[i+EltStride] is undef and this is the first round of mixing,
5924         // then it is safe to just drop this shuffle: V[i] is already in the
5925         // right place, the one element (since it's the first round) being
5926         // inserted as undef can be dropped.  This isn't safe for successive
5927         // rounds because they will permute elements within both vectors.
5928         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5929             EltStride == NumElems/2)
5930           continue;
5931
5932         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5933       }
5934       EltStride >>= 1;
5935     }
5936     return V[0];
5937   }
5938   return SDValue();
5939 }
5940
5941 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5942 // to create 256-bit vectors from two other 128-bit ones.
5943 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5944   SDLoc dl(Op);
5945   MVT ResVT = Op.getValueType().getSimpleVT();
5946
5947   assert((ResVT.is256BitVector() ||
5948           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
5949
5950   SDValue V1 = Op.getOperand(0);
5951   SDValue V2 = Op.getOperand(1);
5952   unsigned NumElems = ResVT.getVectorNumElements();
5953   if(ResVT.is256BitVector())
5954     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5955
5956   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5957 }
5958
5959 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5960   assert(Op.getNumOperands() == 2);
5961
5962   // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors
5963   // from two other 128-bit ones.
5964   return LowerAVXCONCAT_VECTORS(Op, DAG);
5965 }
5966
5967 // Try to lower a shuffle node into a simple blend instruction.
5968 static SDValue
5969 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5970                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5971   SDValue V1 = SVOp->getOperand(0);
5972   SDValue V2 = SVOp->getOperand(1);
5973   SDLoc dl(SVOp);
5974   MVT VT = SVOp->getValueType(0).getSimpleVT();
5975   MVT EltVT = VT.getVectorElementType();
5976   unsigned NumElems = VT.getVectorNumElements();
5977
5978   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5979     return SDValue();
5980   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5981     return SDValue();
5982
5983   // Check the mask for BLEND and build the value.
5984   unsigned MaskValue = 0;
5985   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5986   unsigned NumLanes = (NumElems-1)/8 + 1;
5987   unsigned NumElemsInLane = NumElems / NumLanes;
5988
5989   // Blend for v16i16 should be symetric for the both lanes.
5990   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5991
5992     int SndLaneEltIdx = (NumLanes == 2) ?
5993       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5994     int EltIdx = SVOp->getMaskElt(i);
5995
5996     if ((EltIdx < 0 || EltIdx == (int)i) &&
5997         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5998       continue;
5999
6000     if (((unsigned)EltIdx == (i + NumElems)) &&
6001         (SndLaneEltIdx < 0 ||
6002          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6003       MaskValue |= (1<<i);
6004     else
6005       return SDValue();
6006   }
6007
6008   // Convert i32 vectors to floating point if it is not AVX2.
6009   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6010   MVT BlendVT = VT;
6011   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6012     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6013                                NumElems);
6014     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6015     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6016   }
6017
6018   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6019                             DAG.getConstant(MaskValue, MVT::i32));
6020   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6021 }
6022
6023 // v8i16 shuffles - Prefer shuffles in the following order:
6024 // 1. [all]   pshuflw, pshufhw, optional move
6025 // 2. [ssse3] 1 x pshufb
6026 // 3. [ssse3] 2 x pshufb + 1 x por
6027 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6028 static SDValue
6029 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6030                          SelectionDAG &DAG) {
6031   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6032   SDValue V1 = SVOp->getOperand(0);
6033   SDValue V2 = SVOp->getOperand(1);
6034   SDLoc dl(SVOp);
6035   SmallVector<int, 8> MaskVals;
6036
6037   // Determine if more than 1 of the words in each of the low and high quadwords
6038   // of the result come from the same quadword of one of the two inputs.  Undef
6039   // mask values count as coming from any quadword, for better codegen.
6040   unsigned LoQuad[] = { 0, 0, 0, 0 };
6041   unsigned HiQuad[] = { 0, 0, 0, 0 };
6042   std::bitset<4> InputQuads;
6043   for (unsigned i = 0; i < 8; ++i) {
6044     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6045     int EltIdx = SVOp->getMaskElt(i);
6046     MaskVals.push_back(EltIdx);
6047     if (EltIdx < 0) {
6048       ++Quad[0];
6049       ++Quad[1];
6050       ++Quad[2];
6051       ++Quad[3];
6052       continue;
6053     }
6054     ++Quad[EltIdx / 4];
6055     InputQuads.set(EltIdx / 4);
6056   }
6057
6058   int BestLoQuad = -1;
6059   unsigned MaxQuad = 1;
6060   for (unsigned i = 0; i < 4; ++i) {
6061     if (LoQuad[i] > MaxQuad) {
6062       BestLoQuad = i;
6063       MaxQuad = LoQuad[i];
6064     }
6065   }
6066
6067   int BestHiQuad = -1;
6068   MaxQuad = 1;
6069   for (unsigned i = 0; i < 4; ++i) {
6070     if (HiQuad[i] > MaxQuad) {
6071       BestHiQuad = i;
6072       MaxQuad = HiQuad[i];
6073     }
6074   }
6075
6076   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6077   // of the two input vectors, shuffle them into one input vector so only a
6078   // single pshufb instruction is necessary. If There are more than 2 input
6079   // quads, disable the next transformation since it does not help SSSE3.
6080   bool V1Used = InputQuads[0] || InputQuads[1];
6081   bool V2Used = InputQuads[2] || InputQuads[3];
6082   if (Subtarget->hasSSSE3()) {
6083     if (InputQuads.count() == 2 && V1Used && V2Used) {
6084       BestLoQuad = InputQuads[0] ? 0 : 1;
6085       BestHiQuad = InputQuads[2] ? 2 : 3;
6086     }
6087     if (InputQuads.count() > 2) {
6088       BestLoQuad = -1;
6089       BestHiQuad = -1;
6090     }
6091   }
6092
6093   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6094   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6095   // words from all 4 input quadwords.
6096   SDValue NewV;
6097   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6098     int MaskV[] = {
6099       BestLoQuad < 0 ? 0 : BestLoQuad,
6100       BestHiQuad < 0 ? 1 : BestHiQuad
6101     };
6102     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6103                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6104                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6105     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6106
6107     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6108     // source words for the shuffle, to aid later transformations.
6109     bool AllWordsInNewV = true;
6110     bool InOrder[2] = { true, true };
6111     for (unsigned i = 0; i != 8; ++i) {
6112       int idx = MaskVals[i];
6113       if (idx != (int)i)
6114         InOrder[i/4] = false;
6115       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6116         continue;
6117       AllWordsInNewV = false;
6118       break;
6119     }
6120
6121     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6122     if (AllWordsInNewV) {
6123       for (int i = 0; i != 8; ++i) {
6124         int idx = MaskVals[i];
6125         if (idx < 0)
6126           continue;
6127         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6128         if ((idx != i) && idx < 4)
6129           pshufhw = false;
6130         if ((idx != i) && idx > 3)
6131           pshuflw = false;
6132       }
6133       V1 = NewV;
6134       V2Used = false;
6135       BestLoQuad = 0;
6136       BestHiQuad = 1;
6137     }
6138
6139     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6140     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6141     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6142       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6143       unsigned TargetMask = 0;
6144       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6145                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6146       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6147       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6148                              getShufflePSHUFLWImmediate(SVOp);
6149       V1 = NewV.getOperand(0);
6150       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6151     }
6152   }
6153
6154   // Promote splats to a larger type which usually leads to more efficient code.
6155   // FIXME: Is this true if pshufb is available?
6156   if (SVOp->isSplat())
6157     return PromoteSplat(SVOp, DAG);
6158
6159   // If we have SSSE3, and all words of the result are from 1 input vector,
6160   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6161   // is present, fall back to case 4.
6162   if (Subtarget->hasSSSE3()) {
6163     SmallVector<SDValue,16> pshufbMask;
6164
6165     // If we have elements from both input vectors, set the high bit of the
6166     // shuffle mask element to zero out elements that come from V2 in the V1
6167     // mask, and elements that come from V1 in the V2 mask, so that the two
6168     // results can be OR'd together.
6169     bool TwoInputs = V1Used && V2Used;
6170     for (unsigned i = 0; i != 8; ++i) {
6171       int EltIdx = MaskVals[i] * 2;
6172       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6173       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6174       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6175       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6176     }
6177     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6178     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6179                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6180                                  MVT::v16i8, &pshufbMask[0], 16));
6181     if (!TwoInputs)
6182       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6183
6184     // Calculate the shuffle mask for the second input, shuffle it, and
6185     // OR it with the first shuffled input.
6186     pshufbMask.clear();
6187     for (unsigned i = 0; i != 8; ++i) {
6188       int EltIdx = MaskVals[i] * 2;
6189       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6190       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6191       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6192       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6193     }
6194     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6195     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6196                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6197                                  MVT::v16i8, &pshufbMask[0], 16));
6198     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6199     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6200   }
6201
6202   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6203   // and update MaskVals with new element order.
6204   std::bitset<8> InOrder;
6205   if (BestLoQuad >= 0) {
6206     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6207     for (int i = 0; i != 4; ++i) {
6208       int idx = MaskVals[i];
6209       if (idx < 0) {
6210         InOrder.set(i);
6211       } else if ((idx / 4) == BestLoQuad) {
6212         MaskV[i] = idx & 3;
6213         InOrder.set(i);
6214       }
6215     }
6216     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6217                                 &MaskV[0]);
6218
6219     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6220       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6221       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6222                                   NewV.getOperand(0),
6223                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6224     }
6225   }
6226
6227   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6228   // and update MaskVals with the new element order.
6229   if (BestHiQuad >= 0) {
6230     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6231     for (unsigned i = 4; i != 8; ++i) {
6232       int idx = MaskVals[i];
6233       if (idx < 0) {
6234         InOrder.set(i);
6235       } else if ((idx / 4) == BestHiQuad) {
6236         MaskV[i] = (idx & 3) + 4;
6237         InOrder.set(i);
6238       }
6239     }
6240     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6241                                 &MaskV[0]);
6242
6243     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6244       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6245       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6246                                   NewV.getOperand(0),
6247                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6248     }
6249   }
6250
6251   // In case BestHi & BestLo were both -1, which means each quadword has a word
6252   // from each of the four input quadwords, calculate the InOrder bitvector now
6253   // before falling through to the insert/extract cleanup.
6254   if (BestLoQuad == -1 && BestHiQuad == -1) {
6255     NewV = V1;
6256     for (int i = 0; i != 8; ++i)
6257       if (MaskVals[i] < 0 || MaskVals[i] == i)
6258         InOrder.set(i);
6259   }
6260
6261   // The other elements are put in the right place using pextrw and pinsrw.
6262   for (unsigned i = 0; i != 8; ++i) {
6263     if (InOrder[i])
6264       continue;
6265     int EltIdx = MaskVals[i];
6266     if (EltIdx < 0)
6267       continue;
6268     SDValue ExtOp = (EltIdx < 8) ?
6269       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6270                   DAG.getIntPtrConstant(EltIdx)) :
6271       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6272                   DAG.getIntPtrConstant(EltIdx - 8));
6273     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6274                        DAG.getIntPtrConstant(i));
6275   }
6276   return NewV;
6277 }
6278
6279 // v16i8 shuffles - Prefer shuffles in the following order:
6280 // 1. [ssse3] 1 x pshufb
6281 // 2. [ssse3] 2 x pshufb + 1 x por
6282 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6283 static
6284 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6285                                  SelectionDAG &DAG,
6286                                  const X86TargetLowering &TLI) {
6287   SDValue V1 = SVOp->getOperand(0);
6288   SDValue V2 = SVOp->getOperand(1);
6289   SDLoc dl(SVOp);
6290   ArrayRef<int> MaskVals = SVOp->getMask();
6291
6292   // Promote splats to a larger type which usually leads to more efficient code.
6293   // FIXME: Is this true if pshufb is available?
6294   if (SVOp->isSplat())
6295     return PromoteSplat(SVOp, DAG);
6296
6297   // If we have SSSE3, case 1 is generated when all result bytes come from
6298   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6299   // present, fall back to case 3.
6300
6301   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6302   if (TLI.getSubtarget()->hasSSSE3()) {
6303     SmallVector<SDValue,16> pshufbMask;
6304
6305     // If all result elements are from one input vector, then only translate
6306     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6307     //
6308     // Otherwise, we have elements from both input vectors, and must zero out
6309     // elements that come from V2 in the first mask, and V1 in the second mask
6310     // so that we can OR them together.
6311     for (unsigned i = 0; i != 16; ++i) {
6312       int EltIdx = MaskVals[i];
6313       if (EltIdx < 0 || EltIdx >= 16)
6314         EltIdx = 0x80;
6315       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6316     }
6317     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6318                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6319                                  MVT::v16i8, &pshufbMask[0], 16));
6320
6321     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6322     // the 2nd operand if it's undefined or zero.
6323     if (V2.getOpcode() == ISD::UNDEF ||
6324         ISD::isBuildVectorAllZeros(V2.getNode()))
6325       return V1;
6326
6327     // Calculate the shuffle mask for the second input, shuffle it, and
6328     // OR it with the first shuffled input.
6329     pshufbMask.clear();
6330     for (unsigned i = 0; i != 16; ++i) {
6331       int EltIdx = MaskVals[i];
6332       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6333       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6334     }
6335     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6336                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6337                                  MVT::v16i8, &pshufbMask[0], 16));
6338     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6339   }
6340
6341   // No SSSE3 - Calculate in place words and then fix all out of place words
6342   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6343   // the 16 different words that comprise the two doublequadword input vectors.
6344   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6345   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6346   SDValue NewV = V1;
6347   for (int i = 0; i != 8; ++i) {
6348     int Elt0 = MaskVals[i*2];
6349     int Elt1 = MaskVals[i*2+1];
6350
6351     // This word of the result is all undef, skip it.
6352     if (Elt0 < 0 && Elt1 < 0)
6353       continue;
6354
6355     // This word of the result is already in the correct place, skip it.
6356     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6357       continue;
6358
6359     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6360     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6361     SDValue InsElt;
6362
6363     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6364     // using a single extract together, load it and store it.
6365     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6366       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6367                            DAG.getIntPtrConstant(Elt1 / 2));
6368       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6369                         DAG.getIntPtrConstant(i));
6370       continue;
6371     }
6372
6373     // If Elt1 is defined, extract it from the appropriate source.  If the
6374     // source byte is not also odd, shift the extracted word left 8 bits
6375     // otherwise clear the bottom 8 bits if we need to do an or.
6376     if (Elt1 >= 0) {
6377       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6378                            DAG.getIntPtrConstant(Elt1 / 2));
6379       if ((Elt1 & 1) == 0)
6380         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6381                              DAG.getConstant(8,
6382                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6383       else if (Elt0 >= 0)
6384         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6385                              DAG.getConstant(0xFF00, MVT::i16));
6386     }
6387     // If Elt0 is defined, extract it from the appropriate source.  If the
6388     // source byte is not also even, shift the extracted word right 8 bits. If
6389     // Elt1 was also defined, OR the extracted values together before
6390     // inserting them in the result.
6391     if (Elt0 >= 0) {
6392       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6393                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6394       if ((Elt0 & 1) != 0)
6395         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6396                               DAG.getConstant(8,
6397                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6398       else if (Elt1 >= 0)
6399         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6400                              DAG.getConstant(0x00FF, MVT::i16));
6401       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6402                          : InsElt0;
6403     }
6404     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6405                        DAG.getIntPtrConstant(i));
6406   }
6407   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6408 }
6409
6410 // v32i8 shuffles - Translate to VPSHUFB if possible.
6411 static
6412 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6413                                  const X86Subtarget *Subtarget,
6414                                  SelectionDAG &DAG) {
6415   MVT VT = SVOp->getValueType(0).getSimpleVT();
6416   SDValue V1 = SVOp->getOperand(0);
6417   SDValue V2 = SVOp->getOperand(1);
6418   SDLoc dl(SVOp);
6419   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6420
6421   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6422   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6423   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6424
6425   // VPSHUFB may be generated if
6426   // (1) one of input vector is undefined or zeroinitializer.
6427   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6428   // And (2) the mask indexes don't cross the 128-bit lane.
6429   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6430       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6431     return SDValue();
6432
6433   if (V1IsAllZero && !V2IsAllZero) {
6434     CommuteVectorShuffleMask(MaskVals, 32);
6435     V1 = V2;
6436   }
6437   SmallVector<SDValue, 32> pshufbMask;
6438   for (unsigned i = 0; i != 32; i++) {
6439     int EltIdx = MaskVals[i];
6440     if (EltIdx < 0 || EltIdx >= 32)
6441       EltIdx = 0x80;
6442     else {
6443       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6444         // Cross lane is not allowed.
6445         return SDValue();
6446       EltIdx &= 0xf;
6447     }
6448     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6449   }
6450   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6451                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6452                                   MVT::v32i8, &pshufbMask[0], 32));
6453 }
6454
6455 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6456 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6457 /// done when every pair / quad of shuffle mask elements point to elements in
6458 /// the right sequence. e.g.
6459 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6460 static
6461 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6462                                  SelectionDAG &DAG) {
6463   MVT VT = SVOp->getValueType(0).getSimpleVT();
6464   SDLoc dl(SVOp);
6465   unsigned NumElems = VT.getVectorNumElements();
6466   MVT NewVT;
6467   unsigned Scale;
6468   switch (VT.SimpleTy) {
6469   default: llvm_unreachable("Unexpected!");
6470   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6471   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6472   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6473   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6474   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6475   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6476   }
6477
6478   SmallVector<int, 8> MaskVec;
6479   for (unsigned i = 0; i != NumElems; i += Scale) {
6480     int StartIdx = -1;
6481     for (unsigned j = 0; j != Scale; ++j) {
6482       int EltIdx = SVOp->getMaskElt(i+j);
6483       if (EltIdx < 0)
6484         continue;
6485       if (StartIdx < 0)
6486         StartIdx = (EltIdx / Scale);
6487       if (EltIdx != (int)(StartIdx*Scale + j))
6488         return SDValue();
6489     }
6490     MaskVec.push_back(StartIdx);
6491   }
6492
6493   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6494   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6495   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6496 }
6497
6498 /// getVZextMovL - Return a zero-extending vector move low node.
6499 ///
6500 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6501                             SDValue SrcOp, SelectionDAG &DAG,
6502                             const X86Subtarget *Subtarget, SDLoc dl) {
6503   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6504     LoadSDNode *LD = NULL;
6505     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6506       LD = dyn_cast<LoadSDNode>(SrcOp);
6507     if (!LD) {
6508       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6509       // instead.
6510       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6511       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6512           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6513           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6514           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6515         // PR2108
6516         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6517         return DAG.getNode(ISD::BITCAST, dl, VT,
6518                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6519                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6520                                                    OpVT,
6521                                                    SrcOp.getOperand(0)
6522                                                           .getOperand(0))));
6523       }
6524     }
6525   }
6526
6527   return DAG.getNode(ISD::BITCAST, dl, VT,
6528                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6529                                  DAG.getNode(ISD::BITCAST, dl,
6530                                              OpVT, SrcOp)));
6531 }
6532
6533 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6534 /// which could not be matched by any known target speficic shuffle
6535 static SDValue
6536 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6537
6538   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6539   if (NewOp.getNode())
6540     return NewOp;
6541
6542   MVT VT = SVOp->getValueType(0).getSimpleVT();
6543
6544   unsigned NumElems = VT.getVectorNumElements();
6545   unsigned NumLaneElems = NumElems / 2;
6546
6547   SDLoc dl(SVOp);
6548   MVT EltVT = VT.getVectorElementType();
6549   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6550   SDValue Output[2];
6551
6552   SmallVector<int, 16> Mask;
6553   for (unsigned l = 0; l < 2; ++l) {
6554     // Build a shuffle mask for the output, discovering on the fly which
6555     // input vectors to use as shuffle operands (recorded in InputUsed).
6556     // If building a suitable shuffle vector proves too hard, then bail
6557     // out with UseBuildVector set.
6558     bool UseBuildVector = false;
6559     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6560     unsigned LaneStart = l * NumLaneElems;
6561     for (unsigned i = 0; i != NumLaneElems; ++i) {
6562       // The mask element.  This indexes into the input.
6563       int Idx = SVOp->getMaskElt(i+LaneStart);
6564       if (Idx < 0) {
6565         // the mask element does not index into any input vector.
6566         Mask.push_back(-1);
6567         continue;
6568       }
6569
6570       // The input vector this mask element indexes into.
6571       int Input = Idx / NumLaneElems;
6572
6573       // Turn the index into an offset from the start of the input vector.
6574       Idx -= Input * NumLaneElems;
6575
6576       // Find or create a shuffle vector operand to hold this input.
6577       unsigned OpNo;
6578       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6579         if (InputUsed[OpNo] == Input)
6580           // This input vector is already an operand.
6581           break;
6582         if (InputUsed[OpNo] < 0) {
6583           // Create a new operand for this input vector.
6584           InputUsed[OpNo] = Input;
6585           break;
6586         }
6587       }
6588
6589       if (OpNo >= array_lengthof(InputUsed)) {
6590         // More than two input vectors used!  Give up on trying to create a
6591         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6592         UseBuildVector = true;
6593         break;
6594       }
6595
6596       // Add the mask index for the new shuffle vector.
6597       Mask.push_back(Idx + OpNo * NumLaneElems);
6598     }
6599
6600     if (UseBuildVector) {
6601       SmallVector<SDValue, 16> SVOps;
6602       for (unsigned i = 0; i != NumLaneElems; ++i) {
6603         // The mask element.  This indexes into the input.
6604         int Idx = SVOp->getMaskElt(i+LaneStart);
6605         if (Idx < 0) {
6606           SVOps.push_back(DAG.getUNDEF(EltVT));
6607           continue;
6608         }
6609
6610         // The input vector this mask element indexes into.
6611         int Input = Idx / NumElems;
6612
6613         // Turn the index into an offset from the start of the input vector.
6614         Idx -= Input * NumElems;
6615
6616         // Extract the vector element by hand.
6617         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6618                                     SVOp->getOperand(Input),
6619                                     DAG.getIntPtrConstant(Idx)));
6620       }
6621
6622       // Construct the output using a BUILD_VECTOR.
6623       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6624                               SVOps.size());
6625     } else if (InputUsed[0] < 0) {
6626       // No input vectors were used! The result is undefined.
6627       Output[l] = DAG.getUNDEF(NVT);
6628     } else {
6629       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6630                                         (InputUsed[0] % 2) * NumLaneElems,
6631                                         DAG, dl);
6632       // If only one input was used, use an undefined vector for the other.
6633       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6634         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6635                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6636       // At least one input vector was used. Create a new shuffle vector.
6637       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6638     }
6639
6640     Mask.clear();
6641   }
6642
6643   // Concatenate the result back
6644   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6645 }
6646
6647 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6648 /// 4 elements, and match them with several different shuffle types.
6649 static SDValue
6650 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6651   SDValue V1 = SVOp->getOperand(0);
6652   SDValue V2 = SVOp->getOperand(1);
6653   SDLoc dl(SVOp);
6654   MVT VT = SVOp->getValueType(0).getSimpleVT();
6655
6656   assert(VT.is128BitVector() && "Unsupported vector size");
6657
6658   std::pair<int, int> Locs[4];
6659   int Mask1[] = { -1, -1, -1, -1 };
6660   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6661
6662   unsigned NumHi = 0;
6663   unsigned NumLo = 0;
6664   for (unsigned i = 0; i != 4; ++i) {
6665     int Idx = PermMask[i];
6666     if (Idx < 0) {
6667       Locs[i] = std::make_pair(-1, -1);
6668     } else {
6669       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6670       if (Idx < 4) {
6671         Locs[i] = std::make_pair(0, NumLo);
6672         Mask1[NumLo] = Idx;
6673         NumLo++;
6674       } else {
6675         Locs[i] = std::make_pair(1, NumHi);
6676         if (2+NumHi < 4)
6677           Mask1[2+NumHi] = Idx;
6678         NumHi++;
6679       }
6680     }
6681   }
6682
6683   if (NumLo <= 2 && NumHi <= 2) {
6684     // If no more than two elements come from either vector. This can be
6685     // implemented with two shuffles. First shuffle gather the elements.
6686     // The second shuffle, which takes the first shuffle as both of its
6687     // vector operands, put the elements into the right order.
6688     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6689
6690     int Mask2[] = { -1, -1, -1, -1 };
6691
6692     for (unsigned i = 0; i != 4; ++i)
6693       if (Locs[i].first != -1) {
6694         unsigned Idx = (i < 2) ? 0 : 4;
6695         Idx += Locs[i].first * 2 + Locs[i].second;
6696         Mask2[i] = Idx;
6697       }
6698
6699     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6700   }
6701
6702   if (NumLo == 3 || NumHi == 3) {
6703     // Otherwise, we must have three elements from one vector, call it X, and
6704     // one element from the other, call it Y.  First, use a shufps to build an
6705     // intermediate vector with the one element from Y and the element from X
6706     // that will be in the same half in the final destination (the indexes don't
6707     // matter). Then, use a shufps to build the final vector, taking the half
6708     // containing the element from Y from the intermediate, and the other half
6709     // from X.
6710     if (NumHi == 3) {
6711       // Normalize it so the 3 elements come from V1.
6712       CommuteVectorShuffleMask(PermMask, 4);
6713       std::swap(V1, V2);
6714     }
6715
6716     // Find the element from V2.
6717     unsigned HiIndex;
6718     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6719       int Val = PermMask[HiIndex];
6720       if (Val < 0)
6721         continue;
6722       if (Val >= 4)
6723         break;
6724     }
6725
6726     Mask1[0] = PermMask[HiIndex];
6727     Mask1[1] = -1;
6728     Mask1[2] = PermMask[HiIndex^1];
6729     Mask1[3] = -1;
6730     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6731
6732     if (HiIndex >= 2) {
6733       Mask1[0] = PermMask[0];
6734       Mask1[1] = PermMask[1];
6735       Mask1[2] = HiIndex & 1 ? 6 : 4;
6736       Mask1[3] = HiIndex & 1 ? 4 : 6;
6737       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6738     }
6739
6740     Mask1[0] = HiIndex & 1 ? 2 : 0;
6741     Mask1[1] = HiIndex & 1 ? 0 : 2;
6742     Mask1[2] = PermMask[2];
6743     Mask1[3] = PermMask[3];
6744     if (Mask1[2] >= 0)
6745       Mask1[2] += 4;
6746     if (Mask1[3] >= 0)
6747       Mask1[3] += 4;
6748     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6749   }
6750
6751   // Break it into (shuffle shuffle_hi, shuffle_lo).
6752   int LoMask[] = { -1, -1, -1, -1 };
6753   int HiMask[] = { -1, -1, -1, -1 };
6754
6755   int *MaskPtr = LoMask;
6756   unsigned MaskIdx = 0;
6757   unsigned LoIdx = 0;
6758   unsigned HiIdx = 2;
6759   for (unsigned i = 0; i != 4; ++i) {
6760     if (i == 2) {
6761       MaskPtr = HiMask;
6762       MaskIdx = 1;
6763       LoIdx = 0;
6764       HiIdx = 2;
6765     }
6766     int Idx = PermMask[i];
6767     if (Idx < 0) {
6768       Locs[i] = std::make_pair(-1, -1);
6769     } else if (Idx < 4) {
6770       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6771       MaskPtr[LoIdx] = Idx;
6772       LoIdx++;
6773     } else {
6774       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6775       MaskPtr[HiIdx] = Idx;
6776       HiIdx++;
6777     }
6778   }
6779
6780   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6781   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6782   int MaskOps[] = { -1, -1, -1, -1 };
6783   for (unsigned i = 0; i != 4; ++i)
6784     if (Locs[i].first != -1)
6785       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6786   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6787 }
6788
6789 static bool MayFoldVectorLoad(SDValue V) {
6790   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6791     V = V.getOperand(0);
6792
6793   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6794     V = V.getOperand(0);
6795   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6796       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6797     // BUILD_VECTOR (load), undef
6798     V = V.getOperand(0);
6799
6800   return MayFoldLoad(V);
6801 }
6802
6803 static
6804 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6805   EVT VT = Op.getValueType();
6806
6807   // Canonizalize to v2f64.
6808   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6809   return DAG.getNode(ISD::BITCAST, dl, VT,
6810                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6811                                           V1, DAG));
6812 }
6813
6814 static
6815 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6816                         bool HasSSE2) {
6817   SDValue V1 = Op.getOperand(0);
6818   SDValue V2 = Op.getOperand(1);
6819   EVT VT = Op.getValueType();
6820
6821   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6822
6823   if (HasSSE2 && VT == MVT::v2f64)
6824     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6825
6826   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6827   return DAG.getNode(ISD::BITCAST, dl, VT,
6828                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6829                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6830                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6831 }
6832
6833 static
6834 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6835   SDValue V1 = Op.getOperand(0);
6836   SDValue V2 = Op.getOperand(1);
6837   EVT VT = Op.getValueType();
6838
6839   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6840          "unsupported shuffle type");
6841
6842   if (V2.getOpcode() == ISD::UNDEF)
6843     V2 = V1;
6844
6845   // v4i32 or v4f32
6846   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6847 }
6848
6849 static
6850 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6851   SDValue V1 = Op.getOperand(0);
6852   SDValue V2 = Op.getOperand(1);
6853   EVT VT = Op.getValueType();
6854   unsigned NumElems = VT.getVectorNumElements();
6855
6856   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6857   // operand of these instructions is only memory, so check if there's a
6858   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6859   // same masks.
6860   bool CanFoldLoad = false;
6861
6862   // Trivial case, when V2 comes from a load.
6863   if (MayFoldVectorLoad(V2))
6864     CanFoldLoad = true;
6865
6866   // When V1 is a load, it can be folded later into a store in isel, example:
6867   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6868   //    turns into:
6869   //  (MOVLPSmr addr:$src1, VR128:$src2)
6870   // So, recognize this potential and also use MOVLPS or MOVLPD
6871   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6872     CanFoldLoad = true;
6873
6874   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6875   if (CanFoldLoad) {
6876     if (HasSSE2 && NumElems == 2)
6877       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6878
6879     if (NumElems == 4)
6880       // If we don't care about the second element, proceed to use movss.
6881       if (SVOp->getMaskElt(1) != -1)
6882         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6883   }
6884
6885   // movl and movlp will both match v2i64, but v2i64 is never matched by
6886   // movl earlier because we make it strict to avoid messing with the movlp load
6887   // folding logic (see the code above getMOVLP call). Match it here then,
6888   // this is horrible, but will stay like this until we move all shuffle
6889   // matching to x86 specific nodes. Note that for the 1st condition all
6890   // types are matched with movsd.
6891   if (HasSSE2) {
6892     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6893     // as to remove this logic from here, as much as possible
6894     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6895       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6896     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6897   }
6898
6899   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6900
6901   // Invert the operand order and use SHUFPS to match it.
6902   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6903                               getShuffleSHUFImmediate(SVOp), DAG);
6904 }
6905
6906 // Reduce a vector shuffle to zext.
6907 SDValue
6908 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6909   // PMOVZX is only available from SSE41.
6910   if (!Subtarget->hasSSE41())
6911     return SDValue();
6912
6913   EVT VT = Op.getValueType();
6914
6915   // Only AVX2 support 256-bit vector integer extending.
6916   if (!Subtarget->hasInt256() && VT.is256BitVector())
6917     return SDValue();
6918
6919   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6920   SDLoc DL(Op);
6921   SDValue V1 = Op.getOperand(0);
6922   SDValue V2 = Op.getOperand(1);
6923   unsigned NumElems = VT.getVectorNumElements();
6924
6925   // Extending is an unary operation and the element type of the source vector
6926   // won't be equal to or larger than i64.
6927   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6928       VT.getVectorElementType() == MVT::i64)
6929     return SDValue();
6930
6931   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6932   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6933   while ((1U << Shift) < NumElems) {
6934     if (SVOp->getMaskElt(1U << Shift) == 1)
6935       break;
6936     Shift += 1;
6937     // The maximal ratio is 8, i.e. from i8 to i64.
6938     if (Shift > 3)
6939       return SDValue();
6940   }
6941
6942   // Check the shuffle mask.
6943   unsigned Mask = (1U << Shift) - 1;
6944   for (unsigned i = 0; i != NumElems; ++i) {
6945     int EltIdx = SVOp->getMaskElt(i);
6946     if ((i & Mask) != 0 && EltIdx != -1)
6947       return SDValue();
6948     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6949       return SDValue();
6950   }
6951
6952   LLVMContext *Context = DAG.getContext();
6953   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6954   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6955   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6956
6957   if (!isTypeLegal(NVT))
6958     return SDValue();
6959
6960   // Simplify the operand as it's prepared to be fed into shuffle.
6961   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6962   if (V1.getOpcode() == ISD::BITCAST &&
6963       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6964       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6965       V1.getOperand(0)
6966         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6967     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6968     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6969     ConstantSDNode *CIdx =
6970       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6971     // If it's foldable, i.e. normal load with single use, we will let code
6972     // selection to fold it. Otherwise, we will short the conversion sequence.
6973     if (CIdx && CIdx->getZExtValue() == 0 &&
6974         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6975       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6976         // The "ext_vec_elt" node is wider than the result node.
6977         // In this case we should extract subvector from V.
6978         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6979         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6980         EVT FullVT = V.getValueType();
6981         EVT SubVecVT = EVT::getVectorVT(*Context,
6982                                         FullVT.getVectorElementType(),
6983                                         FullVT.getVectorNumElements()/Ratio);
6984         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6985                         DAG.getIntPtrConstant(0));
6986       }
6987       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6988     }
6989   }
6990
6991   return DAG.getNode(ISD::BITCAST, DL, VT,
6992                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6993 }
6994
6995 SDValue
6996 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6997   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6998   MVT VT = Op.getValueType().getSimpleVT();
6999   SDLoc dl(Op);
7000   SDValue V1 = Op.getOperand(0);
7001   SDValue V2 = Op.getOperand(1);
7002
7003   if (isZeroShuffle(SVOp))
7004     return getZeroVector(VT, Subtarget, DAG, dl);
7005
7006   // Handle splat operations
7007   if (SVOp->isSplat()) {
7008     // Use vbroadcast whenever the splat comes from a foldable load
7009     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
7010     if (Broadcast.getNode())
7011       return Broadcast;
7012   }
7013
7014   // Check integer expanding shuffles.
7015   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
7016   if (NewOp.getNode())
7017     return NewOp;
7018
7019   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7020   // do it!
7021   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7022       VT == MVT::v16i16 || VT == MVT::v32i8) {
7023     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7024     if (NewOp.getNode())
7025       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7026   } else if ((VT == MVT::v4i32 ||
7027              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7028     // FIXME: Figure out a cleaner way to do this.
7029     // Try to make use of movq to zero out the top part.
7030     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7031       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7032       if (NewOp.getNode()) {
7033         MVT NewVT = NewOp.getValueType().getSimpleVT();
7034         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7035                                NewVT, true, false))
7036           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7037                               DAG, Subtarget, dl);
7038       }
7039     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7040       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7041       if (NewOp.getNode()) {
7042         MVT NewVT = NewOp.getValueType().getSimpleVT();
7043         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7044           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7045                               DAG, Subtarget, dl);
7046       }
7047     }
7048   }
7049   return SDValue();
7050 }
7051
7052 SDValue
7053 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7054   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7055   SDValue V1 = Op.getOperand(0);
7056   SDValue V2 = Op.getOperand(1);
7057   MVT VT = Op.getValueType().getSimpleVT();
7058   SDLoc dl(Op);
7059   unsigned NumElems = VT.getVectorNumElements();
7060   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7061   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7062   bool V1IsSplat = false;
7063   bool V2IsSplat = false;
7064   bool HasSSE2 = Subtarget->hasSSE2();
7065   bool HasFp256    = Subtarget->hasFp256();
7066   bool HasInt256   = Subtarget->hasInt256();
7067   MachineFunction &MF = DAG.getMachineFunction();
7068   bool OptForSize = MF.getFunction()->getAttributes().
7069     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7070
7071   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7072
7073   if (V1IsUndef && V2IsUndef)
7074     return DAG.getUNDEF(VT);
7075
7076   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7077
7078   // Vector shuffle lowering takes 3 steps:
7079   //
7080   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7081   //    narrowing and commutation of operands should be handled.
7082   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7083   //    shuffle nodes.
7084   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7085   //    so the shuffle can be broken into other shuffles and the legalizer can
7086   //    try the lowering again.
7087   //
7088   // The general idea is that no vector_shuffle operation should be left to
7089   // be matched during isel, all of them must be converted to a target specific
7090   // node here.
7091
7092   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7093   // narrowing and commutation of operands should be handled. The actual code
7094   // doesn't include all of those, work in progress...
7095   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
7096   if (NewOp.getNode())
7097     return NewOp;
7098
7099   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7100
7101   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7102   // unpckh_undef). Only use pshufd if speed is more important than size.
7103   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7104     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7105   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7106     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7107
7108   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7109       V2IsUndef && MayFoldVectorLoad(V1))
7110     return getMOVDDup(Op, dl, V1, DAG);
7111
7112   if (isMOVHLPS_v_undef_Mask(M, VT))
7113     return getMOVHighToLow(Op, dl, DAG);
7114
7115   // Use to match splats
7116   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7117       (VT == MVT::v2f64 || VT == MVT::v2i64))
7118     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7119
7120   if (isPSHUFDMask(M, VT)) {
7121     // The actual implementation will match the mask in the if above and then
7122     // during isel it can match several different instructions, not only pshufd
7123     // as its name says, sad but true, emulate the behavior for now...
7124     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7125       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7126
7127     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7128
7129     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7130       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7131
7132     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7133       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7134                                   DAG);
7135
7136     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7137                                 TargetMask, DAG);
7138   }
7139
7140   if (isPALIGNRMask(M, VT, Subtarget))
7141     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7142                                 getShufflePALIGNRImmediate(SVOp),
7143                                 DAG);
7144
7145   // Check if this can be converted into a logical shift.
7146   bool isLeft = false;
7147   unsigned ShAmt = 0;
7148   SDValue ShVal;
7149   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7150   if (isShift && ShVal.hasOneUse()) {
7151     // If the shifted value has multiple uses, it may be cheaper to use
7152     // v_set0 + movlhps or movhlps, etc.
7153     MVT EltVT = VT.getVectorElementType();
7154     ShAmt *= EltVT.getSizeInBits();
7155     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7156   }
7157
7158   if (isMOVLMask(M, VT)) {
7159     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7160       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7161     if (!isMOVLPMask(M, VT)) {
7162       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7163         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7164
7165       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7166         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7167     }
7168   }
7169
7170   // FIXME: fold these into legal mask.
7171   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7172     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7173
7174   if (isMOVHLPSMask(M, VT))
7175     return getMOVHighToLow(Op, dl, DAG);
7176
7177   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7178     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7179
7180   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7181     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7182
7183   if (isMOVLPMask(M, VT))
7184     return getMOVLP(Op, dl, DAG, HasSSE2);
7185
7186   if (ShouldXformToMOVHLPS(M, VT) ||
7187       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7188     return CommuteVectorShuffle(SVOp, DAG);
7189
7190   if (isShift) {
7191     // No better options. Use a vshldq / vsrldq.
7192     MVT EltVT = VT.getVectorElementType();
7193     ShAmt *= EltVT.getSizeInBits();
7194     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7195   }
7196
7197   bool Commuted = false;
7198   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7199   // 1,1,1,1 -> v8i16 though.
7200   V1IsSplat = isSplatVector(V1.getNode());
7201   V2IsSplat = isSplatVector(V2.getNode());
7202
7203   // Canonicalize the splat or undef, if present, to be on the RHS.
7204   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7205     CommuteVectorShuffleMask(M, NumElems);
7206     std::swap(V1, V2);
7207     std::swap(V1IsSplat, V2IsSplat);
7208     Commuted = true;
7209   }
7210
7211   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7212     // Shuffling low element of v1 into undef, just return v1.
7213     if (V2IsUndef)
7214       return V1;
7215     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7216     // the instruction selector will not match, so get a canonical MOVL with
7217     // swapped operands to undo the commute.
7218     return getMOVL(DAG, dl, VT, V2, V1);
7219   }
7220
7221   if (isUNPCKLMask(M, VT, HasInt256))
7222     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7223
7224   if (isUNPCKHMask(M, VT, HasInt256))
7225     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7226
7227   if (V2IsSplat) {
7228     // Normalize mask so all entries that point to V2 points to its first
7229     // element then try to match unpck{h|l} again. If match, return a
7230     // new vector_shuffle with the corrected mask.p
7231     SmallVector<int, 8> NewMask(M.begin(), M.end());
7232     NormalizeMask(NewMask, NumElems);
7233     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7234       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7235     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7236       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7237   }
7238
7239   if (Commuted) {
7240     // Commute is back and try unpck* again.
7241     // FIXME: this seems wrong.
7242     CommuteVectorShuffleMask(M, NumElems);
7243     std::swap(V1, V2);
7244     std::swap(V1IsSplat, V2IsSplat);
7245     Commuted = false;
7246
7247     if (isUNPCKLMask(M, VT, HasInt256))
7248       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7249
7250     if (isUNPCKHMask(M, VT, HasInt256))
7251       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7252   }
7253
7254   // Normalize the node to match x86 shuffle ops if needed
7255   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7256     return CommuteVectorShuffle(SVOp, DAG);
7257
7258   // The checks below are all present in isShuffleMaskLegal, but they are
7259   // inlined here right now to enable us to directly emit target specific
7260   // nodes, and remove one by one until they don't return Op anymore.
7261
7262   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7263       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7264     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7265       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7266   }
7267
7268   if (isPSHUFHWMask(M, VT, HasInt256))
7269     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7270                                 getShufflePSHUFHWImmediate(SVOp),
7271                                 DAG);
7272
7273   if (isPSHUFLWMask(M, VT, HasInt256))
7274     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7275                                 getShufflePSHUFLWImmediate(SVOp),
7276                                 DAG);
7277
7278   if (isSHUFPMask(M, VT, HasFp256))
7279     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7280                                 getShuffleSHUFImmediate(SVOp), DAG);
7281
7282   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7283     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7284   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7285     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7286
7287   //===--------------------------------------------------------------------===//
7288   // Generate target specific nodes for 128 or 256-bit shuffles only
7289   // supported in the AVX instruction set.
7290   //
7291
7292   // Handle VMOVDDUPY permutations
7293   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7294     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7295
7296   // Handle VPERMILPS/D* permutations
7297   if (isVPERMILPMask(M, VT, HasFp256)) {
7298     if (HasInt256 && VT == MVT::v8i32)
7299       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7300                                   getShuffleSHUFImmediate(SVOp), DAG);
7301     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7302                                 getShuffleSHUFImmediate(SVOp), DAG);
7303   }
7304
7305   // Handle VPERM2F128/VPERM2I128 permutations
7306   if (isVPERM2X128Mask(M, VT, HasFp256))
7307     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7308                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7309
7310   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7311   if (BlendOp.getNode())
7312     return BlendOp;
7313
7314   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7315     SmallVector<SDValue, 8> permclMask;
7316     for (unsigned i = 0; i != 8; ++i) {
7317       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7318     }
7319     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7320                                &permclMask[0], 8);
7321     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7322     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7323                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7324   }
7325
7326   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7327     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7328                                 getShuffleCLImmediate(SVOp), DAG);
7329
7330   //===--------------------------------------------------------------------===//
7331   // Since no target specific shuffle was selected for this generic one,
7332   // lower it into other known shuffles. FIXME: this isn't true yet, but
7333   // this is the plan.
7334   //
7335
7336   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7337   if (VT == MVT::v8i16) {
7338     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7339     if (NewOp.getNode())
7340       return NewOp;
7341   }
7342
7343   if (VT == MVT::v16i8) {
7344     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7345     if (NewOp.getNode())
7346       return NewOp;
7347   }
7348
7349   if (VT == MVT::v32i8) {
7350     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7351     if (NewOp.getNode())
7352       return NewOp;
7353   }
7354
7355   // Handle all 128-bit wide vectors with 4 elements, and match them with
7356   // several different shuffle types.
7357   if (NumElems == 4 && VT.is128BitVector())
7358     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7359
7360   // Handle general 256-bit shuffles
7361   if (VT.is256BitVector())
7362     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7363
7364   return SDValue();
7365 }
7366
7367 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7368   MVT VT = Op.getValueType().getSimpleVT();
7369   SDLoc dl(Op);
7370
7371   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7372     return SDValue();
7373
7374   if (VT.getSizeInBits() == 8) {
7375     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7376                                   Op.getOperand(0), Op.getOperand(1));
7377     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7378                                   DAG.getValueType(VT));
7379     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7380   }
7381
7382   if (VT.getSizeInBits() == 16) {
7383     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7384     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7385     if (Idx == 0)
7386       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7387                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7388                                      DAG.getNode(ISD::BITCAST, dl,
7389                                                  MVT::v4i32,
7390                                                  Op.getOperand(0)),
7391                                      Op.getOperand(1)));
7392     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7393                                   Op.getOperand(0), Op.getOperand(1));
7394     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7395                                   DAG.getValueType(VT));
7396     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7397   }
7398
7399   if (VT == MVT::f32) {
7400     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7401     // the result back to FR32 register. It's only worth matching if the
7402     // result has a single use which is a store or a bitcast to i32.  And in
7403     // the case of a store, it's not worth it if the index is a constant 0,
7404     // because a MOVSSmr can be used instead, which is smaller and faster.
7405     if (!Op.hasOneUse())
7406       return SDValue();
7407     SDNode *User = *Op.getNode()->use_begin();
7408     if ((User->getOpcode() != ISD::STORE ||
7409          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7410           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7411         (User->getOpcode() != ISD::BITCAST ||
7412          User->getValueType(0) != MVT::i32))
7413       return SDValue();
7414     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7415                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7416                                               Op.getOperand(0)),
7417                                               Op.getOperand(1));
7418     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7419   }
7420
7421   if (VT == MVT::i32 || VT == MVT::i64) {
7422     // ExtractPS/pextrq works with constant index.
7423     if (isa<ConstantSDNode>(Op.getOperand(1)))
7424       return Op;
7425   }
7426   return SDValue();
7427 }
7428
7429 SDValue
7430 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7431                                            SelectionDAG &DAG) const {
7432   SDLoc dl(Op);
7433   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7434     return SDValue();
7435
7436   SDValue Vec = Op.getOperand(0);
7437   MVT VecVT = Vec.getValueType().getSimpleVT();
7438
7439   // If this is a 256-bit vector result, first extract the 128-bit vector and
7440   // then extract the element from the 128-bit vector.
7441   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7442     SDValue Idx = Op.getOperand(1);
7443     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7444
7445     // Get the 128-bit vector.
7446     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7447     EVT EltVT = VecVT.getVectorElementType();
7448
7449     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7450
7451     //if (IdxVal >= NumElems/2)
7452     //  IdxVal -= NumElems/2;
7453     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7454     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7455                        DAG.getConstant(IdxVal, MVT::i32));
7456   }
7457
7458   assert(VecVT.is128BitVector() && "Unexpected vector length");
7459
7460   if (Subtarget->hasSSE41()) {
7461     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7462     if (Res.getNode())
7463       return Res;
7464   }
7465
7466   MVT VT = Op.getValueType().getSimpleVT();
7467   // TODO: handle v16i8.
7468   if (VT.getSizeInBits() == 16) {
7469     SDValue Vec = Op.getOperand(0);
7470     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7471     if (Idx == 0)
7472       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7473                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7474                                      DAG.getNode(ISD::BITCAST, dl,
7475                                                  MVT::v4i32, Vec),
7476                                      Op.getOperand(1)));
7477     // Transform it so it match pextrw which produces a 32-bit result.
7478     MVT EltVT = MVT::i32;
7479     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7480                                   Op.getOperand(0), Op.getOperand(1));
7481     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7482                                   DAG.getValueType(VT));
7483     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7484   }
7485
7486   if (VT.getSizeInBits() == 32) {
7487     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7488     if (Idx == 0)
7489       return Op;
7490
7491     // SHUFPS the element to the lowest double word, then movss.
7492     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7493     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7494     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7495                                        DAG.getUNDEF(VVT), Mask);
7496     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7497                        DAG.getIntPtrConstant(0));
7498   }
7499
7500   if (VT.getSizeInBits() == 64) {
7501     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7502     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7503     //        to match extract_elt for f64.
7504     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7505     if (Idx == 0)
7506       return Op;
7507
7508     // UNPCKHPD the element to the lowest double word, then movsd.
7509     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7510     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7511     int Mask[2] = { 1, -1 };
7512     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7513     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7514                                        DAG.getUNDEF(VVT), Mask);
7515     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7516                        DAG.getIntPtrConstant(0));
7517   }
7518
7519   return SDValue();
7520 }
7521
7522 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7523   MVT VT = Op.getValueType().getSimpleVT();
7524   MVT EltVT = VT.getVectorElementType();
7525   SDLoc dl(Op);
7526
7527   SDValue N0 = Op.getOperand(0);
7528   SDValue N1 = Op.getOperand(1);
7529   SDValue N2 = Op.getOperand(2);
7530
7531   if (!VT.is128BitVector())
7532     return SDValue();
7533
7534   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7535       isa<ConstantSDNode>(N2)) {
7536     unsigned Opc;
7537     if (VT == MVT::v8i16)
7538       Opc = X86ISD::PINSRW;
7539     else if (VT == MVT::v16i8)
7540       Opc = X86ISD::PINSRB;
7541     else
7542       Opc = X86ISD::PINSRB;
7543
7544     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7545     // argument.
7546     if (N1.getValueType() != MVT::i32)
7547       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7548     if (N2.getValueType() != MVT::i32)
7549       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7550     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7551   }
7552
7553   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7554     // Bits [7:6] of the constant are the source select.  This will always be
7555     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7556     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7557     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7558     // Bits [5:4] of the constant are the destination select.  This is the
7559     //  value of the incoming immediate.
7560     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7561     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7562     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7563     // Create this as a scalar to vector..
7564     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7565     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7566   }
7567
7568   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7569     // PINSR* works with constant index.
7570     return Op;
7571   }
7572   return SDValue();
7573 }
7574
7575 SDValue
7576 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7577   MVT VT = Op.getValueType().getSimpleVT();
7578   MVT EltVT = VT.getVectorElementType();
7579
7580   SDLoc dl(Op);
7581   SDValue N0 = Op.getOperand(0);
7582   SDValue N1 = Op.getOperand(1);
7583   SDValue N2 = Op.getOperand(2);
7584
7585   // If this is a 256-bit vector result, first extract the 128-bit vector,
7586   // insert the element into the extracted half and then place it back.
7587   if (VT.is256BitVector() || VT.is512BitVector()) {
7588     if (!isa<ConstantSDNode>(N2))
7589       return SDValue();
7590
7591     // Get the desired 128-bit vector half.
7592     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7593     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7594
7595     // Insert the element into the desired half.
7596     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7597     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7598
7599     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7600                     DAG.getConstant(IdxIn128, MVT::i32));
7601
7602     // Insert the changed part back to the 256-bit vector
7603     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7604   }
7605
7606   if (Subtarget->hasSSE41())
7607     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7608
7609   if (EltVT == MVT::i8)
7610     return SDValue();
7611
7612   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7613     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7614     // as its second argument.
7615     if (N1.getValueType() != MVT::i32)
7616       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7617     if (N2.getValueType() != MVT::i32)
7618       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7619     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7620   }
7621   return SDValue();
7622 }
7623
7624 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7625   LLVMContext *Context = DAG.getContext();
7626   SDLoc dl(Op);
7627   MVT OpVT = Op.getValueType().getSimpleVT();
7628
7629   // If this is a 256-bit vector result, first insert into a 128-bit
7630   // vector and then insert into the 256-bit vector.
7631   if (!OpVT.is128BitVector()) {
7632     // Insert into a 128-bit vector.
7633     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7634     EVT VT128 = EVT::getVectorVT(*Context,
7635                                  OpVT.getVectorElementType(),
7636                                  OpVT.getVectorNumElements() / SizeFactor);
7637
7638     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7639
7640     // Insert the 128-bit vector.
7641     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7642   }
7643
7644   if (OpVT == MVT::v1i64 &&
7645       Op.getOperand(0).getValueType() == MVT::i64)
7646     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7647
7648   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7649   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7650   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7651                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7652 }
7653
7654 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7655 // a simple subregister reference or explicit instructions to grab
7656 // upper bits of a vector.
7657 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7658                                       SelectionDAG &DAG) {
7659   SDLoc dl(Op);
7660   SDValue In =  Op.getOperand(0);
7661   SDValue Idx = Op.getOperand(1);
7662   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7663   EVT ResVT   = Op.getValueType();
7664   EVT InVT    = In.getValueType();
7665
7666   if (Subtarget->hasFp256()) {
7667     if (ResVT.is128BitVector() &&
7668         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7669         isa<ConstantSDNode>(Idx)) {
7670       return Extract128BitVector(In, IdxVal, DAG, dl);
7671     }
7672     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7673         isa<ConstantSDNode>(Idx)) {
7674       return Extract256BitVector(In, IdxVal, DAG, dl);
7675     }
7676   }
7677   return SDValue();
7678 }
7679
7680 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7681 // simple superregister reference or explicit instructions to insert
7682 // the upper bits of a vector.
7683 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7684                                      SelectionDAG &DAG) {
7685   if (Subtarget->hasFp256()) {
7686     SDLoc dl(Op.getNode());
7687     SDValue Vec = Op.getNode()->getOperand(0);
7688     SDValue SubVec = Op.getNode()->getOperand(1);
7689     SDValue Idx = Op.getNode()->getOperand(2);
7690
7691     if ((Op.getNode()->getValueType(0).is256BitVector() ||
7692          Op.getNode()->getValueType(0).is512BitVector()) &&
7693         SubVec.getNode()->getValueType(0).is128BitVector() &&
7694         isa<ConstantSDNode>(Idx)) {
7695       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7696       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7697     }
7698
7699     if (Op.getNode()->getValueType(0).is512BitVector() &&
7700         SubVec.getNode()->getValueType(0).is256BitVector() &&
7701         isa<ConstantSDNode>(Idx)) {
7702       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7703       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7704     }
7705   }
7706   return SDValue();
7707 }
7708
7709 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7710 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7711 // one of the above mentioned nodes. It has to be wrapped because otherwise
7712 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7713 // be used to form addressing mode. These wrapped nodes will be selected
7714 // into MOV32ri.
7715 SDValue
7716 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7717   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7718
7719   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7720   // global base reg.
7721   unsigned char OpFlag = 0;
7722   unsigned WrapperKind = X86ISD::Wrapper;
7723   CodeModel::Model M = getTargetMachine().getCodeModel();
7724
7725   if (Subtarget->isPICStyleRIPRel() &&
7726       (M == CodeModel::Small || M == CodeModel::Kernel))
7727     WrapperKind = X86ISD::WrapperRIP;
7728   else if (Subtarget->isPICStyleGOT())
7729     OpFlag = X86II::MO_GOTOFF;
7730   else if (Subtarget->isPICStyleStubPIC())
7731     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7732
7733   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7734                                              CP->getAlignment(),
7735                                              CP->getOffset(), OpFlag);
7736   SDLoc DL(CP);
7737   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7738   // With PIC, the address is actually $g + Offset.
7739   if (OpFlag) {
7740     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7741                          DAG.getNode(X86ISD::GlobalBaseReg,
7742                                      SDLoc(), getPointerTy()),
7743                          Result);
7744   }
7745
7746   return Result;
7747 }
7748
7749 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7750   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7751
7752   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7753   // global base reg.
7754   unsigned char OpFlag = 0;
7755   unsigned WrapperKind = X86ISD::Wrapper;
7756   CodeModel::Model M = getTargetMachine().getCodeModel();
7757
7758   if (Subtarget->isPICStyleRIPRel() &&
7759       (M == CodeModel::Small || M == CodeModel::Kernel))
7760     WrapperKind = X86ISD::WrapperRIP;
7761   else if (Subtarget->isPICStyleGOT())
7762     OpFlag = X86II::MO_GOTOFF;
7763   else if (Subtarget->isPICStyleStubPIC())
7764     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7765
7766   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7767                                           OpFlag);
7768   SDLoc DL(JT);
7769   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7770
7771   // With PIC, the address is actually $g + Offset.
7772   if (OpFlag)
7773     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7774                          DAG.getNode(X86ISD::GlobalBaseReg,
7775                                      SDLoc(), getPointerTy()),
7776                          Result);
7777
7778   return Result;
7779 }
7780
7781 SDValue
7782 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7783   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7784
7785   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7786   // global base reg.
7787   unsigned char OpFlag = 0;
7788   unsigned WrapperKind = X86ISD::Wrapper;
7789   CodeModel::Model M = getTargetMachine().getCodeModel();
7790
7791   if (Subtarget->isPICStyleRIPRel() &&
7792       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7793     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7794       OpFlag = X86II::MO_GOTPCREL;
7795     WrapperKind = X86ISD::WrapperRIP;
7796   } else if (Subtarget->isPICStyleGOT()) {
7797     OpFlag = X86II::MO_GOT;
7798   } else if (Subtarget->isPICStyleStubPIC()) {
7799     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7800   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7801     OpFlag = X86II::MO_DARWIN_NONLAZY;
7802   }
7803
7804   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7805
7806   SDLoc DL(Op);
7807   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7808
7809   // With PIC, the address is actually $g + Offset.
7810   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7811       !Subtarget->is64Bit()) {
7812     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7813                          DAG.getNode(X86ISD::GlobalBaseReg,
7814                                      SDLoc(), getPointerTy()),
7815                          Result);
7816   }
7817
7818   // For symbols that require a load from a stub to get the address, emit the
7819   // load.
7820   if (isGlobalStubReference(OpFlag))
7821     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7822                          MachinePointerInfo::getGOT(), false, false, false, 0);
7823
7824   return Result;
7825 }
7826
7827 SDValue
7828 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7829   // Create the TargetBlockAddressAddress node.
7830   unsigned char OpFlags =
7831     Subtarget->ClassifyBlockAddressReference();
7832   CodeModel::Model M = getTargetMachine().getCodeModel();
7833   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7834   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7835   SDLoc dl(Op);
7836   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7837                                              OpFlags);
7838
7839   if (Subtarget->isPICStyleRIPRel() &&
7840       (M == CodeModel::Small || M == CodeModel::Kernel))
7841     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7842   else
7843     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7844
7845   // With PIC, the address is actually $g + Offset.
7846   if (isGlobalRelativeToPICBase(OpFlags)) {
7847     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7848                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7849                          Result);
7850   }
7851
7852   return Result;
7853 }
7854
7855 SDValue
7856 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7857                                       int64_t Offset, SelectionDAG &DAG) const {
7858   // Create the TargetGlobalAddress node, folding in the constant
7859   // offset if it is legal.
7860   unsigned char OpFlags =
7861     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7862   CodeModel::Model M = getTargetMachine().getCodeModel();
7863   SDValue Result;
7864   if (OpFlags == X86II::MO_NO_FLAG &&
7865       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7866     // A direct static reference to a global.
7867     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7868     Offset = 0;
7869   } else {
7870     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7871   }
7872
7873   if (Subtarget->isPICStyleRIPRel() &&
7874       (M == CodeModel::Small || M == CodeModel::Kernel))
7875     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7876   else
7877     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7878
7879   // With PIC, the address is actually $g + Offset.
7880   if (isGlobalRelativeToPICBase(OpFlags)) {
7881     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7882                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7883                          Result);
7884   }
7885
7886   // For globals that require a load from a stub to get the address, emit the
7887   // load.
7888   if (isGlobalStubReference(OpFlags))
7889     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7890                          MachinePointerInfo::getGOT(), false, false, false, 0);
7891
7892   // If there was a non-zero offset that we didn't fold, create an explicit
7893   // addition for it.
7894   if (Offset != 0)
7895     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7896                          DAG.getConstant(Offset, getPointerTy()));
7897
7898   return Result;
7899 }
7900
7901 SDValue
7902 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7903   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7904   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7905   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
7906 }
7907
7908 static SDValue
7909 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7910            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7911            unsigned char OperandFlags, bool LocalDynamic = false) {
7912   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7913   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7914   SDLoc dl(GA);
7915   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7916                                            GA->getValueType(0),
7917                                            GA->getOffset(),
7918                                            OperandFlags);
7919
7920   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7921                                            : X86ISD::TLSADDR;
7922
7923   if (InFlag) {
7924     SDValue Ops[] = { Chain,  TGA, *InFlag };
7925     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7926   } else {
7927     SDValue Ops[]  = { Chain, TGA };
7928     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7929   }
7930
7931   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7932   MFI->setAdjustsStack(true);
7933
7934   SDValue Flag = Chain.getValue(1);
7935   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7936 }
7937
7938 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7939 static SDValue
7940 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7941                                 const EVT PtrVT) {
7942   SDValue InFlag;
7943   SDLoc dl(GA);  // ? function entry point might be better
7944   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7945                                    DAG.getNode(X86ISD::GlobalBaseReg,
7946                                                SDLoc(), PtrVT), InFlag);
7947   InFlag = Chain.getValue(1);
7948
7949   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7950 }
7951
7952 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7953 static SDValue
7954 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7955                                 const EVT PtrVT) {
7956   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7957                     X86::RAX, X86II::MO_TLSGD);
7958 }
7959
7960 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7961                                            SelectionDAG &DAG,
7962                                            const EVT PtrVT,
7963                                            bool is64Bit) {
7964   SDLoc dl(GA);
7965
7966   // Get the start address of the TLS block for this module.
7967   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7968       .getInfo<X86MachineFunctionInfo>();
7969   MFI->incNumLocalDynamicTLSAccesses();
7970
7971   SDValue Base;
7972   if (is64Bit) {
7973     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7974                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7975   } else {
7976     SDValue InFlag;
7977     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7978         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
7979     InFlag = Chain.getValue(1);
7980     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7981                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7982   }
7983
7984   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7985   // of Base.
7986
7987   // Build x@dtpoff.
7988   unsigned char OperandFlags = X86II::MO_DTPOFF;
7989   unsigned WrapperKind = X86ISD::Wrapper;
7990   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7991                                            GA->getValueType(0),
7992                                            GA->getOffset(), OperandFlags);
7993   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7994
7995   // Add x@dtpoff with the base.
7996   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7997 }
7998
7999 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8000 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8001                                    const EVT PtrVT, TLSModel::Model model,
8002                                    bool is64Bit, bool isPIC) {
8003   SDLoc dl(GA);
8004
8005   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8006   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8007                                                          is64Bit ? 257 : 256));
8008
8009   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
8010                                       DAG.getIntPtrConstant(0),
8011                                       MachinePointerInfo(Ptr),
8012                                       false, false, false, 0);
8013
8014   unsigned char OperandFlags = 0;
8015   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8016   // initialexec.
8017   unsigned WrapperKind = X86ISD::Wrapper;
8018   if (model == TLSModel::LocalExec) {
8019     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8020   } else if (model == TLSModel::InitialExec) {
8021     if (is64Bit) {
8022       OperandFlags = X86II::MO_GOTTPOFF;
8023       WrapperKind = X86ISD::WrapperRIP;
8024     } else {
8025       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8026     }
8027   } else {
8028     llvm_unreachable("Unexpected model");
8029   }
8030
8031   // emit "addl x@ntpoff,%eax" (local exec)
8032   // or "addl x@indntpoff,%eax" (initial exec)
8033   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8034   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8035                                            GA->getValueType(0),
8036                                            GA->getOffset(), OperandFlags);
8037   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8038
8039   if (model == TLSModel::InitialExec) {
8040     if (isPIC && !is64Bit) {
8041       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8042                           DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8043                            Offset);
8044     }
8045
8046     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8047                          MachinePointerInfo::getGOT(), false, false, false,
8048                          0);
8049   }
8050
8051   // The address of the thread local variable is the add of the thread
8052   // pointer with the offset of the variable.
8053   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8054 }
8055
8056 SDValue
8057 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8058
8059   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8060   const GlobalValue *GV = GA->getGlobal();
8061
8062   if (Subtarget->isTargetELF()) {
8063     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8064
8065     switch (model) {
8066       case TLSModel::GeneralDynamic:
8067         if (Subtarget->is64Bit())
8068           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8069         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8070       case TLSModel::LocalDynamic:
8071         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8072                                            Subtarget->is64Bit());
8073       case TLSModel::InitialExec:
8074       case TLSModel::LocalExec:
8075         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8076                                    Subtarget->is64Bit(),
8077                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8078     }
8079     llvm_unreachable("Unknown TLS model.");
8080   }
8081
8082   if (Subtarget->isTargetDarwin()) {
8083     // Darwin only has one model of TLS.  Lower to that.
8084     unsigned char OpFlag = 0;
8085     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8086                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8087
8088     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8089     // global base reg.
8090     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8091                   !Subtarget->is64Bit();
8092     if (PIC32)
8093       OpFlag = X86II::MO_TLVP_PIC_BASE;
8094     else
8095       OpFlag = X86II::MO_TLVP;
8096     SDLoc DL(Op);
8097     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8098                                                 GA->getValueType(0),
8099                                                 GA->getOffset(), OpFlag);
8100     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8101
8102     // With PIC32, the address is actually $g + Offset.
8103     if (PIC32)
8104       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8105                            DAG.getNode(X86ISD::GlobalBaseReg,
8106                                        SDLoc(), getPointerTy()),
8107                            Offset);
8108
8109     // Lowering the machine isd will make sure everything is in the right
8110     // location.
8111     SDValue Chain = DAG.getEntryNode();
8112     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8113     SDValue Args[] = { Chain, Offset };
8114     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8115
8116     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8117     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8118     MFI->setAdjustsStack(true);
8119
8120     // And our return value (tls address) is in the standard call return value
8121     // location.
8122     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8123     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8124                               Chain.getValue(1));
8125   }
8126
8127   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8128     // Just use the implicit TLS architecture
8129     // Need to generate someting similar to:
8130     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8131     //                                  ; from TEB
8132     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8133     //   mov     rcx, qword [rdx+rcx*8]
8134     //   mov     eax, .tls$:tlsvar
8135     //   [rax+rcx] contains the address
8136     // Windows 64bit: gs:0x58
8137     // Windows 32bit: fs:__tls_array
8138
8139     // If GV is an alias then use the aliasee for determining
8140     // thread-localness.
8141     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8142       GV = GA->resolveAliasedGlobal(false);
8143     SDLoc dl(GA);
8144     SDValue Chain = DAG.getEntryNode();
8145
8146     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8147     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8148     // use its literal value of 0x2C.
8149     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8150                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8151                                                              256)
8152                                         : Type::getInt32PtrTy(*DAG.getContext(),
8153                                                               257));
8154
8155     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8156       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8157         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8158
8159     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8160                                         MachinePointerInfo(Ptr),
8161                                         false, false, false, 0);
8162
8163     // Load the _tls_index variable
8164     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8165     if (Subtarget->is64Bit())
8166       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8167                            IDX, MachinePointerInfo(), MVT::i32,
8168                            false, false, 0);
8169     else
8170       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8171                         false, false, false, 0);
8172
8173     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8174                                     getPointerTy());
8175     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8176
8177     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8178     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8179                       false, false, false, 0);
8180
8181     // Get the offset of start of .tls section
8182     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8183                                              GA->getValueType(0),
8184                                              GA->getOffset(), X86II::MO_SECREL);
8185     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8186
8187     // The address of the thread local variable is the add of the thread
8188     // pointer with the offset of the variable.
8189     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8190   }
8191
8192   llvm_unreachable("TLS not implemented for this target.");
8193 }
8194
8195 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8196 /// and take a 2 x i32 value to shift plus a shift amount.
8197 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8198   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8199   EVT VT = Op.getValueType();
8200   unsigned VTBits = VT.getSizeInBits();
8201   SDLoc dl(Op);
8202   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8203   SDValue ShOpLo = Op.getOperand(0);
8204   SDValue ShOpHi = Op.getOperand(1);
8205   SDValue ShAmt  = Op.getOperand(2);
8206   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8207                                      DAG.getConstant(VTBits - 1, MVT::i8))
8208                        : DAG.getConstant(0, VT);
8209
8210   SDValue Tmp2, Tmp3;
8211   if (Op.getOpcode() == ISD::SHL_PARTS) {
8212     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8213     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8214   } else {
8215     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8216     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8217   }
8218
8219   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8220                                 DAG.getConstant(VTBits, MVT::i8));
8221   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8222                              AndNode, DAG.getConstant(0, MVT::i8));
8223
8224   SDValue Hi, Lo;
8225   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8226   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8227   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8228
8229   if (Op.getOpcode() == ISD::SHL_PARTS) {
8230     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8231     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8232   } else {
8233     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8234     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8235   }
8236
8237   SDValue Ops[2] = { Lo, Hi };
8238   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8239 }
8240
8241 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8242                                            SelectionDAG &DAG) const {
8243   EVT SrcVT = Op.getOperand(0).getValueType();
8244
8245   if (SrcVT.isVector())
8246     return SDValue();
8247
8248   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8249          "Unknown SINT_TO_FP to lower!");
8250
8251   // These are really Legal; return the operand so the caller accepts it as
8252   // Legal.
8253   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8254     return Op;
8255   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8256       Subtarget->is64Bit()) {
8257     return Op;
8258   }
8259
8260   SDLoc dl(Op);
8261   unsigned Size = SrcVT.getSizeInBits()/8;
8262   MachineFunction &MF = DAG.getMachineFunction();
8263   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8264   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8265   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8266                                StackSlot,
8267                                MachinePointerInfo::getFixedStack(SSFI),
8268                                false, false, 0);
8269   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8270 }
8271
8272 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8273                                      SDValue StackSlot,
8274                                      SelectionDAG &DAG) const {
8275   // Build the FILD
8276   SDLoc DL(Op);
8277   SDVTList Tys;
8278   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8279   if (useSSE)
8280     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8281   else
8282     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8283
8284   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8285
8286   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8287   MachineMemOperand *MMO;
8288   if (FI) {
8289     int SSFI = FI->getIndex();
8290     MMO =
8291       DAG.getMachineFunction()
8292       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8293                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8294   } else {
8295     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8296     StackSlot = StackSlot.getOperand(1);
8297   }
8298   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8299   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8300                                            X86ISD::FILD, DL,
8301                                            Tys, Ops, array_lengthof(Ops),
8302                                            SrcVT, MMO);
8303
8304   if (useSSE) {
8305     Chain = Result.getValue(1);
8306     SDValue InFlag = Result.getValue(2);
8307
8308     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8309     // shouldn't be necessary except that RFP cannot be live across
8310     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8311     MachineFunction &MF = DAG.getMachineFunction();
8312     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8313     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8314     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8315     Tys = DAG.getVTList(MVT::Other);
8316     SDValue Ops[] = {
8317       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8318     };
8319     MachineMemOperand *MMO =
8320       DAG.getMachineFunction()
8321       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8322                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8323
8324     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8325                                     Ops, array_lengthof(Ops),
8326                                     Op.getValueType(), MMO);
8327     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8328                          MachinePointerInfo::getFixedStack(SSFI),
8329                          false, false, false, 0);
8330   }
8331
8332   return Result;
8333 }
8334
8335 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8336 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8337                                                SelectionDAG &DAG) const {
8338   // This algorithm is not obvious. Here it is what we're trying to output:
8339   /*
8340      movq       %rax,  %xmm0
8341      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8342      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8343      #ifdef __SSE3__
8344        haddpd   %xmm0, %xmm0
8345      #else
8346        pshufd   $0x4e, %xmm0, %xmm1
8347        addpd    %xmm1, %xmm0
8348      #endif
8349   */
8350
8351   SDLoc dl(Op);
8352   LLVMContext *Context = DAG.getContext();
8353
8354   // Build some magic constants.
8355   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8356   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8357   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8358
8359   SmallVector<Constant*,2> CV1;
8360   CV1.push_back(
8361     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8362                                       APInt(64, 0x4330000000000000ULL))));
8363   CV1.push_back(
8364     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8365                                       APInt(64, 0x4530000000000000ULL))));
8366   Constant *C1 = ConstantVector::get(CV1);
8367   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8368
8369   // Load the 64-bit value into an XMM register.
8370   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8371                             Op.getOperand(0));
8372   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8373                               MachinePointerInfo::getConstantPool(),
8374                               false, false, false, 16);
8375   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8376                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8377                               CLod0);
8378
8379   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8380                               MachinePointerInfo::getConstantPool(),
8381                               false, false, false, 16);
8382   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8383   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8384   SDValue Result;
8385
8386   if (Subtarget->hasSSE3()) {
8387     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8388     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8389   } else {
8390     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8391     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8392                                            S2F, 0x4E, DAG);
8393     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8394                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8395                          Sub);
8396   }
8397
8398   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8399                      DAG.getIntPtrConstant(0));
8400 }
8401
8402 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8403 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8404                                                SelectionDAG &DAG) const {
8405   SDLoc dl(Op);
8406   // FP constant to bias correct the final result.
8407   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8408                                    MVT::f64);
8409
8410   // Load the 32-bit value into an XMM register.
8411   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8412                              Op.getOperand(0));
8413
8414   // Zero out the upper parts of the register.
8415   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8416
8417   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8418                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8419                      DAG.getIntPtrConstant(0));
8420
8421   // Or the load with the bias.
8422   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8423                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8424                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8425                                                    MVT::v2f64, Load)),
8426                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8427                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8428                                                    MVT::v2f64, Bias)));
8429   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8430                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8431                    DAG.getIntPtrConstant(0));
8432
8433   // Subtract the bias.
8434   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8435
8436   // Handle final rounding.
8437   EVT DestVT = Op.getValueType();
8438
8439   if (DestVT.bitsLT(MVT::f64))
8440     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8441                        DAG.getIntPtrConstant(0));
8442   if (DestVT.bitsGT(MVT::f64))
8443     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8444
8445   // Handle final rounding.
8446   return Sub;
8447 }
8448
8449 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8450                                                SelectionDAG &DAG) const {
8451   SDValue N0 = Op.getOperand(0);
8452   EVT SVT = N0.getValueType();
8453   SDLoc dl(Op);
8454
8455   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8456           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8457          "Custom UINT_TO_FP is not supported!");
8458
8459   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8460                              SVT.getVectorNumElements());
8461   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8462                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8463 }
8464
8465 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8466                                            SelectionDAG &DAG) const {
8467   SDValue N0 = Op.getOperand(0);
8468   SDLoc dl(Op);
8469
8470   if (Op.getValueType().isVector())
8471     return lowerUINT_TO_FP_vec(Op, DAG);
8472
8473   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8474   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8475   // the optimization here.
8476   if (DAG.SignBitIsZero(N0))
8477     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8478
8479   EVT SrcVT = N0.getValueType();
8480   EVT DstVT = Op.getValueType();
8481   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8482     return LowerUINT_TO_FP_i64(Op, DAG);
8483   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8484     return LowerUINT_TO_FP_i32(Op, DAG);
8485   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8486     return SDValue();
8487
8488   // Make a 64-bit buffer, and use it to build an FILD.
8489   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8490   if (SrcVT == MVT::i32) {
8491     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8492     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8493                                      getPointerTy(), StackSlot, WordOff);
8494     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8495                                   StackSlot, MachinePointerInfo(),
8496                                   false, false, 0);
8497     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8498                                   OffsetSlot, MachinePointerInfo(),
8499                                   false, false, 0);
8500     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8501     return Fild;
8502   }
8503
8504   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8505   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8506                                StackSlot, MachinePointerInfo(),
8507                                false, false, 0);
8508   // For i64 source, we need to add the appropriate power of 2 if the input
8509   // was negative.  This is the same as the optimization in
8510   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8511   // we must be careful to do the computation in x87 extended precision, not
8512   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8513   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8514   MachineMemOperand *MMO =
8515     DAG.getMachineFunction()
8516     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8517                           MachineMemOperand::MOLoad, 8, 8);
8518
8519   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8520   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8521   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8522                                          array_lengthof(Ops), MVT::i64, MMO);
8523
8524   APInt FF(32, 0x5F800000ULL);
8525
8526   // Check whether the sign bit is set.
8527   SDValue SignSet = DAG.getSetCC(dl,
8528                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8529                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8530                                  ISD::SETLT);
8531
8532   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8533   SDValue FudgePtr = DAG.getConstantPool(
8534                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8535                                          getPointerTy());
8536
8537   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8538   SDValue Zero = DAG.getIntPtrConstant(0);
8539   SDValue Four = DAG.getIntPtrConstant(4);
8540   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8541                                Zero, Four);
8542   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8543
8544   // Load the value out, extending it from f32 to f80.
8545   // FIXME: Avoid the extend by constructing the right constant pool?
8546   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8547                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8548                                  MVT::f32, false, false, 4);
8549   // Extend everything to 80 bits to force it to be done on x87.
8550   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8551   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8552 }
8553
8554 std::pair<SDValue,SDValue>
8555 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8556                                     bool IsSigned, bool IsReplace) const {
8557   SDLoc DL(Op);
8558
8559   EVT DstTy = Op.getValueType();
8560
8561   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8562     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8563     DstTy = MVT::i64;
8564   }
8565
8566   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8567          DstTy.getSimpleVT() >= MVT::i16 &&
8568          "Unknown FP_TO_INT to lower!");
8569
8570   // These are really Legal.
8571   if (DstTy == MVT::i32 &&
8572       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8573     return std::make_pair(SDValue(), SDValue());
8574   if (Subtarget->is64Bit() &&
8575       DstTy == MVT::i64 &&
8576       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8577     return std::make_pair(SDValue(), SDValue());
8578
8579   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8580   // stack slot, or into the FTOL runtime function.
8581   MachineFunction &MF = DAG.getMachineFunction();
8582   unsigned MemSize = DstTy.getSizeInBits()/8;
8583   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8584   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8585
8586   unsigned Opc;
8587   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8588     Opc = X86ISD::WIN_FTOL;
8589   else
8590     switch (DstTy.getSimpleVT().SimpleTy) {
8591     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8592     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8593     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8594     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8595     }
8596
8597   SDValue Chain = DAG.getEntryNode();
8598   SDValue Value = Op.getOperand(0);
8599   EVT TheVT = Op.getOperand(0).getValueType();
8600   // FIXME This causes a redundant load/store if the SSE-class value is already
8601   // in memory, such as if it is on the callstack.
8602   if (isScalarFPTypeInSSEReg(TheVT)) {
8603     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8604     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8605                          MachinePointerInfo::getFixedStack(SSFI),
8606                          false, false, 0);
8607     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8608     SDValue Ops[] = {
8609       Chain, StackSlot, DAG.getValueType(TheVT)
8610     };
8611
8612     MachineMemOperand *MMO =
8613       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8614                               MachineMemOperand::MOLoad, MemSize, MemSize);
8615     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8616                                     array_lengthof(Ops), DstTy, MMO);
8617     Chain = Value.getValue(1);
8618     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8619     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8620   }
8621
8622   MachineMemOperand *MMO =
8623     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8624                             MachineMemOperand::MOStore, MemSize, MemSize);
8625
8626   if (Opc != X86ISD::WIN_FTOL) {
8627     // Build the FP_TO_INT*_IN_MEM
8628     SDValue Ops[] = { Chain, Value, StackSlot };
8629     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8630                                            Ops, array_lengthof(Ops), DstTy,
8631                                            MMO);
8632     return std::make_pair(FIST, StackSlot);
8633   } else {
8634     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8635       DAG.getVTList(MVT::Other, MVT::Glue),
8636       Chain, Value);
8637     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8638       MVT::i32, ftol.getValue(1));
8639     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8640       MVT::i32, eax.getValue(2));
8641     SDValue Ops[] = { eax, edx };
8642     SDValue pair = IsReplace
8643       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8644       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8645     return std::make_pair(pair, SDValue());
8646   }
8647 }
8648
8649 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8650                               const X86Subtarget *Subtarget) {
8651   MVT VT = Op->getValueType(0).getSimpleVT();
8652   SDValue In = Op->getOperand(0);
8653   MVT InVT = In.getValueType().getSimpleVT();
8654   SDLoc dl(Op);
8655
8656   // Optimize vectors in AVX mode:
8657   //
8658   //   v8i16 -> v8i32
8659   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8660   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8661   //   Concat upper and lower parts.
8662   //
8663   //   v4i32 -> v4i64
8664   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8665   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8666   //   Concat upper and lower parts.
8667   //
8668
8669   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8670       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8671     return SDValue();
8672
8673   if (Subtarget->hasInt256())
8674     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8675
8676   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8677   SDValue Undef = DAG.getUNDEF(InVT);
8678   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8679   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8680   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8681
8682   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8683                              VT.getVectorNumElements()/2);
8684
8685   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8686   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8687
8688   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8689 }
8690
8691 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8692                                            SelectionDAG &DAG) const {
8693   if (Subtarget->hasFp256()) {
8694     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8695     if (Res.getNode())
8696       return Res;
8697   }
8698
8699   return SDValue();
8700 }
8701 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8702                                             SelectionDAG &DAG) const {
8703   SDLoc DL(Op);
8704   MVT VT = Op.getValueType().getSimpleVT();
8705   SDValue In = Op.getOperand(0);
8706   MVT SVT = In.getValueType().getSimpleVT();
8707
8708   if (Subtarget->hasFp256()) {
8709     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8710     if (Res.getNode())
8711       return Res;
8712   }
8713
8714   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8715       VT.getVectorNumElements() != SVT.getVectorNumElements())
8716     return SDValue();
8717
8718   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8719
8720   // AVX2 has better support of integer extending.
8721   if (Subtarget->hasInt256())
8722     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8723
8724   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8725   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8726   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8727                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8728                                                 DAG.getUNDEF(MVT::v8i16),
8729                                                 &Mask[0]));
8730
8731   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8732 }
8733
8734 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8735   SDLoc DL(Op);
8736   MVT VT = Op.getValueType().getSimpleVT();
8737   SDValue In = Op.getOperand(0);
8738   MVT SVT = In.getValueType().getSimpleVT();
8739
8740   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8741     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8742     if (Subtarget->hasInt256()) {
8743       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8744       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8745       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8746                                 ShufMask);
8747       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8748                          DAG.getIntPtrConstant(0));
8749     }
8750
8751     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8752     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8753                                DAG.getIntPtrConstant(0));
8754     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8755                                DAG.getIntPtrConstant(2));
8756
8757     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8758     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8759
8760     // The PSHUFD mask:
8761     static const int ShufMask1[] = {0, 2, 0, 0};
8762     SDValue Undef = DAG.getUNDEF(VT);
8763     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8764     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8765
8766     // The MOVLHPS mask:
8767     static const int ShufMask2[] = {0, 1, 4, 5};
8768     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8769   }
8770
8771   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8772     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8773     if (Subtarget->hasInt256()) {
8774       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8775
8776       SmallVector<SDValue,32> pshufbMask;
8777       for (unsigned i = 0; i < 2; ++i) {
8778         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8779         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8780         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8781         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8782         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8783         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8784         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8785         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8786         for (unsigned j = 0; j < 8; ++j)
8787           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8788       }
8789       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8790                                &pshufbMask[0], 32);
8791       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8792       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8793
8794       static const int ShufMask[] = {0,  2,  -1,  -1};
8795       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8796                                 &ShufMask[0]);
8797       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8798                        DAG.getIntPtrConstant(0));
8799       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8800     }
8801
8802     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8803                                DAG.getIntPtrConstant(0));
8804
8805     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8806                                DAG.getIntPtrConstant(4));
8807
8808     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8809     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8810
8811     // The PSHUFB mask:
8812     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8813                                    -1, -1, -1, -1, -1, -1, -1, -1};
8814
8815     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8816     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8817     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8818
8819     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8820     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8821
8822     // The MOVLHPS Mask:
8823     static const int ShufMask2[] = {0, 1, 4, 5};
8824     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8825     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8826   }
8827
8828   // Handle truncation of V256 to V128 using shuffles.
8829   if (!VT.is128BitVector() || !SVT.is256BitVector())
8830     return SDValue();
8831
8832   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8833          "Invalid op");
8834   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8835
8836   unsigned NumElems = VT.getVectorNumElements();
8837   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8838                              NumElems * 2);
8839
8840   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8841   // Prepare truncation shuffle mask
8842   for (unsigned i = 0; i != NumElems; ++i)
8843     MaskVec[i] = i * 2;
8844   SDValue V = DAG.getVectorShuffle(NVT, DL,
8845                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8846                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8847   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8848                      DAG.getIntPtrConstant(0));
8849 }
8850
8851 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8852                                            SelectionDAG &DAG) const {
8853   MVT VT = Op.getValueType().getSimpleVT();
8854   if (VT.isVector()) {
8855     if (VT == MVT::v8i16)
8856       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8857                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8858                                      MVT::v8i32, Op.getOperand(0)));
8859     return SDValue();
8860   }
8861
8862   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8863     /*IsSigned=*/ true, /*IsReplace=*/ false);
8864   SDValue FIST = Vals.first, StackSlot = Vals.second;
8865   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8866   if (FIST.getNode() == 0) return Op;
8867
8868   if (StackSlot.getNode())
8869     // Load the result.
8870     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8871                        FIST, StackSlot, MachinePointerInfo(),
8872                        false, false, false, 0);
8873
8874   // The node is the result.
8875   return FIST;
8876 }
8877
8878 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8879                                            SelectionDAG &DAG) const {
8880   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8881     /*IsSigned=*/ false, /*IsReplace=*/ false);
8882   SDValue FIST = Vals.first, StackSlot = Vals.second;
8883   assert(FIST.getNode() && "Unexpected failure");
8884
8885   if (StackSlot.getNode())
8886     // Load the result.
8887     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8888                        FIST, StackSlot, MachinePointerInfo(),
8889                        false, false, false, 0);
8890
8891   // The node is the result.
8892   return FIST;
8893 }
8894
8895 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8896   SDLoc DL(Op);
8897   MVT VT = Op.getValueType().getSimpleVT();
8898   SDValue In = Op.getOperand(0);
8899   MVT SVT = In.getValueType().getSimpleVT();
8900
8901   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8902
8903   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8904                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8905                                  In, DAG.getUNDEF(SVT)));
8906 }
8907
8908 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8909   LLVMContext *Context = DAG.getContext();
8910   SDLoc dl(Op);
8911   MVT VT = Op.getValueType().getSimpleVT();
8912   MVT EltVT = VT;
8913   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8914   if (VT.isVector()) {
8915     EltVT = VT.getVectorElementType();
8916     NumElts = VT.getVectorNumElements();
8917   }
8918   Constant *C;
8919   if (EltVT == MVT::f64)
8920     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8921                                           APInt(64, ~(1ULL << 63))));
8922   else
8923     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8924                                           APInt(32, ~(1U << 31))));
8925   C = ConstantVector::getSplat(NumElts, C);
8926   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8927   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8928   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8929                              MachinePointerInfo::getConstantPool(),
8930                              false, false, false, Alignment);
8931   if (VT.isVector()) {
8932     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8933     return DAG.getNode(ISD::BITCAST, dl, VT,
8934                        DAG.getNode(ISD::AND, dl, ANDVT,
8935                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8936                                                Op.getOperand(0)),
8937                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8938   }
8939   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8940 }
8941
8942 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8943   LLVMContext *Context = DAG.getContext();
8944   SDLoc dl(Op);
8945   MVT VT = Op.getValueType().getSimpleVT();
8946   MVT EltVT = VT;
8947   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8948   if (VT.isVector()) {
8949     EltVT = VT.getVectorElementType();
8950     NumElts = VT.getVectorNumElements();
8951   }
8952   Constant *C;
8953   if (EltVT == MVT::f64)
8954     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8955                                           APInt(64, 1ULL << 63)));
8956   else
8957     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8958                                           APInt(32, 1U << 31)));
8959   C = ConstantVector::getSplat(NumElts, C);
8960   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8961   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8962   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8963                              MachinePointerInfo::getConstantPool(),
8964                              false, false, false, Alignment);
8965   if (VT.isVector()) {
8966     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8967     return DAG.getNode(ISD::BITCAST, dl, VT,
8968                        DAG.getNode(ISD::XOR, dl, XORVT,
8969                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8970                                                Op.getOperand(0)),
8971                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8972   }
8973
8974   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8975 }
8976
8977 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8978   LLVMContext *Context = DAG.getContext();
8979   SDValue Op0 = Op.getOperand(0);
8980   SDValue Op1 = Op.getOperand(1);
8981   SDLoc dl(Op);
8982   MVT VT = Op.getValueType().getSimpleVT();
8983   MVT SrcVT = Op1.getValueType().getSimpleVT();
8984
8985   // If second operand is smaller, extend it first.
8986   if (SrcVT.bitsLT(VT)) {
8987     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8988     SrcVT = VT;
8989   }
8990   // And if it is bigger, shrink it first.
8991   if (SrcVT.bitsGT(VT)) {
8992     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8993     SrcVT = VT;
8994   }
8995
8996   // At this point the operands and the result should have the same
8997   // type, and that won't be f80 since that is not custom lowered.
8998
8999   // First get the sign bit of second operand.
9000   SmallVector<Constant*,4> CV;
9001   if (SrcVT == MVT::f64) {
9002     const fltSemantics &Sem = APFloat::IEEEdouble;
9003     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9004     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9005   } else {
9006     const fltSemantics &Sem = APFloat::IEEEsingle;
9007     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9008     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9009     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9010     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9011   }
9012   Constant *C = ConstantVector::get(CV);
9013   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9014   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9015                               MachinePointerInfo::getConstantPool(),
9016                               false, false, false, 16);
9017   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9018
9019   // Shift sign bit right or left if the two operands have different types.
9020   if (SrcVT.bitsGT(VT)) {
9021     // Op0 is MVT::f32, Op1 is MVT::f64.
9022     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9023     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9024                           DAG.getConstant(32, MVT::i32));
9025     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9026     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9027                           DAG.getIntPtrConstant(0));
9028   }
9029
9030   // Clear first operand sign bit.
9031   CV.clear();
9032   if (VT == MVT::f64) {
9033     const fltSemantics &Sem = APFloat::IEEEdouble;
9034     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9035                                                    APInt(64, ~(1ULL << 63)))));
9036     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9037   } else {
9038     const fltSemantics &Sem = APFloat::IEEEsingle;
9039     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9040                                                    APInt(32, ~(1U << 31)))));
9041     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9042     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9043     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9044   }
9045   C = ConstantVector::get(CV);
9046   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9047   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9048                               MachinePointerInfo::getConstantPool(),
9049                               false, false, false, 16);
9050   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9051
9052   // Or the value with the sign bit.
9053   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9054 }
9055
9056 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9057   SDValue N0 = Op.getOperand(0);
9058   SDLoc dl(Op);
9059   MVT VT = Op.getValueType().getSimpleVT();
9060
9061   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9062   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9063                                   DAG.getConstant(1, VT));
9064   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9065 }
9066
9067 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9068 //
9069 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
9070                                                   SelectionDAG &DAG) const {
9071   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9072
9073   if (!Subtarget->hasSSE41())
9074     return SDValue();
9075
9076   if (!Op->hasOneUse())
9077     return SDValue();
9078
9079   SDNode *N = Op.getNode();
9080   SDLoc DL(N);
9081
9082   SmallVector<SDValue, 8> Opnds;
9083   DenseMap<SDValue, unsigned> VecInMap;
9084   EVT VT = MVT::Other;
9085
9086   // Recognize a special case where a vector is casted into wide integer to
9087   // test all 0s.
9088   Opnds.push_back(N->getOperand(0));
9089   Opnds.push_back(N->getOperand(1));
9090
9091   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9092     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9093     // BFS traverse all OR'd operands.
9094     if (I->getOpcode() == ISD::OR) {
9095       Opnds.push_back(I->getOperand(0));
9096       Opnds.push_back(I->getOperand(1));
9097       // Re-evaluate the number of nodes to be traversed.
9098       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9099       continue;
9100     }
9101
9102     // Quit if a non-EXTRACT_VECTOR_ELT
9103     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9104       return SDValue();
9105
9106     // Quit if without a constant index.
9107     SDValue Idx = I->getOperand(1);
9108     if (!isa<ConstantSDNode>(Idx))
9109       return SDValue();
9110
9111     SDValue ExtractedFromVec = I->getOperand(0);
9112     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9113     if (M == VecInMap.end()) {
9114       VT = ExtractedFromVec.getValueType();
9115       // Quit if not 128/256-bit vector.
9116       if (!VT.is128BitVector() && !VT.is256BitVector())
9117         return SDValue();
9118       // Quit if not the same type.
9119       if (VecInMap.begin() != VecInMap.end() &&
9120           VT != VecInMap.begin()->first.getValueType())
9121         return SDValue();
9122       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9123     }
9124     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9125   }
9126
9127   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9128          "Not extracted from 128-/256-bit vector.");
9129
9130   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9131   SmallVector<SDValue, 8> VecIns;
9132
9133   for (DenseMap<SDValue, unsigned>::const_iterator
9134         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9135     // Quit if not all elements are used.
9136     if (I->second != FullMask)
9137       return SDValue();
9138     VecIns.push_back(I->first);
9139   }
9140
9141   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9142
9143   // Cast all vectors into TestVT for PTEST.
9144   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9145     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9146
9147   // If more than one full vectors are evaluated, OR them first before PTEST.
9148   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9149     // Each iteration will OR 2 nodes and append the result until there is only
9150     // 1 node left, i.e. the final OR'd value of all vectors.
9151     SDValue LHS = VecIns[Slot];
9152     SDValue RHS = VecIns[Slot + 1];
9153     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9154   }
9155
9156   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9157                      VecIns.back(), VecIns.back());
9158 }
9159
9160 /// Emit nodes that will be selected as "test Op0,Op0", or something
9161 /// equivalent.
9162 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9163                                     SelectionDAG &DAG) const {
9164   SDLoc dl(Op);
9165
9166   // CF and OF aren't always set the way we want. Determine which
9167   // of these we need.
9168   bool NeedCF = false;
9169   bool NeedOF = false;
9170   switch (X86CC) {
9171   default: break;
9172   case X86::COND_A: case X86::COND_AE:
9173   case X86::COND_B: case X86::COND_BE:
9174     NeedCF = true;
9175     break;
9176   case X86::COND_G: case X86::COND_GE:
9177   case X86::COND_L: case X86::COND_LE:
9178   case X86::COND_O: case X86::COND_NO:
9179     NeedOF = true;
9180     break;
9181   }
9182
9183   // See if we can use the EFLAGS value from the operand instead of
9184   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9185   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9186   if (Op.getResNo() != 0 || NeedOF || NeedCF)
9187     // Emit a CMP with 0, which is the TEST pattern.
9188     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9189                        DAG.getConstant(0, Op.getValueType()));
9190
9191   unsigned Opcode = 0;
9192   unsigned NumOperands = 0;
9193
9194   // Truncate operations may prevent the merge of the SETCC instruction
9195   // and the arithmetic intruction before it. Attempt to truncate the operands
9196   // of the arithmetic instruction and use a reduced bit-width instruction.
9197   bool NeedTruncation = false;
9198   SDValue ArithOp = Op;
9199   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9200     SDValue Arith = Op->getOperand(0);
9201     // Both the trunc and the arithmetic op need to have one user each.
9202     if (Arith->hasOneUse())
9203       switch (Arith.getOpcode()) {
9204         default: break;
9205         case ISD::ADD:
9206         case ISD::SUB:
9207         case ISD::AND:
9208         case ISD::OR:
9209         case ISD::XOR: {
9210           NeedTruncation = true;
9211           ArithOp = Arith;
9212         }
9213       }
9214   }
9215
9216   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9217   // which may be the result of a CAST.  We use the variable 'Op', which is the
9218   // non-casted variable when we check for possible users.
9219   switch (ArithOp.getOpcode()) {
9220   case ISD::ADD:
9221     // Due to an isel shortcoming, be conservative if this add is likely to be
9222     // selected as part of a load-modify-store instruction. When the root node
9223     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9224     // uses of other nodes in the match, such as the ADD in this case. This
9225     // leads to the ADD being left around and reselected, with the result being
9226     // two adds in the output.  Alas, even if none our users are stores, that
9227     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9228     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9229     // climbing the DAG back to the root, and it doesn't seem to be worth the
9230     // effort.
9231     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9232          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9233       if (UI->getOpcode() != ISD::CopyToReg &&
9234           UI->getOpcode() != ISD::SETCC &&
9235           UI->getOpcode() != ISD::STORE)
9236         goto default_case;
9237
9238     if (ConstantSDNode *C =
9239         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9240       // An add of one will be selected as an INC.
9241       if (C->getAPIntValue() == 1) {
9242         Opcode = X86ISD::INC;
9243         NumOperands = 1;
9244         break;
9245       }
9246
9247       // An add of negative one (subtract of one) will be selected as a DEC.
9248       if (C->getAPIntValue().isAllOnesValue()) {
9249         Opcode = X86ISD::DEC;
9250         NumOperands = 1;
9251         break;
9252       }
9253     }
9254
9255     // Otherwise use a regular EFLAGS-setting add.
9256     Opcode = X86ISD::ADD;
9257     NumOperands = 2;
9258     break;
9259   case ISD::AND: {
9260     // If the primary and result isn't used, don't bother using X86ISD::AND,
9261     // because a TEST instruction will be better.
9262     bool NonFlagUse = false;
9263     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9264            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9265       SDNode *User = *UI;
9266       unsigned UOpNo = UI.getOperandNo();
9267       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9268         // Look pass truncate.
9269         UOpNo = User->use_begin().getOperandNo();
9270         User = *User->use_begin();
9271       }
9272
9273       if (User->getOpcode() != ISD::BRCOND &&
9274           User->getOpcode() != ISD::SETCC &&
9275           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9276         NonFlagUse = true;
9277         break;
9278       }
9279     }
9280
9281     if (!NonFlagUse)
9282       break;
9283   }
9284     // FALL THROUGH
9285   case ISD::SUB:
9286   case ISD::OR:
9287   case ISD::XOR:
9288     // Due to the ISEL shortcoming noted above, be conservative if this op is
9289     // likely to be selected as part of a load-modify-store instruction.
9290     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9291            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9292       if (UI->getOpcode() == ISD::STORE)
9293         goto default_case;
9294
9295     // Otherwise use a regular EFLAGS-setting instruction.
9296     switch (ArithOp.getOpcode()) {
9297     default: llvm_unreachable("unexpected operator!");
9298     case ISD::SUB: Opcode = X86ISD::SUB; break;
9299     case ISD::XOR: Opcode = X86ISD::XOR; break;
9300     case ISD::AND: Opcode = X86ISD::AND; break;
9301     case ISD::OR: {
9302       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9303         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9304         if (EFLAGS.getNode())
9305           return EFLAGS;
9306       }
9307       Opcode = X86ISD::OR;
9308       break;
9309     }
9310     }
9311
9312     NumOperands = 2;
9313     break;
9314   case X86ISD::ADD:
9315   case X86ISD::SUB:
9316   case X86ISD::INC:
9317   case X86ISD::DEC:
9318   case X86ISD::OR:
9319   case X86ISD::XOR:
9320   case X86ISD::AND:
9321     return SDValue(Op.getNode(), 1);
9322   default:
9323   default_case:
9324     break;
9325   }
9326
9327   // If we found that truncation is beneficial, perform the truncation and
9328   // update 'Op'.
9329   if (NeedTruncation) {
9330     EVT VT = Op.getValueType();
9331     SDValue WideVal = Op->getOperand(0);
9332     EVT WideVT = WideVal.getValueType();
9333     unsigned ConvertedOp = 0;
9334     // Use a target machine opcode to prevent further DAGCombine
9335     // optimizations that may separate the arithmetic operations
9336     // from the setcc node.
9337     switch (WideVal.getOpcode()) {
9338       default: break;
9339       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9340       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9341       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9342       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9343       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9344     }
9345
9346     if (ConvertedOp) {
9347       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9348       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9349         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9350         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9351         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9352       }
9353     }
9354   }
9355
9356   if (Opcode == 0)
9357     // Emit a CMP with 0, which is the TEST pattern.
9358     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9359                        DAG.getConstant(0, Op.getValueType()));
9360
9361   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9362   SmallVector<SDValue, 4> Ops;
9363   for (unsigned i = 0; i != NumOperands; ++i)
9364     Ops.push_back(Op.getOperand(i));
9365
9366   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9367   DAG.ReplaceAllUsesWith(Op, New);
9368   return SDValue(New.getNode(), 1);
9369 }
9370
9371 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9372 /// equivalent.
9373 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9374                                    SelectionDAG &DAG) const {
9375   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9376     if (C->getAPIntValue() == 0)
9377       return EmitTest(Op0, X86CC, DAG);
9378
9379   SDLoc dl(Op0);
9380   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9381        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9382     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9383     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9384     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9385                               Op0, Op1);
9386     return SDValue(Sub.getNode(), 1);
9387   }
9388   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9389 }
9390
9391 /// Convert a comparison if required by the subtarget.
9392 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9393                                                  SelectionDAG &DAG) const {
9394   // If the subtarget does not support the FUCOMI instruction, floating-point
9395   // comparisons have to be converted.
9396   if (Subtarget->hasCMov() ||
9397       Cmp.getOpcode() != X86ISD::CMP ||
9398       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9399       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9400     return Cmp;
9401
9402   // The instruction selector will select an FUCOM instruction instead of
9403   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9404   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9405   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9406   SDLoc dl(Cmp);
9407   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9408   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9409   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9410                             DAG.getConstant(8, MVT::i8));
9411   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9412   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9413 }
9414
9415 static bool isAllOnes(SDValue V) {
9416   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9417   return C && C->isAllOnesValue();
9418 }
9419
9420 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9421 /// if it's possible.
9422 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9423                                      SDLoc dl, SelectionDAG &DAG) const {
9424   SDValue Op0 = And.getOperand(0);
9425   SDValue Op1 = And.getOperand(1);
9426   if (Op0.getOpcode() == ISD::TRUNCATE)
9427     Op0 = Op0.getOperand(0);
9428   if (Op1.getOpcode() == ISD::TRUNCATE)
9429     Op1 = Op1.getOperand(0);
9430
9431   SDValue LHS, RHS;
9432   if (Op1.getOpcode() == ISD::SHL)
9433     std::swap(Op0, Op1);
9434   if (Op0.getOpcode() == ISD::SHL) {
9435     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9436       if (And00C->getZExtValue() == 1) {
9437         // If we looked past a truncate, check that it's only truncating away
9438         // known zeros.
9439         unsigned BitWidth = Op0.getValueSizeInBits();
9440         unsigned AndBitWidth = And.getValueSizeInBits();
9441         if (BitWidth > AndBitWidth) {
9442           APInt Zeros, Ones;
9443           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9444           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9445             return SDValue();
9446         }
9447         LHS = Op1;
9448         RHS = Op0.getOperand(1);
9449       }
9450   } else if (Op1.getOpcode() == ISD::Constant) {
9451     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9452     uint64_t AndRHSVal = AndRHS->getZExtValue();
9453     SDValue AndLHS = Op0;
9454
9455     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9456       LHS = AndLHS.getOperand(0);
9457       RHS = AndLHS.getOperand(1);
9458     }
9459
9460     // Use BT if the immediate can't be encoded in a TEST instruction.
9461     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9462       LHS = AndLHS;
9463       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9464     }
9465   }
9466
9467   if (LHS.getNode()) {
9468     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9469     // instruction.  Since the shift amount is in-range-or-undefined, we know
9470     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9471     // the encoding for the i16 version is larger than the i32 version.
9472     // Also promote i16 to i32 for performance / code size reason.
9473     if (LHS.getValueType() == MVT::i8 ||
9474         LHS.getValueType() == MVT::i16)
9475       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9476
9477     // If the operand types disagree, extend the shift amount to match.  Since
9478     // BT ignores high bits (like shifts) we can use anyextend.
9479     if (LHS.getValueType() != RHS.getValueType())
9480       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9481
9482     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9483     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9484     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9485                        DAG.getConstant(Cond, MVT::i8), BT);
9486   }
9487
9488   return SDValue();
9489 }
9490
9491 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9492 /// mask CMPs.
9493 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9494                               SDValue &Op1) {
9495   unsigned SSECC;
9496   bool Swap = false;
9497
9498   // SSE Condition code mapping:
9499   //  0 - EQ
9500   //  1 - LT
9501   //  2 - LE
9502   //  3 - UNORD
9503   //  4 - NEQ
9504   //  5 - NLT
9505   //  6 - NLE
9506   //  7 - ORD
9507   switch (SetCCOpcode) {
9508   default: llvm_unreachable("Unexpected SETCC condition");
9509   case ISD::SETOEQ:
9510   case ISD::SETEQ:  SSECC = 0; break;
9511   case ISD::SETOGT:
9512   case ISD::SETGT:  Swap = true; // Fallthrough
9513   case ISD::SETLT:
9514   case ISD::SETOLT: SSECC = 1; break;
9515   case ISD::SETOGE:
9516   case ISD::SETGE:  Swap = true; // Fallthrough
9517   case ISD::SETLE:
9518   case ISD::SETOLE: SSECC = 2; break;
9519   case ISD::SETUO:  SSECC = 3; break;
9520   case ISD::SETUNE:
9521   case ISD::SETNE:  SSECC = 4; break;
9522   case ISD::SETULE: Swap = true; // Fallthrough
9523   case ISD::SETUGE: SSECC = 5; break;
9524   case ISD::SETULT: Swap = true; // Fallthrough
9525   case ISD::SETUGT: SSECC = 6; break;
9526   case ISD::SETO:   SSECC = 7; break;
9527   case ISD::SETUEQ:
9528   case ISD::SETONE: SSECC = 8; break;
9529   }
9530   if (Swap)
9531     std::swap(Op0, Op1);
9532
9533   return SSECC;
9534 }
9535
9536 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9537 // ones, and then concatenate the result back.
9538 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9539   MVT VT = Op.getValueType().getSimpleVT();
9540
9541   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9542          "Unsupported value type for operation");
9543
9544   unsigned NumElems = VT.getVectorNumElements();
9545   SDLoc dl(Op);
9546   SDValue CC = Op.getOperand(2);
9547
9548   // Extract the LHS vectors
9549   SDValue LHS = Op.getOperand(0);
9550   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9551   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9552
9553   // Extract the RHS vectors
9554   SDValue RHS = Op.getOperand(1);
9555   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9556   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9557
9558   // Issue the operation on the smaller types and concatenate the result back
9559   MVT EltVT = VT.getVectorElementType();
9560   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9561   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9562                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9563                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9564 }
9565
9566 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9567                            SelectionDAG &DAG) {
9568   SDValue Cond;
9569   SDValue Op0 = Op.getOperand(0);
9570   SDValue Op1 = Op.getOperand(1);
9571   SDValue CC = Op.getOperand(2);
9572   MVT VT = Op.getValueType().getSimpleVT();
9573   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9574   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9575   SDLoc dl(Op);
9576
9577   if (isFP) {
9578 #ifndef NDEBUG
9579     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9580     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9581 #endif
9582
9583     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
9584
9585     // In the two special cases we can't handle, emit two comparisons.
9586     if (SSECC == 8) {
9587       unsigned CC0, CC1;
9588       unsigned CombineOpc;
9589       if (SetCCOpcode == ISD::SETUEQ) {
9590         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9591       } else {
9592         assert(SetCCOpcode == ISD::SETONE);
9593         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9594       }
9595
9596       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9597                                  DAG.getConstant(CC0, MVT::i8));
9598       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9599                                  DAG.getConstant(CC1, MVT::i8));
9600       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9601     }
9602     // Handle all other FP comparisons here.
9603     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9604                        DAG.getConstant(SSECC, MVT::i8));
9605   }
9606
9607   // Break 256-bit integer vector compare into smaller ones.
9608   if (VT.is256BitVector() && !Subtarget->hasInt256())
9609     return Lower256IntVSETCC(Op, DAG);
9610
9611   // We are handling one of the integer comparisons here.  Since SSE only has
9612   // GT and EQ comparisons for integer, swapping operands and multiple
9613   // operations may be required for some comparisons.
9614   unsigned Opc;
9615   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9616   
9617   switch (SetCCOpcode) {
9618   default: llvm_unreachable("Unexpected SETCC condition");
9619   case ISD::SETNE:  Invert = true;
9620   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9621   case ISD::SETLT:  Swap = true;
9622   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9623   case ISD::SETGE:  Swap = true;
9624   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9625   case ISD::SETULT: Swap = true;
9626   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9627   case ISD::SETUGE: Swap = true;
9628   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9629   }
9630   
9631   // Special case: Use min/max operations for SETULE/SETUGE
9632   MVT VET = VT.getVectorElementType();
9633   bool hasMinMax =
9634        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
9635     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
9636   
9637   if (hasMinMax) {
9638     switch (SetCCOpcode) {
9639     default: break;
9640     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
9641     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
9642     }
9643     
9644     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
9645   }
9646   
9647   if (Swap)
9648     std::swap(Op0, Op1);
9649
9650   // Check that the operation in question is available (most are plain SSE2,
9651   // but PCMPGTQ and PCMPEQQ have different requirements).
9652   if (VT == MVT::v2i64) {
9653     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9654       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9655
9656       // First cast everything to the right type.
9657       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9658       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9659
9660       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9661       // bits of the inputs before performing those operations. The lower
9662       // compare is always unsigned.
9663       SDValue SB;
9664       if (FlipSigns) {
9665         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9666       } else {
9667         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9668         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9669         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9670                          Sign, Zero, Sign, Zero);
9671       }
9672       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9673       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9674
9675       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9676       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9677       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9678
9679       // Create masks for only the low parts/high parts of the 64 bit integers.
9680       static const int MaskHi[] = { 1, 1, 3, 3 };
9681       static const int MaskLo[] = { 0, 0, 2, 2 };
9682       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9683       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9684       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9685
9686       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9687       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9688
9689       if (Invert)
9690         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9691
9692       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9693     }
9694
9695     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9696       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9697       // pcmpeqd + pshufd + pand.
9698       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9699
9700       // First cast everything to the right type.
9701       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9702       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9703
9704       // Do the compare.
9705       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9706
9707       // Make sure the lower and upper halves are both all-ones.
9708       static const int Mask[] = { 1, 0, 3, 2 };
9709       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9710       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9711
9712       if (Invert)
9713         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9714
9715       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9716     }
9717   }
9718
9719   // Since SSE has no unsigned integer comparisons, we need to flip the sign
9720   // bits of the inputs before performing those operations.
9721   if (FlipSigns) {
9722     EVT EltVT = VT.getVectorElementType();
9723     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9724     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9725     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9726   }
9727
9728   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9729
9730   // If the logical-not of the result is required, perform that now.
9731   if (Invert)
9732     Result = DAG.getNOT(dl, Result, VT);
9733   
9734   if (MinMax)
9735     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
9736
9737   return Result;
9738 }
9739
9740 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9741
9742   MVT VT = Op.getValueType().getSimpleVT();
9743
9744   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9745
9746   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9747   SDValue Op0 = Op.getOperand(0);
9748   SDValue Op1 = Op.getOperand(1);
9749   SDLoc dl(Op);
9750   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9751
9752   // Optimize to BT if possible.
9753   // Lower (X & (1 << N)) == 0 to BT(X, N).
9754   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9755   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9756   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9757       Op1.getOpcode() == ISD::Constant &&
9758       cast<ConstantSDNode>(Op1)->isNullValue() &&
9759       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9760     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9761     if (NewSetCC.getNode())
9762       return NewSetCC;
9763   }
9764
9765   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9766   // these.
9767   if (Op1.getOpcode() == ISD::Constant &&
9768       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9769        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9770       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9771
9772     // If the input is a setcc, then reuse the input setcc or use a new one with
9773     // the inverted condition.
9774     if (Op0.getOpcode() == X86ISD::SETCC) {
9775       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9776       bool Invert = (CC == ISD::SETNE) ^
9777         cast<ConstantSDNode>(Op1)->isNullValue();
9778       if (!Invert) return Op0;
9779
9780       CCode = X86::GetOppositeBranchCondition(CCode);
9781       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9782                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9783     }
9784   }
9785
9786   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9787   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9788   if (X86CC == X86::COND_INVALID)
9789     return SDValue();
9790
9791   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9792   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9793   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9794                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9795 }
9796
9797 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9798 static bool isX86LogicalCmp(SDValue Op) {
9799   unsigned Opc = Op.getNode()->getOpcode();
9800   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9801       Opc == X86ISD::SAHF)
9802     return true;
9803   if (Op.getResNo() == 1 &&
9804       (Opc == X86ISD::ADD ||
9805        Opc == X86ISD::SUB ||
9806        Opc == X86ISD::ADC ||
9807        Opc == X86ISD::SBB ||
9808        Opc == X86ISD::SMUL ||
9809        Opc == X86ISD::UMUL ||
9810        Opc == X86ISD::INC ||
9811        Opc == X86ISD::DEC ||
9812        Opc == X86ISD::OR ||
9813        Opc == X86ISD::XOR ||
9814        Opc == X86ISD::AND))
9815     return true;
9816
9817   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9818     return true;
9819
9820   return false;
9821 }
9822
9823 static bool isZero(SDValue V) {
9824   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9825   return C && C->isNullValue();
9826 }
9827
9828 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9829   if (V.getOpcode() != ISD::TRUNCATE)
9830     return false;
9831
9832   SDValue VOp0 = V.getOperand(0);
9833   unsigned InBits = VOp0.getValueSizeInBits();
9834   unsigned Bits = V.getValueSizeInBits();
9835   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9836 }
9837
9838 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9839   bool addTest = true;
9840   SDValue Cond  = Op.getOperand(0);
9841   SDValue Op1 = Op.getOperand(1);
9842   SDValue Op2 = Op.getOperand(2);
9843   SDLoc DL(Op);
9844   EVT VT = Op1.getValueType();
9845   SDValue CC;
9846
9847   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
9848   // are available. Otherwise fp cmovs get lowered into a less efficient branch
9849   // sequence later on.
9850   if (Cond.getOpcode() == ISD::SETCC &&
9851       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
9852        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
9853       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
9854     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
9855     int SSECC = translateX86FSETCC(
9856         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
9857
9858     if (SSECC != 8) {
9859       unsigned Opcode = VT == MVT::f32 ? X86ISD::FSETCCss : X86ISD::FSETCCsd;
9860       SDValue Cmp = DAG.getNode(Opcode, DL, VT, CondOp0, CondOp1,
9861                                 DAG.getConstant(SSECC, MVT::i8));
9862       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
9863       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
9864       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
9865     }
9866   }
9867
9868   if (Cond.getOpcode() == ISD::SETCC) {
9869     SDValue NewCond = LowerSETCC(Cond, DAG);
9870     if (NewCond.getNode())
9871       Cond = NewCond;
9872   }
9873
9874   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9875   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9876   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9877   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9878   if (Cond.getOpcode() == X86ISD::SETCC &&
9879       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9880       isZero(Cond.getOperand(1).getOperand(1))) {
9881     SDValue Cmp = Cond.getOperand(1);
9882
9883     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9884
9885     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9886         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9887       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9888
9889       SDValue CmpOp0 = Cmp.getOperand(0);
9890       // Apply further optimizations for special cases
9891       // (select (x != 0), -1, 0) -> neg & sbb
9892       // (select (x == 0), 0, -1) -> neg & sbb
9893       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9894         if (YC->isNullValue() &&
9895             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9896           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9897           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9898                                     DAG.getConstant(0, CmpOp0.getValueType()),
9899                                     CmpOp0);
9900           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9901                                     DAG.getConstant(X86::COND_B, MVT::i8),
9902                                     SDValue(Neg.getNode(), 1));
9903           return Res;
9904         }
9905
9906       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9907                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9908       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9909
9910       SDValue Res =   // Res = 0 or -1.
9911         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9912                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9913
9914       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9915         Res = DAG.getNOT(DL, Res, Res.getValueType());
9916
9917       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9918       if (N2C == 0 || !N2C->isNullValue())
9919         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9920       return Res;
9921     }
9922   }
9923
9924   // Look past (and (setcc_carry (cmp ...)), 1).
9925   if (Cond.getOpcode() == ISD::AND &&
9926       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9927     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9928     if (C && C->getAPIntValue() == 1)
9929       Cond = Cond.getOperand(0);
9930   }
9931
9932   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9933   // setting operand in place of the X86ISD::SETCC.
9934   unsigned CondOpcode = Cond.getOpcode();
9935   if (CondOpcode == X86ISD::SETCC ||
9936       CondOpcode == X86ISD::SETCC_CARRY) {
9937     CC = Cond.getOperand(0);
9938
9939     SDValue Cmp = Cond.getOperand(1);
9940     unsigned Opc = Cmp.getOpcode();
9941     MVT VT = Op.getValueType().getSimpleVT();
9942
9943     bool IllegalFPCMov = false;
9944     if (VT.isFloatingPoint() && !VT.isVector() &&
9945         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9946       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9947
9948     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9949         Opc == X86ISD::BT) { // FIXME
9950       Cond = Cmp;
9951       addTest = false;
9952     }
9953   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9954              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9955              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9956               Cond.getOperand(0).getValueType() != MVT::i8)) {
9957     SDValue LHS = Cond.getOperand(0);
9958     SDValue RHS = Cond.getOperand(1);
9959     unsigned X86Opcode;
9960     unsigned X86Cond;
9961     SDVTList VTs;
9962     switch (CondOpcode) {
9963     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9964     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9965     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9966     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9967     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9968     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9969     default: llvm_unreachable("unexpected overflowing operator");
9970     }
9971     if (CondOpcode == ISD::UMULO)
9972       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9973                           MVT::i32);
9974     else
9975       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9976
9977     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9978
9979     if (CondOpcode == ISD::UMULO)
9980       Cond = X86Op.getValue(2);
9981     else
9982       Cond = X86Op.getValue(1);
9983
9984     CC = DAG.getConstant(X86Cond, MVT::i8);
9985     addTest = false;
9986   }
9987
9988   if (addTest) {
9989     // Look pass the truncate if the high bits are known zero.
9990     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9991         Cond = Cond.getOperand(0);
9992
9993     // We know the result of AND is compared against zero. Try to match
9994     // it to BT.
9995     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9996       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9997       if (NewSetCC.getNode()) {
9998         CC = NewSetCC.getOperand(0);
9999         Cond = NewSetCC.getOperand(1);
10000         addTest = false;
10001       }
10002     }
10003   }
10004
10005   if (addTest) {
10006     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10007     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10008   }
10009
10010   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10011   // a <  b ?  0 : -1 -> RES = setcc_carry
10012   // a >= b ? -1 :  0 -> RES = setcc_carry
10013   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10014   if (Cond.getOpcode() == X86ISD::SUB) {
10015     Cond = ConvertCmpIfNecessary(Cond, DAG);
10016     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10017
10018     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10019         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10020       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10021                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10022       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10023         return DAG.getNOT(DL, Res, Res.getValueType());
10024       return Res;
10025     }
10026   }
10027
10028   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10029   // widen the cmov and push the truncate through. This avoids introducing a new
10030   // branch during isel and doesn't add any extensions.
10031   if (Op.getValueType() == MVT::i8 &&
10032       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10033     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10034     if (T1.getValueType() == T2.getValueType() &&
10035         // Blacklist CopyFromReg to avoid partial register stalls.
10036         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10037       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10038       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10039       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10040     }
10041   }
10042
10043   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10044   // condition is true.
10045   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10046   SDValue Ops[] = { Op2, Op1, CC, Cond };
10047   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10048 }
10049
10050 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
10051                                             SelectionDAG &DAG) const {
10052   MVT VT = Op->getValueType(0).getSimpleVT();
10053   SDValue In = Op->getOperand(0);
10054   MVT InVT = In.getValueType().getSimpleVT();
10055   SDLoc dl(Op);
10056
10057   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10058       (VT != MVT::v8i32 || InVT != MVT::v8i16))
10059     return SDValue();
10060
10061   if (Subtarget->hasInt256())
10062     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10063
10064   // Optimize vectors in AVX mode
10065   // Sign extend  v8i16 to v8i32 and
10066   //              v4i32 to v4i64
10067   //
10068   // Divide input vector into two parts
10069   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10070   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10071   // concat the vectors to original VT
10072
10073   unsigned NumElems = InVT.getVectorNumElements();
10074   SDValue Undef = DAG.getUNDEF(InVT);
10075
10076   SmallVector<int,8> ShufMask1(NumElems, -1);
10077   for (unsigned i = 0; i != NumElems/2; ++i)
10078     ShufMask1[i] = i;
10079
10080   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10081
10082   SmallVector<int,8> ShufMask2(NumElems, -1);
10083   for (unsigned i = 0; i != NumElems/2; ++i)
10084     ShufMask2[i] = i + NumElems/2;
10085
10086   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10087
10088   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10089                                 VT.getVectorNumElements()/2);
10090
10091   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10092   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10093
10094   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10095 }
10096
10097 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10098 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10099 // from the AND / OR.
10100 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10101   Opc = Op.getOpcode();
10102   if (Opc != ISD::OR && Opc != ISD::AND)
10103     return false;
10104   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10105           Op.getOperand(0).hasOneUse() &&
10106           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10107           Op.getOperand(1).hasOneUse());
10108 }
10109
10110 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10111 // 1 and that the SETCC node has a single use.
10112 static bool isXor1OfSetCC(SDValue Op) {
10113   if (Op.getOpcode() != ISD::XOR)
10114     return false;
10115   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10116   if (N1C && N1C->getAPIntValue() == 1) {
10117     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10118       Op.getOperand(0).hasOneUse();
10119   }
10120   return false;
10121 }
10122
10123 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10124   bool addTest = true;
10125   SDValue Chain = Op.getOperand(0);
10126   SDValue Cond  = Op.getOperand(1);
10127   SDValue Dest  = Op.getOperand(2);
10128   SDLoc dl(Op);
10129   SDValue CC;
10130   bool Inverted = false;
10131
10132   if (Cond.getOpcode() == ISD::SETCC) {
10133     // Check for setcc([su]{add,sub,mul}o == 0).
10134     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10135         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10136         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10137         Cond.getOperand(0).getResNo() == 1 &&
10138         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10139          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10140          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10141          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10142          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10143          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10144       Inverted = true;
10145       Cond = Cond.getOperand(0);
10146     } else {
10147       SDValue NewCond = LowerSETCC(Cond, DAG);
10148       if (NewCond.getNode())
10149         Cond = NewCond;
10150     }
10151   }
10152 #if 0
10153   // FIXME: LowerXALUO doesn't handle these!!
10154   else if (Cond.getOpcode() == X86ISD::ADD  ||
10155            Cond.getOpcode() == X86ISD::SUB  ||
10156            Cond.getOpcode() == X86ISD::SMUL ||
10157            Cond.getOpcode() == X86ISD::UMUL)
10158     Cond = LowerXALUO(Cond, DAG);
10159 #endif
10160
10161   // Look pass (and (setcc_carry (cmp ...)), 1).
10162   if (Cond.getOpcode() == ISD::AND &&
10163       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10164     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10165     if (C && C->getAPIntValue() == 1)
10166       Cond = Cond.getOperand(0);
10167   }
10168
10169   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10170   // setting operand in place of the X86ISD::SETCC.
10171   unsigned CondOpcode = Cond.getOpcode();
10172   if (CondOpcode == X86ISD::SETCC ||
10173       CondOpcode == X86ISD::SETCC_CARRY) {
10174     CC = Cond.getOperand(0);
10175
10176     SDValue Cmp = Cond.getOperand(1);
10177     unsigned Opc = Cmp.getOpcode();
10178     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10179     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10180       Cond = Cmp;
10181       addTest = false;
10182     } else {
10183       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10184       default: break;
10185       case X86::COND_O:
10186       case X86::COND_B:
10187         // These can only come from an arithmetic instruction with overflow,
10188         // e.g. SADDO, UADDO.
10189         Cond = Cond.getNode()->getOperand(1);
10190         addTest = false;
10191         break;
10192       }
10193     }
10194   }
10195   CondOpcode = Cond.getOpcode();
10196   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10197       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10198       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10199        Cond.getOperand(0).getValueType() != MVT::i8)) {
10200     SDValue LHS = Cond.getOperand(0);
10201     SDValue RHS = Cond.getOperand(1);
10202     unsigned X86Opcode;
10203     unsigned X86Cond;
10204     SDVTList VTs;
10205     switch (CondOpcode) {
10206     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10207     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10208     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10209     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10210     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10211     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10212     default: llvm_unreachable("unexpected overflowing operator");
10213     }
10214     if (Inverted)
10215       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10216     if (CondOpcode == ISD::UMULO)
10217       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10218                           MVT::i32);
10219     else
10220       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10221
10222     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10223
10224     if (CondOpcode == ISD::UMULO)
10225       Cond = X86Op.getValue(2);
10226     else
10227       Cond = X86Op.getValue(1);
10228
10229     CC = DAG.getConstant(X86Cond, MVT::i8);
10230     addTest = false;
10231   } else {
10232     unsigned CondOpc;
10233     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10234       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10235       if (CondOpc == ISD::OR) {
10236         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10237         // two branches instead of an explicit OR instruction with a
10238         // separate test.
10239         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10240             isX86LogicalCmp(Cmp)) {
10241           CC = Cond.getOperand(0).getOperand(0);
10242           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10243                               Chain, Dest, CC, Cmp);
10244           CC = Cond.getOperand(1).getOperand(0);
10245           Cond = Cmp;
10246           addTest = false;
10247         }
10248       } else { // ISD::AND
10249         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10250         // two branches instead of an explicit AND instruction with a
10251         // separate test. However, we only do this if this block doesn't
10252         // have a fall-through edge, because this requires an explicit
10253         // jmp when the condition is false.
10254         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10255             isX86LogicalCmp(Cmp) &&
10256             Op.getNode()->hasOneUse()) {
10257           X86::CondCode CCode =
10258             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10259           CCode = X86::GetOppositeBranchCondition(CCode);
10260           CC = DAG.getConstant(CCode, MVT::i8);
10261           SDNode *User = *Op.getNode()->use_begin();
10262           // Look for an unconditional branch following this conditional branch.
10263           // We need this because we need to reverse the successors in order
10264           // to implement FCMP_OEQ.
10265           if (User->getOpcode() == ISD::BR) {
10266             SDValue FalseBB = User->getOperand(1);
10267             SDNode *NewBR =
10268               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10269             assert(NewBR == User);
10270             (void)NewBR;
10271             Dest = FalseBB;
10272
10273             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10274                                 Chain, Dest, CC, Cmp);
10275             X86::CondCode CCode =
10276               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10277             CCode = X86::GetOppositeBranchCondition(CCode);
10278             CC = DAG.getConstant(CCode, MVT::i8);
10279             Cond = Cmp;
10280             addTest = false;
10281           }
10282         }
10283       }
10284     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10285       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10286       // It should be transformed during dag combiner except when the condition
10287       // is set by a arithmetics with overflow node.
10288       X86::CondCode CCode =
10289         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10290       CCode = X86::GetOppositeBranchCondition(CCode);
10291       CC = DAG.getConstant(CCode, MVT::i8);
10292       Cond = Cond.getOperand(0).getOperand(1);
10293       addTest = false;
10294     } else if (Cond.getOpcode() == ISD::SETCC &&
10295                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10296       // For FCMP_OEQ, we can emit
10297       // two branches instead of an explicit AND instruction with a
10298       // separate test. However, we only do this if this block doesn't
10299       // have a fall-through edge, because this requires an explicit
10300       // jmp when the condition is false.
10301       if (Op.getNode()->hasOneUse()) {
10302         SDNode *User = *Op.getNode()->use_begin();
10303         // Look for an unconditional branch following this conditional branch.
10304         // We need this because we need to reverse the successors in order
10305         // to implement FCMP_OEQ.
10306         if (User->getOpcode() == ISD::BR) {
10307           SDValue FalseBB = User->getOperand(1);
10308           SDNode *NewBR =
10309             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10310           assert(NewBR == User);
10311           (void)NewBR;
10312           Dest = FalseBB;
10313
10314           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10315                                     Cond.getOperand(0), Cond.getOperand(1));
10316           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10317           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10318           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10319                               Chain, Dest, CC, Cmp);
10320           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10321           Cond = Cmp;
10322           addTest = false;
10323         }
10324       }
10325     } else if (Cond.getOpcode() == ISD::SETCC &&
10326                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10327       // For FCMP_UNE, we can emit
10328       // two branches instead of an explicit AND instruction with a
10329       // separate test. However, we only do this if this block doesn't
10330       // have a fall-through edge, because this requires an explicit
10331       // jmp when the condition is false.
10332       if (Op.getNode()->hasOneUse()) {
10333         SDNode *User = *Op.getNode()->use_begin();
10334         // Look for an unconditional branch following this conditional branch.
10335         // We need this because we need to reverse the successors in order
10336         // to implement FCMP_UNE.
10337         if (User->getOpcode() == ISD::BR) {
10338           SDValue FalseBB = User->getOperand(1);
10339           SDNode *NewBR =
10340             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10341           assert(NewBR == User);
10342           (void)NewBR;
10343
10344           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10345                                     Cond.getOperand(0), Cond.getOperand(1));
10346           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10347           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10348           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10349                               Chain, Dest, CC, Cmp);
10350           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10351           Cond = Cmp;
10352           addTest = false;
10353           Dest = FalseBB;
10354         }
10355       }
10356     }
10357   }
10358
10359   if (addTest) {
10360     // Look pass the truncate if the high bits are known zero.
10361     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10362         Cond = Cond.getOperand(0);
10363
10364     // We know the result of AND is compared against zero. Try to match
10365     // it to BT.
10366     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10367       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10368       if (NewSetCC.getNode()) {
10369         CC = NewSetCC.getOperand(0);
10370         Cond = NewSetCC.getOperand(1);
10371         addTest = false;
10372       }
10373     }
10374   }
10375
10376   if (addTest) {
10377     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10378     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10379   }
10380   Cond = ConvertCmpIfNecessary(Cond, DAG);
10381   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10382                      Chain, Dest, CC, Cond);
10383 }
10384
10385 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10386 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10387 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10388 // that the guard pages used by the OS virtual memory manager are allocated in
10389 // correct sequence.
10390 SDValue
10391 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10392                                            SelectionDAG &DAG) const {
10393   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10394           getTargetMachine().Options.EnableSegmentedStacks) &&
10395          "This should be used only on Windows targets or when segmented stacks "
10396          "are being used");
10397   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10398   SDLoc dl(Op);
10399
10400   // Get the inputs.
10401   SDValue Chain = Op.getOperand(0);
10402   SDValue Size  = Op.getOperand(1);
10403   // FIXME: Ensure alignment here
10404
10405   bool Is64Bit = Subtarget->is64Bit();
10406   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10407
10408   if (getTargetMachine().Options.EnableSegmentedStacks) {
10409     MachineFunction &MF = DAG.getMachineFunction();
10410     MachineRegisterInfo &MRI = MF.getRegInfo();
10411
10412     if (Is64Bit) {
10413       // The 64 bit implementation of segmented stacks needs to clobber both r10
10414       // r11. This makes it impossible to use it along with nested parameters.
10415       const Function *F = MF.getFunction();
10416
10417       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10418            I != E; ++I)
10419         if (I->hasNestAttr())
10420           report_fatal_error("Cannot use segmented stacks with functions that "
10421                              "have nested arguments.");
10422     }
10423
10424     const TargetRegisterClass *AddrRegClass =
10425       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10426     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10427     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10428     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10429                                 DAG.getRegister(Vreg, SPTy));
10430     SDValue Ops1[2] = { Value, Chain };
10431     return DAG.getMergeValues(Ops1, 2, dl);
10432   } else {
10433     SDValue Flag;
10434     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10435
10436     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10437     Flag = Chain.getValue(1);
10438     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10439
10440     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10441     Flag = Chain.getValue(1);
10442
10443     const X86RegisterInfo *RegInfo =
10444       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10445     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10446                                SPTy).getValue(1);
10447
10448     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10449     return DAG.getMergeValues(Ops1, 2, dl);
10450   }
10451 }
10452
10453 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10454   MachineFunction &MF = DAG.getMachineFunction();
10455   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10456
10457   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10458   SDLoc DL(Op);
10459
10460   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10461     // vastart just stores the address of the VarArgsFrameIndex slot into the
10462     // memory location argument.
10463     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10464                                    getPointerTy());
10465     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10466                         MachinePointerInfo(SV), false, false, 0);
10467   }
10468
10469   // __va_list_tag:
10470   //   gp_offset         (0 - 6 * 8)
10471   //   fp_offset         (48 - 48 + 8 * 16)
10472   //   overflow_arg_area (point to parameters coming in memory).
10473   //   reg_save_area
10474   SmallVector<SDValue, 8> MemOps;
10475   SDValue FIN = Op.getOperand(1);
10476   // Store gp_offset
10477   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10478                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10479                                                MVT::i32),
10480                                FIN, MachinePointerInfo(SV), false, false, 0);
10481   MemOps.push_back(Store);
10482
10483   // Store fp_offset
10484   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10485                     FIN, DAG.getIntPtrConstant(4));
10486   Store = DAG.getStore(Op.getOperand(0), DL,
10487                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10488                                        MVT::i32),
10489                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10490   MemOps.push_back(Store);
10491
10492   // Store ptr to overflow_arg_area
10493   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10494                     FIN, DAG.getIntPtrConstant(4));
10495   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10496                                     getPointerTy());
10497   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10498                        MachinePointerInfo(SV, 8),
10499                        false, false, 0);
10500   MemOps.push_back(Store);
10501
10502   // Store ptr to reg_save_area.
10503   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10504                     FIN, DAG.getIntPtrConstant(8));
10505   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10506                                     getPointerTy());
10507   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10508                        MachinePointerInfo(SV, 16), false, false, 0);
10509   MemOps.push_back(Store);
10510   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10511                      &MemOps[0], MemOps.size());
10512 }
10513
10514 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10515   assert(Subtarget->is64Bit() &&
10516          "LowerVAARG only handles 64-bit va_arg!");
10517   assert((Subtarget->isTargetLinux() ||
10518           Subtarget->isTargetDarwin()) &&
10519           "Unhandled target in LowerVAARG");
10520   assert(Op.getNode()->getNumOperands() == 4);
10521   SDValue Chain = Op.getOperand(0);
10522   SDValue SrcPtr = Op.getOperand(1);
10523   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10524   unsigned Align = Op.getConstantOperandVal(3);
10525   SDLoc dl(Op);
10526
10527   EVT ArgVT = Op.getNode()->getValueType(0);
10528   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10529   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10530   uint8_t ArgMode;
10531
10532   // Decide which area this value should be read from.
10533   // TODO: Implement the AMD64 ABI in its entirety. This simple
10534   // selection mechanism works only for the basic types.
10535   if (ArgVT == MVT::f80) {
10536     llvm_unreachable("va_arg for f80 not yet implemented");
10537   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10538     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10539   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10540     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10541   } else {
10542     llvm_unreachable("Unhandled argument type in LowerVAARG");
10543   }
10544
10545   if (ArgMode == 2) {
10546     // Sanity Check: Make sure using fp_offset makes sense.
10547     assert(!getTargetMachine().Options.UseSoftFloat &&
10548            !(DAG.getMachineFunction()
10549                 .getFunction()->getAttributes()
10550                 .hasAttribute(AttributeSet::FunctionIndex,
10551                               Attribute::NoImplicitFloat)) &&
10552            Subtarget->hasSSE1());
10553   }
10554
10555   // Insert VAARG_64 node into the DAG
10556   // VAARG_64 returns two values: Variable Argument Address, Chain
10557   SmallVector<SDValue, 11> InstOps;
10558   InstOps.push_back(Chain);
10559   InstOps.push_back(SrcPtr);
10560   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10561   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10562   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10563   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10564   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10565                                           VTs, &InstOps[0], InstOps.size(),
10566                                           MVT::i64,
10567                                           MachinePointerInfo(SV),
10568                                           /*Align=*/0,
10569                                           /*Volatile=*/false,
10570                                           /*ReadMem=*/true,
10571                                           /*WriteMem=*/true);
10572   Chain = VAARG.getValue(1);
10573
10574   // Load the next argument and return it
10575   return DAG.getLoad(ArgVT, dl,
10576                      Chain,
10577                      VAARG,
10578                      MachinePointerInfo(),
10579                      false, false, false, 0);
10580 }
10581
10582 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10583                            SelectionDAG &DAG) {
10584   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10585   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10586   SDValue Chain = Op.getOperand(0);
10587   SDValue DstPtr = Op.getOperand(1);
10588   SDValue SrcPtr = Op.getOperand(2);
10589   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10590   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10591   SDLoc DL(Op);
10592
10593   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10594                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10595                        false,
10596                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10597 }
10598
10599 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10600 // may or may not be a constant. Takes immediate version of shift as input.
10601 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10602                                    SDValue SrcOp, SDValue ShAmt,
10603                                    SelectionDAG &DAG) {
10604   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10605
10606   if (isa<ConstantSDNode>(ShAmt)) {
10607     // Constant may be a TargetConstant. Use a regular constant.
10608     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10609     switch (Opc) {
10610       default: llvm_unreachable("Unknown target vector shift node");
10611       case X86ISD::VSHLI:
10612       case X86ISD::VSRLI:
10613       case X86ISD::VSRAI:
10614         return DAG.getNode(Opc, dl, VT, SrcOp,
10615                            DAG.getConstant(ShiftAmt, MVT::i32));
10616     }
10617   }
10618
10619   // Change opcode to non-immediate version
10620   switch (Opc) {
10621     default: llvm_unreachable("Unknown target vector shift node");
10622     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10623     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10624     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10625   }
10626
10627   // Need to build a vector containing shift amount
10628   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10629   SDValue ShOps[4];
10630   ShOps[0] = ShAmt;
10631   ShOps[1] = DAG.getConstant(0, MVT::i32);
10632   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10633   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10634
10635   // The return type has to be a 128-bit type with the same element
10636   // type as the input type.
10637   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10638   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10639
10640   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10641   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10642 }
10643
10644 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10645   SDLoc dl(Op);
10646   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10647   switch (IntNo) {
10648   default: return SDValue();    // Don't custom lower most intrinsics.
10649   // Comparison intrinsics.
10650   case Intrinsic::x86_sse_comieq_ss:
10651   case Intrinsic::x86_sse_comilt_ss:
10652   case Intrinsic::x86_sse_comile_ss:
10653   case Intrinsic::x86_sse_comigt_ss:
10654   case Intrinsic::x86_sse_comige_ss:
10655   case Intrinsic::x86_sse_comineq_ss:
10656   case Intrinsic::x86_sse_ucomieq_ss:
10657   case Intrinsic::x86_sse_ucomilt_ss:
10658   case Intrinsic::x86_sse_ucomile_ss:
10659   case Intrinsic::x86_sse_ucomigt_ss:
10660   case Intrinsic::x86_sse_ucomige_ss:
10661   case Intrinsic::x86_sse_ucomineq_ss:
10662   case Intrinsic::x86_sse2_comieq_sd:
10663   case Intrinsic::x86_sse2_comilt_sd:
10664   case Intrinsic::x86_sse2_comile_sd:
10665   case Intrinsic::x86_sse2_comigt_sd:
10666   case Intrinsic::x86_sse2_comige_sd:
10667   case Intrinsic::x86_sse2_comineq_sd:
10668   case Intrinsic::x86_sse2_ucomieq_sd:
10669   case Intrinsic::x86_sse2_ucomilt_sd:
10670   case Intrinsic::x86_sse2_ucomile_sd:
10671   case Intrinsic::x86_sse2_ucomigt_sd:
10672   case Intrinsic::x86_sse2_ucomige_sd:
10673   case Intrinsic::x86_sse2_ucomineq_sd: {
10674     unsigned Opc;
10675     ISD::CondCode CC;
10676     switch (IntNo) {
10677     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10678     case Intrinsic::x86_sse_comieq_ss:
10679     case Intrinsic::x86_sse2_comieq_sd:
10680       Opc = X86ISD::COMI;
10681       CC = ISD::SETEQ;
10682       break;
10683     case Intrinsic::x86_sse_comilt_ss:
10684     case Intrinsic::x86_sse2_comilt_sd:
10685       Opc = X86ISD::COMI;
10686       CC = ISD::SETLT;
10687       break;
10688     case Intrinsic::x86_sse_comile_ss:
10689     case Intrinsic::x86_sse2_comile_sd:
10690       Opc = X86ISD::COMI;
10691       CC = ISD::SETLE;
10692       break;
10693     case Intrinsic::x86_sse_comigt_ss:
10694     case Intrinsic::x86_sse2_comigt_sd:
10695       Opc = X86ISD::COMI;
10696       CC = ISD::SETGT;
10697       break;
10698     case Intrinsic::x86_sse_comige_ss:
10699     case Intrinsic::x86_sse2_comige_sd:
10700       Opc = X86ISD::COMI;
10701       CC = ISD::SETGE;
10702       break;
10703     case Intrinsic::x86_sse_comineq_ss:
10704     case Intrinsic::x86_sse2_comineq_sd:
10705       Opc = X86ISD::COMI;
10706       CC = ISD::SETNE;
10707       break;
10708     case Intrinsic::x86_sse_ucomieq_ss:
10709     case Intrinsic::x86_sse2_ucomieq_sd:
10710       Opc = X86ISD::UCOMI;
10711       CC = ISD::SETEQ;
10712       break;
10713     case Intrinsic::x86_sse_ucomilt_ss:
10714     case Intrinsic::x86_sse2_ucomilt_sd:
10715       Opc = X86ISD::UCOMI;
10716       CC = ISD::SETLT;
10717       break;
10718     case Intrinsic::x86_sse_ucomile_ss:
10719     case Intrinsic::x86_sse2_ucomile_sd:
10720       Opc = X86ISD::UCOMI;
10721       CC = ISD::SETLE;
10722       break;
10723     case Intrinsic::x86_sse_ucomigt_ss:
10724     case Intrinsic::x86_sse2_ucomigt_sd:
10725       Opc = X86ISD::UCOMI;
10726       CC = ISD::SETGT;
10727       break;
10728     case Intrinsic::x86_sse_ucomige_ss:
10729     case Intrinsic::x86_sse2_ucomige_sd:
10730       Opc = X86ISD::UCOMI;
10731       CC = ISD::SETGE;
10732       break;
10733     case Intrinsic::x86_sse_ucomineq_ss:
10734     case Intrinsic::x86_sse2_ucomineq_sd:
10735       Opc = X86ISD::UCOMI;
10736       CC = ISD::SETNE;
10737       break;
10738     }
10739
10740     SDValue LHS = Op.getOperand(1);
10741     SDValue RHS = Op.getOperand(2);
10742     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10743     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10744     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10745     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10746                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10747     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10748   }
10749
10750   // Arithmetic intrinsics.
10751   case Intrinsic::x86_sse2_pmulu_dq:
10752   case Intrinsic::x86_avx2_pmulu_dq:
10753     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10754                        Op.getOperand(1), Op.getOperand(2));
10755
10756   // SSE2/AVX2 sub with unsigned saturation intrinsics
10757   case Intrinsic::x86_sse2_psubus_b:
10758   case Intrinsic::x86_sse2_psubus_w:
10759   case Intrinsic::x86_avx2_psubus_b:
10760   case Intrinsic::x86_avx2_psubus_w:
10761     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10762                        Op.getOperand(1), Op.getOperand(2));
10763
10764   // SSE3/AVX horizontal add/sub intrinsics
10765   case Intrinsic::x86_sse3_hadd_ps:
10766   case Intrinsic::x86_sse3_hadd_pd:
10767   case Intrinsic::x86_avx_hadd_ps_256:
10768   case Intrinsic::x86_avx_hadd_pd_256:
10769   case Intrinsic::x86_sse3_hsub_ps:
10770   case Intrinsic::x86_sse3_hsub_pd:
10771   case Intrinsic::x86_avx_hsub_ps_256:
10772   case Intrinsic::x86_avx_hsub_pd_256:
10773   case Intrinsic::x86_ssse3_phadd_w_128:
10774   case Intrinsic::x86_ssse3_phadd_d_128:
10775   case Intrinsic::x86_avx2_phadd_w:
10776   case Intrinsic::x86_avx2_phadd_d:
10777   case Intrinsic::x86_ssse3_phsub_w_128:
10778   case Intrinsic::x86_ssse3_phsub_d_128:
10779   case Intrinsic::x86_avx2_phsub_w:
10780   case Intrinsic::x86_avx2_phsub_d: {
10781     unsigned Opcode;
10782     switch (IntNo) {
10783     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10784     case Intrinsic::x86_sse3_hadd_ps:
10785     case Intrinsic::x86_sse3_hadd_pd:
10786     case Intrinsic::x86_avx_hadd_ps_256:
10787     case Intrinsic::x86_avx_hadd_pd_256:
10788       Opcode = X86ISD::FHADD;
10789       break;
10790     case Intrinsic::x86_sse3_hsub_ps:
10791     case Intrinsic::x86_sse3_hsub_pd:
10792     case Intrinsic::x86_avx_hsub_ps_256:
10793     case Intrinsic::x86_avx_hsub_pd_256:
10794       Opcode = X86ISD::FHSUB;
10795       break;
10796     case Intrinsic::x86_ssse3_phadd_w_128:
10797     case Intrinsic::x86_ssse3_phadd_d_128:
10798     case Intrinsic::x86_avx2_phadd_w:
10799     case Intrinsic::x86_avx2_phadd_d:
10800       Opcode = X86ISD::HADD;
10801       break;
10802     case Intrinsic::x86_ssse3_phsub_w_128:
10803     case Intrinsic::x86_ssse3_phsub_d_128:
10804     case Intrinsic::x86_avx2_phsub_w:
10805     case Intrinsic::x86_avx2_phsub_d:
10806       Opcode = X86ISD::HSUB;
10807       break;
10808     }
10809     return DAG.getNode(Opcode, dl, Op.getValueType(),
10810                        Op.getOperand(1), Op.getOperand(2));
10811   }
10812
10813   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10814   case Intrinsic::x86_sse2_pmaxu_b:
10815   case Intrinsic::x86_sse41_pmaxuw:
10816   case Intrinsic::x86_sse41_pmaxud:
10817   case Intrinsic::x86_avx2_pmaxu_b:
10818   case Intrinsic::x86_avx2_pmaxu_w:
10819   case Intrinsic::x86_avx2_pmaxu_d:
10820   case Intrinsic::x86_sse2_pminu_b:
10821   case Intrinsic::x86_sse41_pminuw:
10822   case Intrinsic::x86_sse41_pminud:
10823   case Intrinsic::x86_avx2_pminu_b:
10824   case Intrinsic::x86_avx2_pminu_w:
10825   case Intrinsic::x86_avx2_pminu_d:
10826   case Intrinsic::x86_sse41_pmaxsb:
10827   case Intrinsic::x86_sse2_pmaxs_w:
10828   case Intrinsic::x86_sse41_pmaxsd:
10829   case Intrinsic::x86_avx2_pmaxs_b:
10830   case Intrinsic::x86_avx2_pmaxs_w:
10831   case Intrinsic::x86_avx2_pmaxs_d:
10832   case Intrinsic::x86_sse41_pminsb:
10833   case Intrinsic::x86_sse2_pmins_w:
10834   case Intrinsic::x86_sse41_pminsd:
10835   case Intrinsic::x86_avx2_pmins_b:
10836   case Intrinsic::x86_avx2_pmins_w:
10837   case Intrinsic::x86_avx2_pmins_d: {
10838     unsigned Opcode;
10839     switch (IntNo) {
10840     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10841     case Intrinsic::x86_sse2_pmaxu_b:
10842     case Intrinsic::x86_sse41_pmaxuw:
10843     case Intrinsic::x86_sse41_pmaxud:
10844     case Intrinsic::x86_avx2_pmaxu_b:
10845     case Intrinsic::x86_avx2_pmaxu_w:
10846     case Intrinsic::x86_avx2_pmaxu_d:
10847       Opcode = X86ISD::UMAX;
10848       break;
10849     case Intrinsic::x86_sse2_pminu_b:
10850     case Intrinsic::x86_sse41_pminuw:
10851     case Intrinsic::x86_sse41_pminud:
10852     case Intrinsic::x86_avx2_pminu_b:
10853     case Intrinsic::x86_avx2_pminu_w:
10854     case Intrinsic::x86_avx2_pminu_d:
10855       Opcode = X86ISD::UMIN;
10856       break;
10857     case Intrinsic::x86_sse41_pmaxsb:
10858     case Intrinsic::x86_sse2_pmaxs_w:
10859     case Intrinsic::x86_sse41_pmaxsd:
10860     case Intrinsic::x86_avx2_pmaxs_b:
10861     case Intrinsic::x86_avx2_pmaxs_w:
10862     case Intrinsic::x86_avx2_pmaxs_d:
10863       Opcode = X86ISD::SMAX;
10864       break;
10865     case Intrinsic::x86_sse41_pminsb:
10866     case Intrinsic::x86_sse2_pmins_w:
10867     case Intrinsic::x86_sse41_pminsd:
10868     case Intrinsic::x86_avx2_pmins_b:
10869     case Intrinsic::x86_avx2_pmins_w:
10870     case Intrinsic::x86_avx2_pmins_d:
10871       Opcode = X86ISD::SMIN;
10872       break;
10873     }
10874     return DAG.getNode(Opcode, dl, Op.getValueType(),
10875                        Op.getOperand(1), Op.getOperand(2));
10876   }
10877
10878   // SSE/SSE2/AVX floating point max/min intrinsics.
10879   case Intrinsic::x86_sse_max_ps:
10880   case Intrinsic::x86_sse2_max_pd:
10881   case Intrinsic::x86_avx_max_ps_256:
10882   case Intrinsic::x86_avx_max_pd_256:
10883   case Intrinsic::x86_sse_min_ps:
10884   case Intrinsic::x86_sse2_min_pd:
10885   case Intrinsic::x86_avx_min_ps_256:
10886   case Intrinsic::x86_avx_min_pd_256: {
10887     unsigned Opcode;
10888     switch (IntNo) {
10889     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10890     case Intrinsic::x86_sse_max_ps:
10891     case Intrinsic::x86_sse2_max_pd:
10892     case Intrinsic::x86_avx_max_ps_256:
10893     case Intrinsic::x86_avx_max_pd_256:
10894       Opcode = X86ISD::FMAX;
10895       break;
10896     case Intrinsic::x86_sse_min_ps:
10897     case Intrinsic::x86_sse2_min_pd:
10898     case Intrinsic::x86_avx_min_ps_256:
10899     case Intrinsic::x86_avx_min_pd_256:
10900       Opcode = X86ISD::FMIN;
10901       break;
10902     }
10903     return DAG.getNode(Opcode, dl, Op.getValueType(),
10904                        Op.getOperand(1), Op.getOperand(2));
10905   }
10906
10907   // AVX2 variable shift intrinsics
10908   case Intrinsic::x86_avx2_psllv_d:
10909   case Intrinsic::x86_avx2_psllv_q:
10910   case Intrinsic::x86_avx2_psllv_d_256:
10911   case Intrinsic::x86_avx2_psllv_q_256:
10912   case Intrinsic::x86_avx2_psrlv_d:
10913   case Intrinsic::x86_avx2_psrlv_q:
10914   case Intrinsic::x86_avx2_psrlv_d_256:
10915   case Intrinsic::x86_avx2_psrlv_q_256:
10916   case Intrinsic::x86_avx2_psrav_d:
10917   case Intrinsic::x86_avx2_psrav_d_256: {
10918     unsigned Opcode;
10919     switch (IntNo) {
10920     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10921     case Intrinsic::x86_avx2_psllv_d:
10922     case Intrinsic::x86_avx2_psllv_q:
10923     case Intrinsic::x86_avx2_psllv_d_256:
10924     case Intrinsic::x86_avx2_psllv_q_256:
10925       Opcode = ISD::SHL;
10926       break;
10927     case Intrinsic::x86_avx2_psrlv_d:
10928     case Intrinsic::x86_avx2_psrlv_q:
10929     case Intrinsic::x86_avx2_psrlv_d_256:
10930     case Intrinsic::x86_avx2_psrlv_q_256:
10931       Opcode = ISD::SRL;
10932       break;
10933     case Intrinsic::x86_avx2_psrav_d:
10934     case Intrinsic::x86_avx2_psrav_d_256:
10935       Opcode = ISD::SRA;
10936       break;
10937     }
10938     return DAG.getNode(Opcode, dl, Op.getValueType(),
10939                        Op.getOperand(1), Op.getOperand(2));
10940   }
10941
10942   case Intrinsic::x86_ssse3_pshuf_b_128:
10943   case Intrinsic::x86_avx2_pshuf_b:
10944     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10945                        Op.getOperand(1), Op.getOperand(2));
10946
10947   case Intrinsic::x86_ssse3_psign_b_128:
10948   case Intrinsic::x86_ssse3_psign_w_128:
10949   case Intrinsic::x86_ssse3_psign_d_128:
10950   case Intrinsic::x86_avx2_psign_b:
10951   case Intrinsic::x86_avx2_psign_w:
10952   case Intrinsic::x86_avx2_psign_d:
10953     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10954                        Op.getOperand(1), Op.getOperand(2));
10955
10956   case Intrinsic::x86_sse41_insertps:
10957     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10958                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10959
10960   case Intrinsic::x86_avx_vperm2f128_ps_256:
10961   case Intrinsic::x86_avx_vperm2f128_pd_256:
10962   case Intrinsic::x86_avx_vperm2f128_si_256:
10963   case Intrinsic::x86_avx2_vperm2i128:
10964     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10965                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10966
10967   case Intrinsic::x86_avx2_permd:
10968   case Intrinsic::x86_avx2_permps:
10969     // Operands intentionally swapped. Mask is last operand to intrinsic,
10970     // but second operand for node/intruction.
10971     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10972                        Op.getOperand(2), Op.getOperand(1));
10973
10974   case Intrinsic::x86_sse_sqrt_ps:
10975   case Intrinsic::x86_sse2_sqrt_pd:
10976   case Intrinsic::x86_avx_sqrt_ps_256:
10977   case Intrinsic::x86_avx_sqrt_pd_256:
10978     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10979
10980   // ptest and testp intrinsics. The intrinsic these come from are designed to
10981   // return an integer value, not just an instruction so lower it to the ptest
10982   // or testp pattern and a setcc for the result.
10983   case Intrinsic::x86_sse41_ptestz:
10984   case Intrinsic::x86_sse41_ptestc:
10985   case Intrinsic::x86_sse41_ptestnzc:
10986   case Intrinsic::x86_avx_ptestz_256:
10987   case Intrinsic::x86_avx_ptestc_256:
10988   case Intrinsic::x86_avx_ptestnzc_256:
10989   case Intrinsic::x86_avx_vtestz_ps:
10990   case Intrinsic::x86_avx_vtestc_ps:
10991   case Intrinsic::x86_avx_vtestnzc_ps:
10992   case Intrinsic::x86_avx_vtestz_pd:
10993   case Intrinsic::x86_avx_vtestc_pd:
10994   case Intrinsic::x86_avx_vtestnzc_pd:
10995   case Intrinsic::x86_avx_vtestz_ps_256:
10996   case Intrinsic::x86_avx_vtestc_ps_256:
10997   case Intrinsic::x86_avx_vtestnzc_ps_256:
10998   case Intrinsic::x86_avx_vtestz_pd_256:
10999   case Intrinsic::x86_avx_vtestc_pd_256:
11000   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11001     bool IsTestPacked = false;
11002     unsigned X86CC;
11003     switch (IntNo) {
11004     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11005     case Intrinsic::x86_avx_vtestz_ps:
11006     case Intrinsic::x86_avx_vtestz_pd:
11007     case Intrinsic::x86_avx_vtestz_ps_256:
11008     case Intrinsic::x86_avx_vtestz_pd_256:
11009       IsTestPacked = true; // Fallthrough
11010     case Intrinsic::x86_sse41_ptestz:
11011     case Intrinsic::x86_avx_ptestz_256:
11012       // ZF = 1
11013       X86CC = X86::COND_E;
11014       break;
11015     case Intrinsic::x86_avx_vtestc_ps:
11016     case Intrinsic::x86_avx_vtestc_pd:
11017     case Intrinsic::x86_avx_vtestc_ps_256:
11018     case Intrinsic::x86_avx_vtestc_pd_256:
11019       IsTestPacked = true; // Fallthrough
11020     case Intrinsic::x86_sse41_ptestc:
11021     case Intrinsic::x86_avx_ptestc_256:
11022       // CF = 1
11023       X86CC = X86::COND_B;
11024       break;
11025     case Intrinsic::x86_avx_vtestnzc_ps:
11026     case Intrinsic::x86_avx_vtestnzc_pd:
11027     case Intrinsic::x86_avx_vtestnzc_ps_256:
11028     case Intrinsic::x86_avx_vtestnzc_pd_256:
11029       IsTestPacked = true; // Fallthrough
11030     case Intrinsic::x86_sse41_ptestnzc:
11031     case Intrinsic::x86_avx_ptestnzc_256:
11032       // ZF and CF = 0
11033       X86CC = X86::COND_A;
11034       break;
11035     }
11036
11037     SDValue LHS = Op.getOperand(1);
11038     SDValue RHS = Op.getOperand(2);
11039     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11040     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11041     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11042     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11043     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11044   }
11045
11046   // SSE/AVX shift intrinsics
11047   case Intrinsic::x86_sse2_psll_w:
11048   case Intrinsic::x86_sse2_psll_d:
11049   case Intrinsic::x86_sse2_psll_q:
11050   case Intrinsic::x86_avx2_psll_w:
11051   case Intrinsic::x86_avx2_psll_d:
11052   case Intrinsic::x86_avx2_psll_q:
11053   case Intrinsic::x86_sse2_psrl_w:
11054   case Intrinsic::x86_sse2_psrl_d:
11055   case Intrinsic::x86_sse2_psrl_q:
11056   case Intrinsic::x86_avx2_psrl_w:
11057   case Intrinsic::x86_avx2_psrl_d:
11058   case Intrinsic::x86_avx2_psrl_q:
11059   case Intrinsic::x86_sse2_psra_w:
11060   case Intrinsic::x86_sse2_psra_d:
11061   case Intrinsic::x86_avx2_psra_w:
11062   case Intrinsic::x86_avx2_psra_d: {
11063     unsigned Opcode;
11064     switch (IntNo) {
11065     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11066     case Intrinsic::x86_sse2_psll_w:
11067     case Intrinsic::x86_sse2_psll_d:
11068     case Intrinsic::x86_sse2_psll_q:
11069     case Intrinsic::x86_avx2_psll_w:
11070     case Intrinsic::x86_avx2_psll_d:
11071     case Intrinsic::x86_avx2_psll_q:
11072       Opcode = X86ISD::VSHL;
11073       break;
11074     case Intrinsic::x86_sse2_psrl_w:
11075     case Intrinsic::x86_sse2_psrl_d:
11076     case Intrinsic::x86_sse2_psrl_q:
11077     case Intrinsic::x86_avx2_psrl_w:
11078     case Intrinsic::x86_avx2_psrl_d:
11079     case Intrinsic::x86_avx2_psrl_q:
11080       Opcode = X86ISD::VSRL;
11081       break;
11082     case Intrinsic::x86_sse2_psra_w:
11083     case Intrinsic::x86_sse2_psra_d:
11084     case Intrinsic::x86_avx2_psra_w:
11085     case Intrinsic::x86_avx2_psra_d:
11086       Opcode = X86ISD::VSRA;
11087       break;
11088     }
11089     return DAG.getNode(Opcode, dl, Op.getValueType(),
11090                        Op.getOperand(1), Op.getOperand(2));
11091   }
11092
11093   // SSE/AVX immediate shift intrinsics
11094   case Intrinsic::x86_sse2_pslli_w:
11095   case Intrinsic::x86_sse2_pslli_d:
11096   case Intrinsic::x86_sse2_pslli_q:
11097   case Intrinsic::x86_avx2_pslli_w:
11098   case Intrinsic::x86_avx2_pslli_d:
11099   case Intrinsic::x86_avx2_pslli_q:
11100   case Intrinsic::x86_sse2_psrli_w:
11101   case Intrinsic::x86_sse2_psrli_d:
11102   case Intrinsic::x86_sse2_psrli_q:
11103   case Intrinsic::x86_avx2_psrli_w:
11104   case Intrinsic::x86_avx2_psrli_d:
11105   case Intrinsic::x86_avx2_psrli_q:
11106   case Intrinsic::x86_sse2_psrai_w:
11107   case Intrinsic::x86_sse2_psrai_d:
11108   case Intrinsic::x86_avx2_psrai_w:
11109   case Intrinsic::x86_avx2_psrai_d: {
11110     unsigned Opcode;
11111     switch (IntNo) {
11112     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11113     case Intrinsic::x86_sse2_pslli_w:
11114     case Intrinsic::x86_sse2_pslli_d:
11115     case Intrinsic::x86_sse2_pslli_q:
11116     case Intrinsic::x86_avx2_pslli_w:
11117     case Intrinsic::x86_avx2_pslli_d:
11118     case Intrinsic::x86_avx2_pslli_q:
11119       Opcode = X86ISD::VSHLI;
11120       break;
11121     case Intrinsic::x86_sse2_psrli_w:
11122     case Intrinsic::x86_sse2_psrli_d:
11123     case Intrinsic::x86_sse2_psrli_q:
11124     case Intrinsic::x86_avx2_psrli_w:
11125     case Intrinsic::x86_avx2_psrli_d:
11126     case Intrinsic::x86_avx2_psrli_q:
11127       Opcode = X86ISD::VSRLI;
11128       break;
11129     case Intrinsic::x86_sse2_psrai_w:
11130     case Intrinsic::x86_sse2_psrai_d:
11131     case Intrinsic::x86_avx2_psrai_w:
11132     case Intrinsic::x86_avx2_psrai_d:
11133       Opcode = X86ISD::VSRAI;
11134       break;
11135     }
11136     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11137                                Op.getOperand(1), Op.getOperand(2), DAG);
11138   }
11139
11140   case Intrinsic::x86_sse42_pcmpistria128:
11141   case Intrinsic::x86_sse42_pcmpestria128:
11142   case Intrinsic::x86_sse42_pcmpistric128:
11143   case Intrinsic::x86_sse42_pcmpestric128:
11144   case Intrinsic::x86_sse42_pcmpistrio128:
11145   case Intrinsic::x86_sse42_pcmpestrio128:
11146   case Intrinsic::x86_sse42_pcmpistris128:
11147   case Intrinsic::x86_sse42_pcmpestris128:
11148   case Intrinsic::x86_sse42_pcmpistriz128:
11149   case Intrinsic::x86_sse42_pcmpestriz128: {
11150     unsigned Opcode;
11151     unsigned X86CC;
11152     switch (IntNo) {
11153     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11154     case Intrinsic::x86_sse42_pcmpistria128:
11155       Opcode = X86ISD::PCMPISTRI;
11156       X86CC = X86::COND_A;
11157       break;
11158     case Intrinsic::x86_sse42_pcmpestria128:
11159       Opcode = X86ISD::PCMPESTRI;
11160       X86CC = X86::COND_A;
11161       break;
11162     case Intrinsic::x86_sse42_pcmpistric128:
11163       Opcode = X86ISD::PCMPISTRI;
11164       X86CC = X86::COND_B;
11165       break;
11166     case Intrinsic::x86_sse42_pcmpestric128:
11167       Opcode = X86ISD::PCMPESTRI;
11168       X86CC = X86::COND_B;
11169       break;
11170     case Intrinsic::x86_sse42_pcmpistrio128:
11171       Opcode = X86ISD::PCMPISTRI;
11172       X86CC = X86::COND_O;
11173       break;
11174     case Intrinsic::x86_sse42_pcmpestrio128:
11175       Opcode = X86ISD::PCMPESTRI;
11176       X86CC = X86::COND_O;
11177       break;
11178     case Intrinsic::x86_sse42_pcmpistris128:
11179       Opcode = X86ISD::PCMPISTRI;
11180       X86CC = X86::COND_S;
11181       break;
11182     case Intrinsic::x86_sse42_pcmpestris128:
11183       Opcode = X86ISD::PCMPESTRI;
11184       X86CC = X86::COND_S;
11185       break;
11186     case Intrinsic::x86_sse42_pcmpistriz128:
11187       Opcode = X86ISD::PCMPISTRI;
11188       X86CC = X86::COND_E;
11189       break;
11190     case Intrinsic::x86_sse42_pcmpestriz128:
11191       Opcode = X86ISD::PCMPESTRI;
11192       X86CC = X86::COND_E;
11193       break;
11194     }
11195     SmallVector<SDValue, 5> NewOps;
11196     NewOps.append(Op->op_begin()+1, Op->op_end());
11197     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11198     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11199     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11200                                 DAG.getConstant(X86CC, MVT::i8),
11201                                 SDValue(PCMP.getNode(), 1));
11202     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11203   }
11204
11205   case Intrinsic::x86_sse42_pcmpistri128:
11206   case Intrinsic::x86_sse42_pcmpestri128: {
11207     unsigned Opcode;
11208     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11209       Opcode = X86ISD::PCMPISTRI;
11210     else
11211       Opcode = X86ISD::PCMPESTRI;
11212
11213     SmallVector<SDValue, 5> NewOps;
11214     NewOps.append(Op->op_begin()+1, Op->op_end());
11215     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11216     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11217   }
11218   case Intrinsic::x86_fma_vfmadd_ps:
11219   case Intrinsic::x86_fma_vfmadd_pd:
11220   case Intrinsic::x86_fma_vfmsub_ps:
11221   case Intrinsic::x86_fma_vfmsub_pd:
11222   case Intrinsic::x86_fma_vfnmadd_ps:
11223   case Intrinsic::x86_fma_vfnmadd_pd:
11224   case Intrinsic::x86_fma_vfnmsub_ps:
11225   case Intrinsic::x86_fma_vfnmsub_pd:
11226   case Intrinsic::x86_fma_vfmaddsub_ps:
11227   case Intrinsic::x86_fma_vfmaddsub_pd:
11228   case Intrinsic::x86_fma_vfmsubadd_ps:
11229   case Intrinsic::x86_fma_vfmsubadd_pd:
11230   case Intrinsic::x86_fma_vfmadd_ps_256:
11231   case Intrinsic::x86_fma_vfmadd_pd_256:
11232   case Intrinsic::x86_fma_vfmsub_ps_256:
11233   case Intrinsic::x86_fma_vfmsub_pd_256:
11234   case Intrinsic::x86_fma_vfnmadd_ps_256:
11235   case Intrinsic::x86_fma_vfnmadd_pd_256:
11236   case Intrinsic::x86_fma_vfnmsub_ps_256:
11237   case Intrinsic::x86_fma_vfnmsub_pd_256:
11238   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11239   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11240   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11241   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
11242     unsigned Opc;
11243     switch (IntNo) {
11244     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11245     case Intrinsic::x86_fma_vfmadd_ps:
11246     case Intrinsic::x86_fma_vfmadd_pd:
11247     case Intrinsic::x86_fma_vfmadd_ps_256:
11248     case Intrinsic::x86_fma_vfmadd_pd_256:
11249       Opc = X86ISD::FMADD;
11250       break;
11251     case Intrinsic::x86_fma_vfmsub_ps:
11252     case Intrinsic::x86_fma_vfmsub_pd:
11253     case Intrinsic::x86_fma_vfmsub_ps_256:
11254     case Intrinsic::x86_fma_vfmsub_pd_256:
11255       Opc = X86ISD::FMSUB;
11256       break;
11257     case Intrinsic::x86_fma_vfnmadd_ps:
11258     case Intrinsic::x86_fma_vfnmadd_pd:
11259     case Intrinsic::x86_fma_vfnmadd_ps_256:
11260     case Intrinsic::x86_fma_vfnmadd_pd_256:
11261       Opc = X86ISD::FNMADD;
11262       break;
11263     case Intrinsic::x86_fma_vfnmsub_ps:
11264     case Intrinsic::x86_fma_vfnmsub_pd:
11265     case Intrinsic::x86_fma_vfnmsub_ps_256:
11266     case Intrinsic::x86_fma_vfnmsub_pd_256:
11267       Opc = X86ISD::FNMSUB;
11268       break;
11269     case Intrinsic::x86_fma_vfmaddsub_ps:
11270     case Intrinsic::x86_fma_vfmaddsub_pd:
11271     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11272     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11273       Opc = X86ISD::FMADDSUB;
11274       break;
11275     case Intrinsic::x86_fma_vfmsubadd_ps:
11276     case Intrinsic::x86_fma_vfmsubadd_pd:
11277     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11278     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11279       Opc = X86ISD::FMSUBADD;
11280       break;
11281     }
11282
11283     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11284                        Op.getOperand(2), Op.getOperand(3));
11285   }
11286   }
11287 }
11288
11289 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
11290   SDLoc dl(Op);
11291   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11292   switch (IntNo) {
11293   default: return SDValue();    // Don't custom lower most intrinsics.
11294
11295   // RDRAND/RDSEED intrinsics.
11296   case Intrinsic::x86_rdrand_16:
11297   case Intrinsic::x86_rdrand_32:
11298   case Intrinsic::x86_rdrand_64:
11299   case Intrinsic::x86_rdseed_16:
11300   case Intrinsic::x86_rdseed_32:
11301   case Intrinsic::x86_rdseed_64: {
11302     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11303                        IntNo == Intrinsic::x86_rdseed_32 ||
11304                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11305                                                             X86ISD::RDRAND;
11306     // Emit the node with the right value type.
11307     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11308     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11309
11310     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11311     // Otherwise return the value from Rand, which is always 0, casted to i32.
11312     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11313                       DAG.getConstant(1, Op->getValueType(1)),
11314                       DAG.getConstant(X86::COND_B, MVT::i32),
11315                       SDValue(Result.getNode(), 1) };
11316     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11317                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11318                                   Ops, array_lengthof(Ops));
11319
11320     // Return { result, isValid, chain }.
11321     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11322                        SDValue(Result.getNode(), 2));
11323   }
11324
11325   // XTEST intrinsics.
11326   case Intrinsic::x86_xtest: {
11327     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11328     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11329     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11330                                 DAG.getConstant(X86::COND_NE, MVT::i8),
11331                                 InTrans);
11332     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11333     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11334                        Ret, SDValue(InTrans.getNode(), 1));
11335   }
11336   }
11337 }
11338
11339 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11340                                            SelectionDAG &DAG) const {
11341   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11342   MFI->setReturnAddressIsTaken(true);
11343
11344   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11345   SDLoc dl(Op);
11346   EVT PtrVT = getPointerTy();
11347
11348   if (Depth > 0) {
11349     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11350     const X86RegisterInfo *RegInfo =
11351       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11352     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11353     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11354                        DAG.getNode(ISD::ADD, dl, PtrVT,
11355                                    FrameAddr, Offset),
11356                        MachinePointerInfo(), false, false, false, 0);
11357   }
11358
11359   // Just load the return address.
11360   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11361   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11362                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11363 }
11364
11365 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11366   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11367   MFI->setFrameAddressIsTaken(true);
11368
11369   EVT VT = Op.getValueType();
11370   SDLoc dl(Op);  // FIXME probably not meaningful
11371   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11372   const X86RegisterInfo *RegInfo =
11373     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11374   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11375   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11376           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11377          "Invalid Frame Register!");
11378   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11379   while (Depth--)
11380     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11381                             MachinePointerInfo(),
11382                             false, false, false, 0);
11383   return FrameAddr;
11384 }
11385
11386 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11387                                                      SelectionDAG &DAG) const {
11388   const X86RegisterInfo *RegInfo =
11389     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11390   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11391 }
11392
11393 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11394   SDValue Chain     = Op.getOperand(0);
11395   SDValue Offset    = Op.getOperand(1);
11396   SDValue Handler   = Op.getOperand(2);
11397   SDLoc dl      (Op);
11398
11399   EVT PtrVT = getPointerTy();
11400   const X86RegisterInfo *RegInfo =
11401     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11402   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11403   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11404           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11405          "Invalid Frame Register!");
11406   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11407   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11408
11409   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11410                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11411   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11412   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11413                        false, false, 0);
11414   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11415
11416   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11417                      DAG.getRegister(StoreAddrReg, PtrVT));
11418 }
11419
11420 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11421                                                SelectionDAG &DAG) const {
11422   SDLoc DL(Op);
11423   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11424                      DAG.getVTList(MVT::i32, MVT::Other),
11425                      Op.getOperand(0), Op.getOperand(1));
11426 }
11427
11428 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11429                                                 SelectionDAG &DAG) const {
11430   SDLoc DL(Op);
11431   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11432                      Op.getOperand(0), Op.getOperand(1));
11433 }
11434
11435 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11436   return Op.getOperand(0);
11437 }
11438
11439 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11440                                                 SelectionDAG &DAG) const {
11441   SDValue Root = Op.getOperand(0);
11442   SDValue Trmp = Op.getOperand(1); // trampoline
11443   SDValue FPtr = Op.getOperand(2); // nested function
11444   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11445   SDLoc dl (Op);
11446
11447   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11448   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11449
11450   if (Subtarget->is64Bit()) {
11451     SDValue OutChains[6];
11452
11453     // Large code-model.
11454     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11455     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11456
11457     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11458     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11459
11460     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11461
11462     // Load the pointer to the nested function into R11.
11463     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11464     SDValue Addr = Trmp;
11465     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11466                                 Addr, MachinePointerInfo(TrmpAddr),
11467                                 false, false, 0);
11468
11469     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11470                        DAG.getConstant(2, MVT::i64));
11471     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11472                                 MachinePointerInfo(TrmpAddr, 2),
11473                                 false, false, 2);
11474
11475     // Load the 'nest' parameter value into R10.
11476     // R10 is specified in X86CallingConv.td
11477     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11478     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11479                        DAG.getConstant(10, MVT::i64));
11480     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11481                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11482                                 false, false, 0);
11483
11484     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11485                        DAG.getConstant(12, MVT::i64));
11486     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11487                                 MachinePointerInfo(TrmpAddr, 12),
11488                                 false, false, 2);
11489
11490     // Jump to the nested function.
11491     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11492     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11493                        DAG.getConstant(20, MVT::i64));
11494     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11495                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11496                                 false, false, 0);
11497
11498     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11499     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11500                        DAG.getConstant(22, MVT::i64));
11501     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11502                                 MachinePointerInfo(TrmpAddr, 22),
11503                                 false, false, 0);
11504
11505     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11506   } else {
11507     const Function *Func =
11508       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11509     CallingConv::ID CC = Func->getCallingConv();
11510     unsigned NestReg;
11511
11512     switch (CC) {
11513     default:
11514       llvm_unreachable("Unsupported calling convention");
11515     case CallingConv::C:
11516     case CallingConv::X86_StdCall: {
11517       // Pass 'nest' parameter in ECX.
11518       // Must be kept in sync with X86CallingConv.td
11519       NestReg = X86::ECX;
11520
11521       // Check that ECX wasn't needed by an 'inreg' parameter.
11522       FunctionType *FTy = Func->getFunctionType();
11523       const AttributeSet &Attrs = Func->getAttributes();
11524
11525       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11526         unsigned InRegCount = 0;
11527         unsigned Idx = 1;
11528
11529         for (FunctionType::param_iterator I = FTy->param_begin(),
11530              E = FTy->param_end(); I != E; ++I, ++Idx)
11531           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11532             // FIXME: should only count parameters that are lowered to integers.
11533             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11534
11535         if (InRegCount > 2) {
11536           report_fatal_error("Nest register in use - reduce number of inreg"
11537                              " parameters!");
11538         }
11539       }
11540       break;
11541     }
11542     case CallingConv::X86_FastCall:
11543     case CallingConv::X86_ThisCall:
11544     case CallingConv::Fast:
11545       // Pass 'nest' parameter in EAX.
11546       // Must be kept in sync with X86CallingConv.td
11547       NestReg = X86::EAX;
11548       break;
11549     }
11550
11551     SDValue OutChains[4];
11552     SDValue Addr, Disp;
11553
11554     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11555                        DAG.getConstant(10, MVT::i32));
11556     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11557
11558     // This is storing the opcode for MOV32ri.
11559     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11560     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11561     OutChains[0] = DAG.getStore(Root, dl,
11562                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11563                                 Trmp, MachinePointerInfo(TrmpAddr),
11564                                 false, false, 0);
11565
11566     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11567                        DAG.getConstant(1, MVT::i32));
11568     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11569                                 MachinePointerInfo(TrmpAddr, 1),
11570                                 false, false, 1);
11571
11572     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11573     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11574                        DAG.getConstant(5, MVT::i32));
11575     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11576                                 MachinePointerInfo(TrmpAddr, 5),
11577                                 false, false, 1);
11578
11579     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11580                        DAG.getConstant(6, MVT::i32));
11581     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11582                                 MachinePointerInfo(TrmpAddr, 6),
11583                                 false, false, 1);
11584
11585     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11586   }
11587 }
11588
11589 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11590                                             SelectionDAG &DAG) const {
11591   /*
11592    The rounding mode is in bits 11:10 of FPSR, and has the following
11593    settings:
11594      00 Round to nearest
11595      01 Round to -inf
11596      10 Round to +inf
11597      11 Round to 0
11598
11599   FLT_ROUNDS, on the other hand, expects the following:
11600     -1 Undefined
11601      0 Round to 0
11602      1 Round to nearest
11603      2 Round to +inf
11604      3 Round to -inf
11605
11606   To perform the conversion, we do:
11607     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11608   */
11609
11610   MachineFunction &MF = DAG.getMachineFunction();
11611   const TargetMachine &TM = MF.getTarget();
11612   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11613   unsigned StackAlignment = TFI.getStackAlignment();
11614   EVT VT = Op.getValueType();
11615   SDLoc DL(Op);
11616
11617   // Save FP Control Word to stack slot
11618   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11619   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11620
11621   MachineMemOperand *MMO =
11622    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11623                            MachineMemOperand::MOStore, 2, 2);
11624
11625   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11626   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11627                                           DAG.getVTList(MVT::Other),
11628                                           Ops, array_lengthof(Ops), MVT::i16,
11629                                           MMO);
11630
11631   // Load FP Control Word from stack slot
11632   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11633                             MachinePointerInfo(), false, false, false, 0);
11634
11635   // Transform as necessary
11636   SDValue CWD1 =
11637     DAG.getNode(ISD::SRL, DL, MVT::i16,
11638                 DAG.getNode(ISD::AND, DL, MVT::i16,
11639                             CWD, DAG.getConstant(0x800, MVT::i16)),
11640                 DAG.getConstant(11, MVT::i8));
11641   SDValue CWD2 =
11642     DAG.getNode(ISD::SRL, DL, MVT::i16,
11643                 DAG.getNode(ISD::AND, DL, MVT::i16,
11644                             CWD, DAG.getConstant(0x400, MVT::i16)),
11645                 DAG.getConstant(9, MVT::i8));
11646
11647   SDValue RetVal =
11648     DAG.getNode(ISD::AND, DL, MVT::i16,
11649                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11650                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11651                             DAG.getConstant(1, MVT::i16)),
11652                 DAG.getConstant(3, MVT::i16));
11653
11654   return DAG.getNode((VT.getSizeInBits() < 16 ?
11655                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11656 }
11657
11658 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11659   EVT VT = Op.getValueType();
11660   EVT OpVT = VT;
11661   unsigned NumBits = VT.getSizeInBits();
11662   SDLoc dl(Op);
11663
11664   Op = Op.getOperand(0);
11665   if (VT == MVT::i8) {
11666     // Zero extend to i32 since there is not an i8 bsr.
11667     OpVT = MVT::i32;
11668     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11669   }
11670
11671   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11672   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11673   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11674
11675   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11676   SDValue Ops[] = {
11677     Op,
11678     DAG.getConstant(NumBits+NumBits-1, OpVT),
11679     DAG.getConstant(X86::COND_E, MVT::i8),
11680     Op.getValue(1)
11681   };
11682   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11683
11684   // Finally xor with NumBits-1.
11685   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11686
11687   if (VT == MVT::i8)
11688     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11689   return Op;
11690 }
11691
11692 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11693   EVT VT = Op.getValueType();
11694   EVT OpVT = VT;
11695   unsigned NumBits = VT.getSizeInBits();
11696   SDLoc dl(Op);
11697
11698   Op = Op.getOperand(0);
11699   if (VT == MVT::i8) {
11700     // Zero extend to i32 since there is not an i8 bsr.
11701     OpVT = MVT::i32;
11702     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11703   }
11704
11705   // Issue a bsr (scan bits in reverse).
11706   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11707   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11708
11709   // And xor with NumBits-1.
11710   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11711
11712   if (VT == MVT::i8)
11713     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11714   return Op;
11715 }
11716
11717 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11718   EVT VT = Op.getValueType();
11719   unsigned NumBits = VT.getSizeInBits();
11720   SDLoc dl(Op);
11721   Op = Op.getOperand(0);
11722
11723   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11724   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11725   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11726
11727   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11728   SDValue Ops[] = {
11729     Op,
11730     DAG.getConstant(NumBits, VT),
11731     DAG.getConstant(X86::COND_E, MVT::i8),
11732     Op.getValue(1)
11733   };
11734   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11735 }
11736
11737 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11738 // ones, and then concatenate the result back.
11739 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11740   EVT VT = Op.getValueType();
11741
11742   assert(VT.is256BitVector() && VT.isInteger() &&
11743          "Unsupported value type for operation");
11744
11745   unsigned NumElems = VT.getVectorNumElements();
11746   SDLoc dl(Op);
11747
11748   // Extract the LHS vectors
11749   SDValue LHS = Op.getOperand(0);
11750   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11751   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11752
11753   // Extract the RHS vectors
11754   SDValue RHS = Op.getOperand(1);
11755   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11756   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11757
11758   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11759   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11760
11761   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11762                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11763                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11764 }
11765
11766 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11767   assert(Op.getValueType().is256BitVector() &&
11768          Op.getValueType().isInteger() &&
11769          "Only handle AVX 256-bit vector integer operation");
11770   return Lower256IntArith(Op, DAG);
11771 }
11772
11773 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11774   assert(Op.getValueType().is256BitVector() &&
11775          Op.getValueType().isInteger() &&
11776          "Only handle AVX 256-bit vector integer operation");
11777   return Lower256IntArith(Op, DAG);
11778 }
11779
11780 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11781                         SelectionDAG &DAG) {
11782   SDLoc dl(Op);
11783   EVT VT = Op.getValueType();
11784
11785   // Decompose 256-bit ops into smaller 128-bit ops.
11786   if (VT.is256BitVector() && !Subtarget->hasInt256())
11787     return Lower256IntArith(Op, DAG);
11788
11789   SDValue A = Op.getOperand(0);
11790   SDValue B = Op.getOperand(1);
11791
11792   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11793   if (VT == MVT::v4i32) {
11794     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11795            "Should not custom lower when pmuldq is available!");
11796
11797     // Extract the odd parts.
11798     static const int UnpackMask[] = { 1, -1, 3, -1 };
11799     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11800     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11801
11802     // Multiply the even parts.
11803     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11804     // Now multiply odd parts.
11805     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11806
11807     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11808     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11809
11810     // Merge the two vectors back together with a shuffle. This expands into 2
11811     // shuffles.
11812     static const int ShufMask[] = { 0, 4, 2, 6 };
11813     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11814   }
11815
11816   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11817          "Only know how to lower V2I64/V4I64 multiply");
11818
11819   //  Ahi = psrlqi(a, 32);
11820   //  Bhi = psrlqi(b, 32);
11821   //
11822   //  AloBlo = pmuludq(a, b);
11823   //  AloBhi = pmuludq(a, Bhi);
11824   //  AhiBlo = pmuludq(Ahi, b);
11825
11826   //  AloBhi = psllqi(AloBhi, 32);
11827   //  AhiBlo = psllqi(AhiBlo, 32);
11828   //  return AloBlo + AloBhi + AhiBlo;
11829
11830   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11831
11832   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11833   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11834
11835   // Bit cast to 32-bit vectors for MULUDQ
11836   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11837   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11838   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11839   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11840   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11841
11842   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11843   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11844   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11845
11846   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11847   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11848
11849   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11850   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11851 }
11852
11853 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11854   EVT VT = Op.getValueType();
11855   EVT EltTy = VT.getVectorElementType();
11856   unsigned NumElts = VT.getVectorNumElements();
11857   SDValue N0 = Op.getOperand(0);
11858   SDLoc dl(Op);
11859
11860   // Lower sdiv X, pow2-const.
11861   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11862   if (!C)
11863     return SDValue();
11864
11865   APInt SplatValue, SplatUndef;
11866   unsigned SplatBitSize;
11867   bool HasAnyUndefs;
11868   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11869                           HasAnyUndefs) ||
11870       EltTy.getSizeInBits() < SplatBitSize)
11871     return SDValue();
11872
11873   if ((SplatValue != 0) &&
11874       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11875     unsigned lg2 = SplatValue.countTrailingZeros();
11876     // Splat the sign bit.
11877     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11878     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11879     // Add (N0 < 0) ? abs2 - 1 : 0;
11880     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11881     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11882     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11883     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11884     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11885
11886     // If we're dividing by a positive value, we're done.  Otherwise, we must
11887     // negate the result.
11888     if (SplatValue.isNonNegative())
11889       return SRA;
11890
11891     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11892     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11893     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11894   }
11895   return SDValue();
11896 }
11897
11898 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11899                                          const X86Subtarget *Subtarget) {
11900   EVT VT = Op.getValueType();
11901   SDLoc dl(Op);
11902   SDValue R = Op.getOperand(0);
11903   SDValue Amt = Op.getOperand(1);
11904
11905   // Optimize shl/srl/sra with constant shift amount.
11906   if (isSplatVector(Amt.getNode())) {
11907     SDValue SclrAmt = Amt->getOperand(0);
11908     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11909       uint64_t ShiftAmt = C->getZExtValue();
11910
11911       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11912           (Subtarget->hasInt256() &&
11913            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11914         if (Op.getOpcode() == ISD::SHL)
11915           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11916                              DAG.getConstant(ShiftAmt, MVT::i32));
11917         if (Op.getOpcode() == ISD::SRL)
11918           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11919                              DAG.getConstant(ShiftAmt, MVT::i32));
11920         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11921           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11922                              DAG.getConstant(ShiftAmt, MVT::i32));
11923       }
11924
11925       if (VT == MVT::v16i8) {
11926         if (Op.getOpcode() == ISD::SHL) {
11927           // Make a large shift.
11928           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11929                                     DAG.getConstant(ShiftAmt, MVT::i32));
11930           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11931           // Zero out the rightmost bits.
11932           SmallVector<SDValue, 16> V(16,
11933                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11934                                                      MVT::i8));
11935           return DAG.getNode(ISD::AND, dl, VT, SHL,
11936                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11937         }
11938         if (Op.getOpcode() == ISD::SRL) {
11939           // Make a large shift.
11940           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11941                                     DAG.getConstant(ShiftAmt, MVT::i32));
11942           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11943           // Zero out the leftmost bits.
11944           SmallVector<SDValue, 16> V(16,
11945                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11946                                                      MVT::i8));
11947           return DAG.getNode(ISD::AND, dl, VT, SRL,
11948                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11949         }
11950         if (Op.getOpcode() == ISD::SRA) {
11951           if (ShiftAmt == 7) {
11952             // R s>> 7  ===  R s< 0
11953             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11954             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11955           }
11956
11957           // R s>> a === ((R u>> a) ^ m) - m
11958           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11959           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11960                                                          MVT::i8));
11961           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11962           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11963           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11964           return Res;
11965         }
11966         llvm_unreachable("Unknown shift opcode.");
11967       }
11968
11969       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11970         if (Op.getOpcode() == ISD::SHL) {
11971           // Make a large shift.
11972           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11973                                     DAG.getConstant(ShiftAmt, MVT::i32));
11974           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11975           // Zero out the rightmost bits.
11976           SmallVector<SDValue, 32> V(32,
11977                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11978                                                      MVT::i8));
11979           return DAG.getNode(ISD::AND, dl, VT, SHL,
11980                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11981         }
11982         if (Op.getOpcode() == ISD::SRL) {
11983           // Make a large shift.
11984           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11985                                     DAG.getConstant(ShiftAmt, MVT::i32));
11986           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11987           // Zero out the leftmost bits.
11988           SmallVector<SDValue, 32> V(32,
11989                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11990                                                      MVT::i8));
11991           return DAG.getNode(ISD::AND, dl, VT, SRL,
11992                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11993         }
11994         if (Op.getOpcode() == ISD::SRA) {
11995           if (ShiftAmt == 7) {
11996             // R s>> 7  ===  R s< 0
11997             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11998             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11999           }
12000
12001           // R s>> a === ((R u>> a) ^ m) - m
12002           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12003           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12004                                                          MVT::i8));
12005           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12006           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12007           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12008           return Res;
12009         }
12010         llvm_unreachable("Unknown shift opcode.");
12011       }
12012     }
12013   }
12014
12015   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12016   if (!Subtarget->is64Bit() &&
12017       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12018       Amt.getOpcode() == ISD::BITCAST &&
12019       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12020     Amt = Amt.getOperand(0);
12021     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12022                      VT.getVectorNumElements();
12023     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12024     uint64_t ShiftAmt = 0;
12025     for (unsigned i = 0; i != Ratio; ++i) {
12026       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12027       if (C == 0)
12028         return SDValue();
12029       // 6 == Log2(64)
12030       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12031     }
12032     // Check remaining shift amounts.
12033     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12034       uint64_t ShAmt = 0;
12035       for (unsigned j = 0; j != Ratio; ++j) {
12036         ConstantSDNode *C =
12037           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12038         if (C == 0)
12039           return SDValue();
12040         // 6 == Log2(64)
12041         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12042       }
12043       if (ShAmt != ShiftAmt)
12044         return SDValue();
12045     }
12046     switch (Op.getOpcode()) {
12047     default:
12048       llvm_unreachable("Unknown shift opcode!");
12049     case ISD::SHL:
12050       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12051                          DAG.getConstant(ShiftAmt, MVT::i32));
12052     case ISD::SRL:
12053       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12054                          DAG.getConstant(ShiftAmt, MVT::i32));
12055     case ISD::SRA:
12056       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12057                          DAG.getConstant(ShiftAmt, MVT::i32));
12058     }
12059   }
12060
12061   return SDValue();
12062 }
12063
12064 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12065                                         const X86Subtarget* Subtarget) {
12066   EVT VT = Op.getValueType();
12067   SDLoc dl(Op);
12068   SDValue R = Op.getOperand(0);
12069   SDValue Amt = Op.getOperand(1);
12070
12071   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12072       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12073       (Subtarget->hasInt256() &&
12074        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12075         VT == MVT::v8i32 || VT == MVT::v16i16))) {
12076     SDValue BaseShAmt;
12077     EVT EltVT = VT.getVectorElementType();
12078
12079     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12080       unsigned NumElts = VT.getVectorNumElements();
12081       unsigned i, j;
12082       for (i = 0; i != NumElts; ++i) {
12083         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12084           continue;
12085         break;
12086       }
12087       for (j = i; j != NumElts; ++j) {
12088         SDValue Arg = Amt.getOperand(j);
12089         if (Arg.getOpcode() == ISD::UNDEF) continue;
12090         if (Arg != Amt.getOperand(i))
12091           break;
12092       }
12093       if (i != NumElts && j == NumElts)
12094         BaseShAmt = Amt.getOperand(i);
12095     } else {
12096       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12097         Amt = Amt.getOperand(0);
12098       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12099                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12100         SDValue InVec = Amt.getOperand(0);
12101         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12102           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12103           unsigned i = 0;
12104           for (; i != NumElts; ++i) {
12105             SDValue Arg = InVec.getOperand(i);
12106             if (Arg.getOpcode() == ISD::UNDEF) continue;
12107             BaseShAmt = Arg;
12108             break;
12109           }
12110         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12111            if (ConstantSDNode *C =
12112                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12113              unsigned SplatIdx =
12114                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12115              if (C->getZExtValue() == SplatIdx)
12116                BaseShAmt = InVec.getOperand(1);
12117            }
12118         }
12119         if (BaseShAmt.getNode() == 0)
12120           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12121                                   DAG.getIntPtrConstant(0));
12122       }
12123     }
12124
12125     if (BaseShAmt.getNode()) {
12126       if (EltVT.bitsGT(MVT::i32))
12127         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12128       else if (EltVT.bitsLT(MVT::i32))
12129         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12130
12131       switch (Op.getOpcode()) {
12132       default:
12133         llvm_unreachable("Unknown shift opcode!");
12134       case ISD::SHL:
12135         switch (VT.getSimpleVT().SimpleTy) {
12136         default: return SDValue();
12137         case MVT::v2i64:
12138         case MVT::v4i32:
12139         case MVT::v8i16:
12140         case MVT::v4i64:
12141         case MVT::v8i32:
12142         case MVT::v16i16:
12143           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12144         }
12145       case ISD::SRA:
12146         switch (VT.getSimpleVT().SimpleTy) {
12147         default: return SDValue();
12148         case MVT::v4i32:
12149         case MVT::v8i16:
12150         case MVT::v8i32:
12151         case MVT::v16i16:
12152           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12153         }
12154       case ISD::SRL:
12155         switch (VT.getSimpleVT().SimpleTy) {
12156         default: return SDValue();
12157         case MVT::v2i64:
12158         case MVT::v4i32:
12159         case MVT::v8i16:
12160         case MVT::v4i64:
12161         case MVT::v8i32:
12162         case MVT::v16i16:
12163           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12164         }
12165       }
12166     }
12167   }
12168
12169   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12170   if (!Subtarget->is64Bit() &&
12171       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12172       Amt.getOpcode() == ISD::BITCAST &&
12173       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12174     Amt = Amt.getOperand(0);
12175     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12176                      VT.getVectorNumElements();
12177     std::vector<SDValue> Vals(Ratio);
12178     for (unsigned i = 0; i != Ratio; ++i)
12179       Vals[i] = Amt.getOperand(i);
12180     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12181       for (unsigned j = 0; j != Ratio; ++j)
12182         if (Vals[j] != Amt.getOperand(i + j))
12183           return SDValue();
12184     }
12185     switch (Op.getOpcode()) {
12186     default:
12187       llvm_unreachable("Unknown shift opcode!");
12188     case ISD::SHL:
12189       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12190     case ISD::SRL:
12191       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12192     case ISD::SRA:
12193       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12194     }
12195   }
12196
12197   return SDValue();
12198 }
12199
12200 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
12201
12202   EVT VT = Op.getValueType();
12203   SDLoc dl(Op);
12204   SDValue R = Op.getOperand(0);
12205   SDValue Amt = Op.getOperand(1);
12206   SDValue V;
12207
12208   if (!Subtarget->hasSSE2())
12209     return SDValue();
12210
12211   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12212   if (V.getNode())
12213     return V;
12214
12215   V = LowerScalarVariableShift(Op, DAG, Subtarget);
12216   if (V.getNode())
12217       return V;
12218
12219   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12220   if (Subtarget->hasInt256()) {
12221     if (Op.getOpcode() == ISD::SRL &&
12222         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12223          VT == MVT::v4i64 || VT == MVT::v8i32))
12224       return Op;
12225     if (Op.getOpcode() == ISD::SHL &&
12226         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12227          VT == MVT::v4i64 || VT == MVT::v8i32))
12228       return Op;
12229     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12230       return Op;
12231   }
12232
12233   // Lower SHL with variable shift amount.
12234   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12235     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12236
12237     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12238     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12239     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12240     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12241   }
12242   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12243     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12244
12245     // a = a << 5;
12246     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12247     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12248
12249     // Turn 'a' into a mask suitable for VSELECT
12250     SDValue VSelM = DAG.getConstant(0x80, VT);
12251     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12252     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12253
12254     SDValue CM1 = DAG.getConstant(0x0f, VT);
12255     SDValue CM2 = DAG.getConstant(0x3f, VT);
12256
12257     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12258     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12259     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12260                             DAG.getConstant(4, MVT::i32), DAG);
12261     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12262     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12263
12264     // a += a
12265     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12266     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12267     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12268
12269     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12270     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12271     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12272                             DAG.getConstant(2, MVT::i32), DAG);
12273     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12274     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12275
12276     // a += a
12277     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12278     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12279     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12280
12281     // return VSELECT(r, r+r, a);
12282     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
12283                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
12284     return R;
12285   }
12286
12287   // Decompose 256-bit shifts into smaller 128-bit shifts.
12288   if (VT.is256BitVector()) {
12289     unsigned NumElems = VT.getVectorNumElements();
12290     MVT EltVT = VT.getVectorElementType().getSimpleVT();
12291     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12292
12293     // Extract the two vectors
12294     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
12295     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
12296
12297     // Recreate the shift amount vectors
12298     SDValue Amt1, Amt2;
12299     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12300       // Constant shift amount
12301       SmallVector<SDValue, 4> Amt1Csts;
12302       SmallVector<SDValue, 4> Amt2Csts;
12303       for (unsigned i = 0; i != NumElems/2; ++i)
12304         Amt1Csts.push_back(Amt->getOperand(i));
12305       for (unsigned i = NumElems/2; i != NumElems; ++i)
12306         Amt2Csts.push_back(Amt->getOperand(i));
12307
12308       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12309                                  &Amt1Csts[0], NumElems/2);
12310       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12311                                  &Amt2Csts[0], NumElems/2);
12312     } else {
12313       // Variable shift amount
12314       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12315       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12316     }
12317
12318     // Issue new vector shifts for the smaller types
12319     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12320     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12321
12322     // Concatenate the result back
12323     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12324   }
12325
12326   return SDValue();
12327 }
12328
12329 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12330   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12331   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12332   // looks for this combo and may remove the "setcc" instruction if the "setcc"
12333   // has only one use.
12334   SDNode *N = Op.getNode();
12335   SDValue LHS = N->getOperand(0);
12336   SDValue RHS = N->getOperand(1);
12337   unsigned BaseOp = 0;
12338   unsigned Cond = 0;
12339   SDLoc DL(Op);
12340   switch (Op.getOpcode()) {
12341   default: llvm_unreachable("Unknown ovf instruction!");
12342   case ISD::SADDO:
12343     // A subtract of one will be selected as a INC. Note that INC doesn't
12344     // set CF, so we can't do this for UADDO.
12345     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12346       if (C->isOne()) {
12347         BaseOp = X86ISD::INC;
12348         Cond = X86::COND_O;
12349         break;
12350       }
12351     BaseOp = X86ISD::ADD;
12352     Cond = X86::COND_O;
12353     break;
12354   case ISD::UADDO:
12355     BaseOp = X86ISD::ADD;
12356     Cond = X86::COND_B;
12357     break;
12358   case ISD::SSUBO:
12359     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12360     // set CF, so we can't do this for USUBO.
12361     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12362       if (C->isOne()) {
12363         BaseOp = X86ISD::DEC;
12364         Cond = X86::COND_O;
12365         break;
12366       }
12367     BaseOp = X86ISD::SUB;
12368     Cond = X86::COND_O;
12369     break;
12370   case ISD::USUBO:
12371     BaseOp = X86ISD::SUB;
12372     Cond = X86::COND_B;
12373     break;
12374   case ISD::SMULO:
12375     BaseOp = X86ISD::SMUL;
12376     Cond = X86::COND_O;
12377     break;
12378   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12379     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12380                                  MVT::i32);
12381     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12382
12383     SDValue SetCC =
12384       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12385                   DAG.getConstant(X86::COND_O, MVT::i32),
12386                   SDValue(Sum.getNode(), 2));
12387
12388     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12389   }
12390   }
12391
12392   // Also sets EFLAGS.
12393   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12394   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12395
12396   SDValue SetCC =
12397     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12398                 DAG.getConstant(Cond, MVT::i32),
12399                 SDValue(Sum.getNode(), 1));
12400
12401   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12402 }
12403
12404 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12405                                                   SelectionDAG &DAG) const {
12406   SDLoc dl(Op);
12407   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12408   EVT VT = Op.getValueType();
12409
12410   if (!Subtarget->hasSSE2() || !VT.isVector())
12411     return SDValue();
12412
12413   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12414                       ExtraVT.getScalarType().getSizeInBits();
12415   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12416
12417   switch (VT.getSimpleVT().SimpleTy) {
12418     default: return SDValue();
12419     case MVT::v8i32:
12420     case MVT::v16i16:
12421       if (!Subtarget->hasFp256())
12422         return SDValue();
12423       if (!Subtarget->hasInt256()) {
12424         // needs to be split
12425         unsigned NumElems = VT.getVectorNumElements();
12426
12427         // Extract the LHS vectors
12428         SDValue LHS = Op.getOperand(0);
12429         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12430         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12431
12432         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12433         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12434
12435         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12436         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12437         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12438                                    ExtraNumElems/2);
12439         SDValue Extra = DAG.getValueType(ExtraVT);
12440
12441         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12442         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12443
12444         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12445       }
12446       // fall through
12447     case MVT::v4i32:
12448     case MVT::v8i16: {
12449       // (sext (vzext x)) -> (vsext x)
12450       SDValue Op0 = Op.getOperand(0);
12451       SDValue Op00 = Op0.getOperand(0);
12452       SDValue Tmp1;
12453       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12454       if (Op0.getOpcode() == ISD::BITCAST &&
12455           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12456         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12457       if (Tmp1.getNode()) {
12458         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12459         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12460                "This optimization is invalid without a VZEXT.");
12461         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12462       }
12463
12464       // If the above didn't work, then just use Shift-Left + Shift-Right.
12465       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12466       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12467     }
12468   }
12469 }
12470
12471 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12472                                  SelectionDAG &DAG) {
12473   SDLoc dl(Op);
12474   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12475     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12476   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12477     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12478
12479   // The only fence that needs an instruction is a sequentially-consistent
12480   // cross-thread fence.
12481   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12482     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12483     // no-sse2). There isn't any reason to disable it if the target processor
12484     // supports it.
12485     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12486       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12487
12488     SDValue Chain = Op.getOperand(0);
12489     SDValue Zero = DAG.getConstant(0, MVT::i32);
12490     SDValue Ops[] = {
12491       DAG.getRegister(X86::ESP, MVT::i32), // Base
12492       DAG.getTargetConstant(1, MVT::i8),   // Scale
12493       DAG.getRegister(0, MVT::i32),        // Index
12494       DAG.getTargetConstant(0, MVT::i32),  // Disp
12495       DAG.getRegister(0, MVT::i32),        // Segment.
12496       Zero,
12497       Chain
12498     };
12499     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12500     return SDValue(Res, 0);
12501   }
12502
12503   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12504   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12505 }
12506
12507 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12508                              SelectionDAG &DAG) {
12509   EVT T = Op.getValueType();
12510   SDLoc DL(Op);
12511   unsigned Reg = 0;
12512   unsigned size = 0;
12513   switch(T.getSimpleVT().SimpleTy) {
12514   default: llvm_unreachable("Invalid value type!");
12515   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12516   case MVT::i16: Reg = X86::AX;  size = 2; break;
12517   case MVT::i32: Reg = X86::EAX; size = 4; break;
12518   case MVT::i64:
12519     assert(Subtarget->is64Bit() && "Node not type legal!");
12520     Reg = X86::RAX; size = 8;
12521     break;
12522   }
12523   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12524                                     Op.getOperand(2), SDValue());
12525   SDValue Ops[] = { cpIn.getValue(0),
12526                     Op.getOperand(1),
12527                     Op.getOperand(3),
12528                     DAG.getTargetConstant(size, MVT::i8),
12529                     cpIn.getValue(1) };
12530   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12531   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12532   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12533                                            Ops, array_lengthof(Ops), T, MMO);
12534   SDValue cpOut =
12535     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12536   return cpOut;
12537 }
12538
12539 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12540                                      SelectionDAG &DAG) {
12541   assert(Subtarget->is64Bit() && "Result not type legalized?");
12542   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12543   SDValue TheChain = Op.getOperand(0);
12544   SDLoc dl(Op);
12545   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12546   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12547   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12548                                    rax.getValue(2));
12549   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12550                             DAG.getConstant(32, MVT::i8));
12551   SDValue Ops[] = {
12552     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12553     rdx.getValue(1)
12554   };
12555   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12556 }
12557
12558 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12559   EVT SrcVT = Op.getOperand(0).getValueType();
12560   EVT DstVT = Op.getValueType();
12561   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12562          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12563   assert((DstVT == MVT::i64 ||
12564           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12565          "Unexpected custom BITCAST");
12566   // i64 <=> MMX conversions are Legal.
12567   if (SrcVT==MVT::i64 && DstVT.isVector())
12568     return Op;
12569   if (DstVT==MVT::i64 && SrcVT.isVector())
12570     return Op;
12571   // MMX <=> MMX conversions are Legal.
12572   if (SrcVT.isVector() && DstVT.isVector())
12573     return Op;
12574   // All other conversions need to be expanded.
12575   return SDValue();
12576 }
12577
12578 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12579   SDNode *Node = Op.getNode();
12580   SDLoc dl(Node);
12581   EVT T = Node->getValueType(0);
12582   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12583                               DAG.getConstant(0, T), Node->getOperand(2));
12584   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12585                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12586                        Node->getOperand(0),
12587                        Node->getOperand(1), negOp,
12588                        cast<AtomicSDNode>(Node)->getSrcValue(),
12589                        cast<AtomicSDNode>(Node)->getAlignment(),
12590                        cast<AtomicSDNode>(Node)->getOrdering(),
12591                        cast<AtomicSDNode>(Node)->getSynchScope());
12592 }
12593
12594 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12595   SDNode *Node = Op.getNode();
12596   SDLoc dl(Node);
12597   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12598
12599   // Convert seq_cst store -> xchg
12600   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12601   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12602   //        (The only way to get a 16-byte store is cmpxchg16b)
12603   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12604   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12605       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12606     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12607                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12608                                  Node->getOperand(0),
12609                                  Node->getOperand(1), Node->getOperand(2),
12610                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12611                                  cast<AtomicSDNode>(Node)->getOrdering(),
12612                                  cast<AtomicSDNode>(Node)->getSynchScope());
12613     return Swap.getValue(1);
12614   }
12615   // Other atomic stores have a simple pattern.
12616   return Op;
12617 }
12618
12619 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12620   EVT VT = Op.getNode()->getValueType(0);
12621
12622   // Let legalize expand this if it isn't a legal type yet.
12623   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12624     return SDValue();
12625
12626   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12627
12628   unsigned Opc;
12629   bool ExtraOp = false;
12630   switch (Op.getOpcode()) {
12631   default: llvm_unreachable("Invalid code");
12632   case ISD::ADDC: Opc = X86ISD::ADD; break;
12633   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12634   case ISD::SUBC: Opc = X86ISD::SUB; break;
12635   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12636   }
12637
12638   if (!ExtraOp)
12639     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12640                        Op.getOperand(1));
12641   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12642                      Op.getOperand(1), Op.getOperand(2));
12643 }
12644
12645 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12646   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12647
12648   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12649   // which returns the values as { float, float } (in XMM0) or
12650   // { double, double } (which is returned in XMM0, XMM1).
12651   SDLoc dl(Op);
12652   SDValue Arg = Op.getOperand(0);
12653   EVT ArgVT = Arg.getValueType();
12654   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12655
12656   ArgListTy Args;
12657   ArgListEntry Entry;
12658
12659   Entry.Node = Arg;
12660   Entry.Ty = ArgTy;
12661   Entry.isSExt = false;
12662   Entry.isZExt = false;
12663   Args.push_back(Entry);
12664
12665   bool isF64 = ArgVT == MVT::f64;
12666   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12667   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12668   // the results are returned via SRet in memory.
12669   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12670   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12671
12672   Type *RetTy = isF64
12673     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12674     : (Type*)VectorType::get(ArgTy, 4);
12675   TargetLowering::
12676     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12677                          false, false, false, false, 0,
12678                          CallingConv::C, /*isTaillCall=*/false,
12679                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12680                          Callee, Args, DAG, dl);
12681   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12682
12683   if (isF64)
12684     // Returned in xmm0 and xmm1.
12685     return CallResult.first;
12686
12687   // Returned in bits 0:31 and 32:64 xmm0.
12688   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12689                                CallResult.first, DAG.getIntPtrConstant(0));
12690   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12691                                CallResult.first, DAG.getIntPtrConstant(1));
12692   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12693   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12694 }
12695
12696 /// LowerOperation - Provide custom lowering hooks for some operations.
12697 ///
12698 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12699   switch (Op.getOpcode()) {
12700   default: llvm_unreachable("Should not custom lower this!");
12701   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12702   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12703   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12704   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12705   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12706   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12707   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12708   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12709   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12710   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12711   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12712   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12713   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12714   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12715   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12716   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12717   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12718   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12719   case ISD::SHL_PARTS:
12720   case ISD::SRA_PARTS:
12721   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12722   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12723   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12724   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12725   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12726   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12727   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12728   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12729   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12730   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12731   case ISD::FABS:               return LowerFABS(Op, DAG);
12732   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12733   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12734   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12735   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12736   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12737   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12738   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12739   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12740   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12741   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12742   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12743   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12744   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12745   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12746   case ISD::FRAME_TO_ARGS_OFFSET:
12747                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12748   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12749   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12750   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12751   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12752   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12753   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12754   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12755   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12756   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12757   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12758   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12759   case ISD::SRA:
12760   case ISD::SRL:
12761   case ISD::SHL:                return LowerShift(Op, DAG);
12762   case ISD::SADDO:
12763   case ISD::UADDO:
12764   case ISD::SSUBO:
12765   case ISD::USUBO:
12766   case ISD::SMULO:
12767   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12768   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12769   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12770   case ISD::ADDC:
12771   case ISD::ADDE:
12772   case ISD::SUBC:
12773   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12774   case ISD::ADD:                return LowerADD(Op, DAG);
12775   case ISD::SUB:                return LowerSUB(Op, DAG);
12776   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12777   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12778   }
12779 }
12780
12781 static void ReplaceATOMIC_LOAD(SDNode *Node,
12782                                   SmallVectorImpl<SDValue> &Results,
12783                                   SelectionDAG &DAG) {
12784   SDLoc dl(Node);
12785   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12786
12787   // Convert wide load -> cmpxchg8b/cmpxchg16b
12788   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12789   //        (The only way to get a 16-byte load is cmpxchg16b)
12790   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12791   SDValue Zero = DAG.getConstant(0, VT);
12792   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12793                                Node->getOperand(0),
12794                                Node->getOperand(1), Zero, Zero,
12795                                cast<AtomicSDNode>(Node)->getMemOperand(),
12796                                cast<AtomicSDNode>(Node)->getOrdering(),
12797                                cast<AtomicSDNode>(Node)->getSynchScope());
12798   Results.push_back(Swap.getValue(0));
12799   Results.push_back(Swap.getValue(1));
12800 }
12801
12802 static void
12803 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12804                         SelectionDAG &DAG, unsigned NewOp) {
12805   SDLoc dl(Node);
12806   assert (Node->getValueType(0) == MVT::i64 &&
12807           "Only know how to expand i64 atomics");
12808
12809   SDValue Chain = Node->getOperand(0);
12810   SDValue In1 = Node->getOperand(1);
12811   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12812                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12813   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12814                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12815   SDValue Ops[] = { Chain, In1, In2L, In2H };
12816   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12817   SDValue Result =
12818     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12819                             cast<MemSDNode>(Node)->getMemOperand());
12820   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12821   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12822   Results.push_back(Result.getValue(2));
12823 }
12824
12825 /// ReplaceNodeResults - Replace a node with an illegal result type
12826 /// with a new node built out of custom code.
12827 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12828                                            SmallVectorImpl<SDValue>&Results,
12829                                            SelectionDAG &DAG) const {
12830   SDLoc dl(N);
12831   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12832   switch (N->getOpcode()) {
12833   default:
12834     llvm_unreachable("Do not know how to custom type legalize this operation!");
12835   case ISD::SIGN_EXTEND_INREG:
12836   case ISD::ADDC:
12837   case ISD::ADDE:
12838   case ISD::SUBC:
12839   case ISD::SUBE:
12840     // We don't want to expand or promote these.
12841     return;
12842   case ISD::FP_TO_SINT:
12843   case ISD::FP_TO_UINT: {
12844     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12845
12846     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12847       return;
12848
12849     std::pair<SDValue,SDValue> Vals =
12850         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12851     SDValue FIST = Vals.first, StackSlot = Vals.second;
12852     if (FIST.getNode() != 0) {
12853       EVT VT = N->getValueType(0);
12854       // Return a load from the stack slot.
12855       if (StackSlot.getNode() != 0)
12856         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12857                                       MachinePointerInfo(),
12858                                       false, false, false, 0));
12859       else
12860         Results.push_back(FIST);
12861     }
12862     return;
12863   }
12864   case ISD::UINT_TO_FP: {
12865     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12866     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12867         N->getValueType(0) != MVT::v2f32)
12868       return;
12869     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12870                                  N->getOperand(0));
12871     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12872                                      MVT::f64);
12873     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12874     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12875                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12876     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12877     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12878     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12879     return;
12880   }
12881   case ISD::FP_ROUND: {
12882     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12883         return;
12884     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12885     Results.push_back(V);
12886     return;
12887   }
12888   case ISD::READCYCLECOUNTER: {
12889     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12890     SDValue TheChain = N->getOperand(0);
12891     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12892     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12893                                      rd.getValue(1));
12894     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12895                                      eax.getValue(2));
12896     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12897     SDValue Ops[] = { eax, edx };
12898     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12899                                   array_lengthof(Ops)));
12900     Results.push_back(edx.getValue(1));
12901     return;
12902   }
12903   case ISD::ATOMIC_CMP_SWAP: {
12904     EVT T = N->getValueType(0);
12905     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12906     bool Regs64bit = T == MVT::i128;
12907     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12908     SDValue cpInL, cpInH;
12909     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12910                         DAG.getConstant(0, HalfT));
12911     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12912                         DAG.getConstant(1, HalfT));
12913     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12914                              Regs64bit ? X86::RAX : X86::EAX,
12915                              cpInL, SDValue());
12916     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12917                              Regs64bit ? X86::RDX : X86::EDX,
12918                              cpInH, cpInL.getValue(1));
12919     SDValue swapInL, swapInH;
12920     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12921                           DAG.getConstant(0, HalfT));
12922     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12923                           DAG.getConstant(1, HalfT));
12924     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12925                                Regs64bit ? X86::RBX : X86::EBX,
12926                                swapInL, cpInH.getValue(1));
12927     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12928                                Regs64bit ? X86::RCX : X86::ECX,
12929                                swapInH, swapInL.getValue(1));
12930     SDValue Ops[] = { swapInH.getValue(0),
12931                       N->getOperand(1),
12932                       swapInH.getValue(1) };
12933     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12934     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12935     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12936                                   X86ISD::LCMPXCHG8_DAG;
12937     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12938                                              Ops, array_lengthof(Ops), T, MMO);
12939     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12940                                         Regs64bit ? X86::RAX : X86::EAX,
12941                                         HalfT, Result.getValue(1));
12942     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12943                                         Regs64bit ? X86::RDX : X86::EDX,
12944                                         HalfT, cpOutL.getValue(2));
12945     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12946     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12947     Results.push_back(cpOutH.getValue(1));
12948     return;
12949   }
12950   case ISD::ATOMIC_LOAD_ADD:
12951   case ISD::ATOMIC_LOAD_AND:
12952   case ISD::ATOMIC_LOAD_NAND:
12953   case ISD::ATOMIC_LOAD_OR:
12954   case ISD::ATOMIC_LOAD_SUB:
12955   case ISD::ATOMIC_LOAD_XOR:
12956   case ISD::ATOMIC_LOAD_MAX:
12957   case ISD::ATOMIC_LOAD_MIN:
12958   case ISD::ATOMIC_LOAD_UMAX:
12959   case ISD::ATOMIC_LOAD_UMIN:
12960   case ISD::ATOMIC_SWAP: {
12961     unsigned Opc;
12962     switch (N->getOpcode()) {
12963     default: llvm_unreachable("Unexpected opcode");
12964     case ISD::ATOMIC_LOAD_ADD:
12965       Opc = X86ISD::ATOMADD64_DAG;
12966       break;
12967     case ISD::ATOMIC_LOAD_AND:
12968       Opc = X86ISD::ATOMAND64_DAG;
12969       break;
12970     case ISD::ATOMIC_LOAD_NAND:
12971       Opc = X86ISD::ATOMNAND64_DAG;
12972       break;
12973     case ISD::ATOMIC_LOAD_OR:
12974       Opc = X86ISD::ATOMOR64_DAG;
12975       break;
12976     case ISD::ATOMIC_LOAD_SUB:
12977       Opc = X86ISD::ATOMSUB64_DAG;
12978       break;
12979     case ISD::ATOMIC_LOAD_XOR:
12980       Opc = X86ISD::ATOMXOR64_DAG;
12981       break;
12982     case ISD::ATOMIC_LOAD_MAX:
12983       Opc = X86ISD::ATOMMAX64_DAG;
12984       break;
12985     case ISD::ATOMIC_LOAD_MIN:
12986       Opc = X86ISD::ATOMMIN64_DAG;
12987       break;
12988     case ISD::ATOMIC_LOAD_UMAX:
12989       Opc = X86ISD::ATOMUMAX64_DAG;
12990       break;
12991     case ISD::ATOMIC_LOAD_UMIN:
12992       Opc = X86ISD::ATOMUMIN64_DAG;
12993       break;
12994     case ISD::ATOMIC_SWAP:
12995       Opc = X86ISD::ATOMSWAP64_DAG;
12996       break;
12997     }
12998     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12999     return;
13000   }
13001   case ISD::ATOMIC_LOAD:
13002     ReplaceATOMIC_LOAD(N, Results, DAG);
13003   }
13004 }
13005
13006 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13007   switch (Opcode) {
13008   default: return NULL;
13009   case X86ISD::BSF:                return "X86ISD::BSF";
13010   case X86ISD::BSR:                return "X86ISD::BSR";
13011   case X86ISD::SHLD:               return "X86ISD::SHLD";
13012   case X86ISD::SHRD:               return "X86ISD::SHRD";
13013   case X86ISD::FAND:               return "X86ISD::FAND";
13014   case X86ISD::FANDN:              return "X86ISD::FANDN";
13015   case X86ISD::FOR:                return "X86ISD::FOR";
13016   case X86ISD::FXOR:               return "X86ISD::FXOR";
13017   case X86ISD::FSRL:               return "X86ISD::FSRL";
13018   case X86ISD::FILD:               return "X86ISD::FILD";
13019   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13020   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13021   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13022   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13023   case X86ISD::FLD:                return "X86ISD::FLD";
13024   case X86ISD::FST:                return "X86ISD::FST";
13025   case X86ISD::CALL:               return "X86ISD::CALL";
13026   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13027   case X86ISD::BT:                 return "X86ISD::BT";
13028   case X86ISD::CMP:                return "X86ISD::CMP";
13029   case X86ISD::COMI:               return "X86ISD::COMI";
13030   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13031   case X86ISD::SETCC:              return "X86ISD::SETCC";
13032   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13033   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
13034   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
13035   case X86ISD::CMOV:               return "X86ISD::CMOV";
13036   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13037   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13038   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13039   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13040   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13041   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13042   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13043   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13044   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13045   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13046   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13047   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13048   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13049   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13050   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13051   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13052   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13053   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13054   case X86ISD::HADD:               return "X86ISD::HADD";
13055   case X86ISD::HSUB:               return "X86ISD::HSUB";
13056   case X86ISD::FHADD:              return "X86ISD::FHADD";
13057   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13058   case X86ISD::UMAX:               return "X86ISD::UMAX";
13059   case X86ISD::UMIN:               return "X86ISD::UMIN";
13060   case X86ISD::SMAX:               return "X86ISD::SMAX";
13061   case X86ISD::SMIN:               return "X86ISD::SMIN";
13062   case X86ISD::FMAX:               return "X86ISD::FMAX";
13063   case X86ISD::FMIN:               return "X86ISD::FMIN";
13064   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13065   case X86ISD::FMINC:              return "X86ISD::FMINC";
13066   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13067   case X86ISD::FRCP:               return "X86ISD::FRCP";
13068   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13069   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13070   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13071   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13072   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13073   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13074   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13075   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13076   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13077   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13078   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13079   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13080   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13081   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13082   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13083   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13084   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13085   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13086   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13087   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13088   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13089   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13090   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13091   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13092   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13093   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13094   case X86ISD::VSHL:               return "X86ISD::VSHL";
13095   case X86ISD::VSRL:               return "X86ISD::VSRL";
13096   case X86ISD::VSRA:               return "X86ISD::VSRA";
13097   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13098   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13099   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13100   case X86ISD::CMPP:               return "X86ISD::CMPP";
13101   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13102   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13103   case X86ISD::ADD:                return "X86ISD::ADD";
13104   case X86ISD::SUB:                return "X86ISD::SUB";
13105   case X86ISD::ADC:                return "X86ISD::ADC";
13106   case X86ISD::SBB:                return "X86ISD::SBB";
13107   case X86ISD::SMUL:               return "X86ISD::SMUL";
13108   case X86ISD::UMUL:               return "X86ISD::UMUL";
13109   case X86ISD::INC:                return "X86ISD::INC";
13110   case X86ISD::DEC:                return "X86ISD::DEC";
13111   case X86ISD::OR:                 return "X86ISD::OR";
13112   case X86ISD::XOR:                return "X86ISD::XOR";
13113   case X86ISD::AND:                return "X86ISD::AND";
13114   case X86ISD::BLSI:               return "X86ISD::BLSI";
13115   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13116   case X86ISD::BLSR:               return "X86ISD::BLSR";
13117   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13118   case X86ISD::PTEST:              return "X86ISD::PTEST";
13119   case X86ISD::TESTP:              return "X86ISD::TESTP";
13120   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13121   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13122   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13123   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13124   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
13125   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
13126   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
13127   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
13128   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
13129   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
13130   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
13131   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
13132   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
13133   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
13134   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
13135   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
13136   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
13137   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
13138   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
13139   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
13140   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
13141   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
13142   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
13143   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13144   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
13145   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
13146   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
13147   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
13148   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
13149   case X86ISD::SAHF:               return "X86ISD::SAHF";
13150   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
13151   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
13152   case X86ISD::FMADD:              return "X86ISD::FMADD";
13153   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
13154   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
13155   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
13156   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
13157   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
13158   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
13159   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
13160   case X86ISD::XTEST:              return "X86ISD::XTEST";
13161   }
13162 }
13163
13164 // isLegalAddressingMode - Return true if the addressing mode represented
13165 // by AM is legal for this target, for a load/store of the specified type.
13166 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13167                                               Type *Ty) const {
13168   // X86 supports extremely general addressing modes.
13169   CodeModel::Model M = getTargetMachine().getCodeModel();
13170   Reloc::Model R = getTargetMachine().getRelocationModel();
13171
13172   // X86 allows a sign-extended 32-bit immediate field as a displacement.
13173   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13174     return false;
13175
13176   if (AM.BaseGV) {
13177     unsigned GVFlags =
13178       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13179
13180     // If a reference to this global requires an extra load, we can't fold it.
13181     if (isGlobalStubReference(GVFlags))
13182       return false;
13183
13184     // If BaseGV requires a register for the PIC base, we cannot also have a
13185     // BaseReg specified.
13186     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13187       return false;
13188
13189     // If lower 4G is not available, then we must use rip-relative addressing.
13190     if ((M != CodeModel::Small || R != Reloc::Static) &&
13191         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13192       return false;
13193   }
13194
13195   switch (AM.Scale) {
13196   case 0:
13197   case 1:
13198   case 2:
13199   case 4:
13200   case 8:
13201     // These scales always work.
13202     break;
13203   case 3:
13204   case 5:
13205   case 9:
13206     // These scales are formed with basereg+scalereg.  Only accept if there is
13207     // no basereg yet.
13208     if (AM.HasBaseReg)
13209       return false;
13210     break;
13211   default:  // Other stuff never works.
13212     return false;
13213   }
13214
13215   return true;
13216 }
13217
13218 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13219   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13220     return false;
13221   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13222   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13223   return NumBits1 > NumBits2;
13224 }
13225
13226 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13227   return isInt<32>(Imm);
13228 }
13229
13230 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13231   // Can also use sub to handle negated immediates.
13232   return isInt<32>(Imm);
13233 }
13234
13235 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13236   if (!VT1.isInteger() || !VT2.isInteger())
13237     return false;
13238   unsigned NumBits1 = VT1.getSizeInBits();
13239   unsigned NumBits2 = VT2.getSizeInBits();
13240   return NumBits1 > NumBits2;
13241 }
13242
13243 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13244   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13245   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
13246 }
13247
13248 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
13249   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13250   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
13251 }
13252
13253 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13254   EVT VT1 = Val.getValueType();
13255   if (isZExtFree(VT1, VT2))
13256     return true;
13257
13258   if (Val.getOpcode() != ISD::LOAD)
13259     return false;
13260
13261   if (!VT1.isSimple() || !VT1.isInteger() ||
13262       !VT2.isSimple() || !VT2.isInteger())
13263     return false;
13264
13265   switch (VT1.getSimpleVT().SimpleTy) {
13266   default: break;
13267   case MVT::i8:
13268   case MVT::i16:
13269   case MVT::i32:
13270     // X86 has 8, 16, and 32-bit zero-extending loads.
13271     return true;
13272   }
13273
13274   return false;
13275 }
13276
13277 bool
13278 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13279   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
13280     return false;
13281
13282   VT = VT.getScalarType();
13283
13284   if (!VT.isSimple())
13285     return false;
13286
13287   switch (VT.getSimpleVT().SimpleTy) {
13288   case MVT::f32:
13289   case MVT::f64:
13290     return true;
13291   default:
13292     break;
13293   }
13294
13295   return false;
13296 }
13297
13298 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
13299   // i16 instructions are longer (0x66 prefix) and potentially slower.
13300   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
13301 }
13302
13303 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13304 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13305 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13306 /// are assumed to be legal.
13307 bool
13308 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13309                                       EVT VT) const {
13310   // Very little shuffling can be done for 64-bit vectors right now.
13311   if (VT.getSizeInBits() == 64)
13312     return false;
13313
13314   // FIXME: pshufb, blends, shifts.
13315   return (VT.getVectorNumElements() == 2 ||
13316           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13317           isMOVLMask(M, VT) ||
13318           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
13319           isPSHUFDMask(M, VT) ||
13320           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
13321           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
13322           isPALIGNRMask(M, VT, Subtarget) ||
13323           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
13324           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
13325           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
13326           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13327 }
13328
13329 bool
13330 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13331                                           EVT VT) const {
13332   unsigned NumElts = VT.getVectorNumElements();
13333   // FIXME: This collection of masks seems suspect.
13334   if (NumElts == 2)
13335     return true;
13336   if (NumElts == 4 && VT.is128BitVector()) {
13337     return (isMOVLMask(Mask, VT)  ||
13338             isCommutedMOVLMask(Mask, VT, true) ||
13339             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13340             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13341   }
13342   return false;
13343 }
13344
13345 //===----------------------------------------------------------------------===//
13346 //                           X86 Scheduler Hooks
13347 //===----------------------------------------------------------------------===//
13348
13349 /// Utility function to emit xbegin specifying the start of an RTM region.
13350 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13351                                      const TargetInstrInfo *TII) {
13352   DebugLoc DL = MI->getDebugLoc();
13353
13354   const BasicBlock *BB = MBB->getBasicBlock();
13355   MachineFunction::iterator I = MBB;
13356   ++I;
13357
13358   // For the v = xbegin(), we generate
13359   //
13360   // thisMBB:
13361   //  xbegin sinkMBB
13362   //
13363   // mainMBB:
13364   //  eax = -1
13365   //
13366   // sinkMBB:
13367   //  v = eax
13368
13369   MachineBasicBlock *thisMBB = MBB;
13370   MachineFunction *MF = MBB->getParent();
13371   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13372   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13373   MF->insert(I, mainMBB);
13374   MF->insert(I, sinkMBB);
13375
13376   // Transfer the remainder of BB and its successor edges to sinkMBB.
13377   sinkMBB->splice(sinkMBB->begin(), MBB,
13378                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13379   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13380
13381   // thisMBB:
13382   //  xbegin sinkMBB
13383   //  # fallthrough to mainMBB
13384   //  # abortion to sinkMBB
13385   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13386   thisMBB->addSuccessor(mainMBB);
13387   thisMBB->addSuccessor(sinkMBB);
13388
13389   // mainMBB:
13390   //  EAX = -1
13391   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13392   mainMBB->addSuccessor(sinkMBB);
13393
13394   // sinkMBB:
13395   // EAX is live into the sinkMBB
13396   sinkMBB->addLiveIn(X86::EAX);
13397   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13398           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13399     .addReg(X86::EAX);
13400
13401   MI->eraseFromParent();
13402   return sinkMBB;
13403 }
13404
13405 // Get CMPXCHG opcode for the specified data type.
13406 static unsigned getCmpXChgOpcode(EVT VT) {
13407   switch (VT.getSimpleVT().SimpleTy) {
13408   case MVT::i8:  return X86::LCMPXCHG8;
13409   case MVT::i16: return X86::LCMPXCHG16;
13410   case MVT::i32: return X86::LCMPXCHG32;
13411   case MVT::i64: return X86::LCMPXCHG64;
13412   default:
13413     break;
13414   }
13415   llvm_unreachable("Invalid operand size!");
13416 }
13417
13418 // Get LOAD opcode for the specified data type.
13419 static unsigned getLoadOpcode(EVT VT) {
13420   switch (VT.getSimpleVT().SimpleTy) {
13421   case MVT::i8:  return X86::MOV8rm;
13422   case MVT::i16: return X86::MOV16rm;
13423   case MVT::i32: return X86::MOV32rm;
13424   case MVT::i64: return X86::MOV64rm;
13425   default:
13426     break;
13427   }
13428   llvm_unreachable("Invalid operand size!");
13429 }
13430
13431 // Get opcode of the non-atomic one from the specified atomic instruction.
13432 static unsigned getNonAtomicOpcode(unsigned Opc) {
13433   switch (Opc) {
13434   case X86::ATOMAND8:  return X86::AND8rr;
13435   case X86::ATOMAND16: return X86::AND16rr;
13436   case X86::ATOMAND32: return X86::AND32rr;
13437   case X86::ATOMAND64: return X86::AND64rr;
13438   case X86::ATOMOR8:   return X86::OR8rr;
13439   case X86::ATOMOR16:  return X86::OR16rr;
13440   case X86::ATOMOR32:  return X86::OR32rr;
13441   case X86::ATOMOR64:  return X86::OR64rr;
13442   case X86::ATOMXOR8:  return X86::XOR8rr;
13443   case X86::ATOMXOR16: return X86::XOR16rr;
13444   case X86::ATOMXOR32: return X86::XOR32rr;
13445   case X86::ATOMXOR64: return X86::XOR64rr;
13446   }
13447   llvm_unreachable("Unhandled atomic-load-op opcode!");
13448 }
13449
13450 // Get opcode of the non-atomic one from the specified atomic instruction with
13451 // extra opcode.
13452 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13453                                                unsigned &ExtraOpc) {
13454   switch (Opc) {
13455   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13456   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13457   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13458   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13459   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13460   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13461   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13462   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13463   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13464   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13465   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13466   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13467   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13468   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13469   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13470   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13471   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13472   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13473   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13474   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13475   }
13476   llvm_unreachable("Unhandled atomic-load-op opcode!");
13477 }
13478
13479 // Get opcode of the non-atomic one from the specified atomic instruction for
13480 // 64-bit data type on 32-bit target.
13481 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13482   switch (Opc) {
13483   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13484   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13485   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13486   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13487   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13488   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13489   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13490   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13491   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13492   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13493   }
13494   llvm_unreachable("Unhandled atomic-load-op opcode!");
13495 }
13496
13497 // Get opcode of the non-atomic one from the specified atomic instruction for
13498 // 64-bit data type on 32-bit target with extra opcode.
13499 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13500                                                    unsigned &HiOpc,
13501                                                    unsigned &ExtraOpc) {
13502   switch (Opc) {
13503   case X86::ATOMNAND6432:
13504     ExtraOpc = X86::NOT32r;
13505     HiOpc = X86::AND32rr;
13506     return X86::AND32rr;
13507   }
13508   llvm_unreachable("Unhandled atomic-load-op opcode!");
13509 }
13510
13511 // Get pseudo CMOV opcode from the specified data type.
13512 static unsigned getPseudoCMOVOpc(EVT VT) {
13513   switch (VT.getSimpleVT().SimpleTy) {
13514   case MVT::i8:  return X86::CMOV_GR8;
13515   case MVT::i16: return X86::CMOV_GR16;
13516   case MVT::i32: return X86::CMOV_GR32;
13517   default:
13518     break;
13519   }
13520   llvm_unreachable("Unknown CMOV opcode!");
13521 }
13522
13523 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13524 // They will be translated into a spin-loop or compare-exchange loop from
13525 //
13526 //    ...
13527 //    dst = atomic-fetch-op MI.addr, MI.val
13528 //    ...
13529 //
13530 // to
13531 //
13532 //    ...
13533 //    t1 = LOAD MI.addr
13534 // loop:
13535 //    t4 = phi(t1, t3 / loop)
13536 //    t2 = OP MI.val, t4
13537 //    EAX = t4
13538 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13539 //    t3 = EAX
13540 //    JNE loop
13541 // sink:
13542 //    dst = t3
13543 //    ...
13544 MachineBasicBlock *
13545 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13546                                        MachineBasicBlock *MBB) const {
13547   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13548   DebugLoc DL = MI->getDebugLoc();
13549
13550   MachineFunction *MF = MBB->getParent();
13551   MachineRegisterInfo &MRI = MF->getRegInfo();
13552
13553   const BasicBlock *BB = MBB->getBasicBlock();
13554   MachineFunction::iterator I = MBB;
13555   ++I;
13556
13557   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13558          "Unexpected number of operands");
13559
13560   assert(MI->hasOneMemOperand() &&
13561          "Expected atomic-load-op to have one memoperand");
13562
13563   // Memory Reference
13564   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13565   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13566
13567   unsigned DstReg, SrcReg;
13568   unsigned MemOpndSlot;
13569
13570   unsigned CurOp = 0;
13571
13572   DstReg = MI->getOperand(CurOp++).getReg();
13573   MemOpndSlot = CurOp;
13574   CurOp += X86::AddrNumOperands;
13575   SrcReg = MI->getOperand(CurOp++).getReg();
13576
13577   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13578   MVT::SimpleValueType VT = *RC->vt_begin();
13579   unsigned t1 = MRI.createVirtualRegister(RC);
13580   unsigned t2 = MRI.createVirtualRegister(RC);
13581   unsigned t3 = MRI.createVirtualRegister(RC);
13582   unsigned t4 = MRI.createVirtualRegister(RC);
13583   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13584
13585   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13586   unsigned LOADOpc = getLoadOpcode(VT);
13587
13588   // For the atomic load-arith operator, we generate
13589   //
13590   //  thisMBB:
13591   //    t1 = LOAD [MI.addr]
13592   //  mainMBB:
13593   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13594   //    t1 = OP MI.val, EAX
13595   //    EAX = t4
13596   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13597   //    t3 = EAX
13598   //    JNE mainMBB
13599   //  sinkMBB:
13600   //    dst = t3
13601
13602   MachineBasicBlock *thisMBB = MBB;
13603   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13604   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13605   MF->insert(I, mainMBB);
13606   MF->insert(I, sinkMBB);
13607
13608   MachineInstrBuilder MIB;
13609
13610   // Transfer the remainder of BB and its successor edges to sinkMBB.
13611   sinkMBB->splice(sinkMBB->begin(), MBB,
13612                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13613   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13614
13615   // thisMBB:
13616   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13617   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13618     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13619     if (NewMO.isReg())
13620       NewMO.setIsKill(false);
13621     MIB.addOperand(NewMO);
13622   }
13623   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13624     unsigned flags = (*MMOI)->getFlags();
13625     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13626     MachineMemOperand *MMO =
13627       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13628                                (*MMOI)->getSize(),
13629                                (*MMOI)->getBaseAlignment(),
13630                                (*MMOI)->getTBAAInfo(),
13631                                (*MMOI)->getRanges());
13632     MIB.addMemOperand(MMO);
13633   }
13634
13635   thisMBB->addSuccessor(mainMBB);
13636
13637   // mainMBB:
13638   MachineBasicBlock *origMainMBB = mainMBB;
13639
13640   // Add a PHI.
13641   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13642                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13643
13644   unsigned Opc = MI->getOpcode();
13645   switch (Opc) {
13646   default:
13647     llvm_unreachable("Unhandled atomic-load-op opcode!");
13648   case X86::ATOMAND8:
13649   case X86::ATOMAND16:
13650   case X86::ATOMAND32:
13651   case X86::ATOMAND64:
13652   case X86::ATOMOR8:
13653   case X86::ATOMOR16:
13654   case X86::ATOMOR32:
13655   case X86::ATOMOR64:
13656   case X86::ATOMXOR8:
13657   case X86::ATOMXOR16:
13658   case X86::ATOMXOR32:
13659   case X86::ATOMXOR64: {
13660     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13661     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13662       .addReg(t4);
13663     break;
13664   }
13665   case X86::ATOMNAND8:
13666   case X86::ATOMNAND16:
13667   case X86::ATOMNAND32:
13668   case X86::ATOMNAND64: {
13669     unsigned Tmp = MRI.createVirtualRegister(RC);
13670     unsigned NOTOpc;
13671     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13672     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13673       .addReg(t4);
13674     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13675     break;
13676   }
13677   case X86::ATOMMAX8:
13678   case X86::ATOMMAX16:
13679   case X86::ATOMMAX32:
13680   case X86::ATOMMAX64:
13681   case X86::ATOMMIN8:
13682   case X86::ATOMMIN16:
13683   case X86::ATOMMIN32:
13684   case X86::ATOMMIN64:
13685   case X86::ATOMUMAX8:
13686   case X86::ATOMUMAX16:
13687   case X86::ATOMUMAX32:
13688   case X86::ATOMUMAX64:
13689   case X86::ATOMUMIN8:
13690   case X86::ATOMUMIN16:
13691   case X86::ATOMUMIN32:
13692   case X86::ATOMUMIN64: {
13693     unsigned CMPOpc;
13694     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13695
13696     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13697       .addReg(SrcReg)
13698       .addReg(t4);
13699
13700     if (Subtarget->hasCMov()) {
13701       if (VT != MVT::i8) {
13702         // Native support
13703         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13704           .addReg(SrcReg)
13705           .addReg(t4);
13706       } else {
13707         // Promote i8 to i32 to use CMOV32
13708         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13709         const TargetRegisterClass *RC32 =
13710           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13711         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13712         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13713         unsigned Tmp = MRI.createVirtualRegister(RC32);
13714
13715         unsigned Undef = MRI.createVirtualRegister(RC32);
13716         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13717
13718         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13719           .addReg(Undef)
13720           .addReg(SrcReg)
13721           .addImm(X86::sub_8bit);
13722         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13723           .addReg(Undef)
13724           .addReg(t4)
13725           .addImm(X86::sub_8bit);
13726
13727         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13728           .addReg(SrcReg32)
13729           .addReg(AccReg32);
13730
13731         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13732           .addReg(Tmp, 0, X86::sub_8bit);
13733       }
13734     } else {
13735       // Use pseudo select and lower them.
13736       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13737              "Invalid atomic-load-op transformation!");
13738       unsigned SelOpc = getPseudoCMOVOpc(VT);
13739       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13740       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13741       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13742               .addReg(SrcReg).addReg(t4)
13743               .addImm(CC);
13744       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13745       // Replace the original PHI node as mainMBB is changed after CMOV
13746       // lowering.
13747       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13748         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13749       Phi->eraseFromParent();
13750     }
13751     break;
13752   }
13753   }
13754
13755   // Copy PhyReg back from virtual register.
13756   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13757     .addReg(t4);
13758
13759   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13760   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13761     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13762     if (NewMO.isReg())
13763       NewMO.setIsKill(false);
13764     MIB.addOperand(NewMO);
13765   }
13766   MIB.addReg(t2);
13767   MIB.setMemRefs(MMOBegin, MMOEnd);
13768
13769   // Copy PhyReg back to virtual register.
13770   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13771     .addReg(PhyReg);
13772
13773   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13774
13775   mainMBB->addSuccessor(origMainMBB);
13776   mainMBB->addSuccessor(sinkMBB);
13777
13778   // sinkMBB:
13779   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13780           TII->get(TargetOpcode::COPY), DstReg)
13781     .addReg(t3);
13782
13783   MI->eraseFromParent();
13784   return sinkMBB;
13785 }
13786
13787 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13788 // instructions. They will be translated into a spin-loop or compare-exchange
13789 // loop from
13790 //
13791 //    ...
13792 //    dst = atomic-fetch-op MI.addr, MI.val
13793 //    ...
13794 //
13795 // to
13796 //
13797 //    ...
13798 //    t1L = LOAD [MI.addr + 0]
13799 //    t1H = LOAD [MI.addr + 4]
13800 // loop:
13801 //    t4L = phi(t1L, t3L / loop)
13802 //    t4H = phi(t1H, t3H / loop)
13803 //    t2L = OP MI.val.lo, t4L
13804 //    t2H = OP MI.val.hi, t4H
13805 //    EAX = t4L
13806 //    EDX = t4H
13807 //    EBX = t2L
13808 //    ECX = t2H
13809 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13810 //    t3L = EAX
13811 //    t3H = EDX
13812 //    JNE loop
13813 // sink:
13814 //    dstL = t3L
13815 //    dstH = t3H
13816 //    ...
13817 MachineBasicBlock *
13818 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13819                                            MachineBasicBlock *MBB) const {
13820   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13821   DebugLoc DL = MI->getDebugLoc();
13822
13823   MachineFunction *MF = MBB->getParent();
13824   MachineRegisterInfo &MRI = MF->getRegInfo();
13825
13826   const BasicBlock *BB = MBB->getBasicBlock();
13827   MachineFunction::iterator I = MBB;
13828   ++I;
13829
13830   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13831          "Unexpected number of operands");
13832
13833   assert(MI->hasOneMemOperand() &&
13834          "Expected atomic-load-op32 to have one memoperand");
13835
13836   // Memory Reference
13837   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13838   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13839
13840   unsigned DstLoReg, DstHiReg;
13841   unsigned SrcLoReg, SrcHiReg;
13842   unsigned MemOpndSlot;
13843
13844   unsigned CurOp = 0;
13845
13846   DstLoReg = MI->getOperand(CurOp++).getReg();
13847   DstHiReg = MI->getOperand(CurOp++).getReg();
13848   MemOpndSlot = CurOp;
13849   CurOp += X86::AddrNumOperands;
13850   SrcLoReg = MI->getOperand(CurOp++).getReg();
13851   SrcHiReg = MI->getOperand(CurOp++).getReg();
13852
13853   const TargetRegisterClass *RC = &X86::GR32RegClass;
13854   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13855
13856   unsigned t1L = MRI.createVirtualRegister(RC);
13857   unsigned t1H = MRI.createVirtualRegister(RC);
13858   unsigned t2L = MRI.createVirtualRegister(RC);
13859   unsigned t2H = MRI.createVirtualRegister(RC);
13860   unsigned t3L = MRI.createVirtualRegister(RC);
13861   unsigned t3H = MRI.createVirtualRegister(RC);
13862   unsigned t4L = MRI.createVirtualRegister(RC);
13863   unsigned t4H = MRI.createVirtualRegister(RC);
13864
13865   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13866   unsigned LOADOpc = X86::MOV32rm;
13867
13868   // For the atomic load-arith operator, we generate
13869   //
13870   //  thisMBB:
13871   //    t1L = LOAD [MI.addr + 0]
13872   //    t1H = LOAD [MI.addr + 4]
13873   //  mainMBB:
13874   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13875   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13876   //    t2L = OP MI.val.lo, t4L
13877   //    t2H = OP MI.val.hi, t4H
13878   //    EBX = t2L
13879   //    ECX = t2H
13880   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13881   //    t3L = EAX
13882   //    t3H = EDX
13883   //    JNE loop
13884   //  sinkMBB:
13885   //    dstL = t3L
13886   //    dstH = t3H
13887
13888   MachineBasicBlock *thisMBB = MBB;
13889   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13890   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13891   MF->insert(I, mainMBB);
13892   MF->insert(I, sinkMBB);
13893
13894   MachineInstrBuilder MIB;
13895
13896   // Transfer the remainder of BB and its successor edges to sinkMBB.
13897   sinkMBB->splice(sinkMBB->begin(), MBB,
13898                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13899   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13900
13901   // thisMBB:
13902   // Lo
13903   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13904   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13905     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13906     if (NewMO.isReg())
13907       NewMO.setIsKill(false);
13908     MIB.addOperand(NewMO);
13909   }
13910   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13911     unsigned flags = (*MMOI)->getFlags();
13912     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13913     MachineMemOperand *MMO =
13914       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13915                                (*MMOI)->getSize(),
13916                                (*MMOI)->getBaseAlignment(),
13917                                (*MMOI)->getTBAAInfo(),
13918                                (*MMOI)->getRanges());
13919     MIB.addMemOperand(MMO);
13920   };
13921   MachineInstr *LowMI = MIB;
13922
13923   // Hi
13924   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13925   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13926     if (i == X86::AddrDisp) {
13927       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13928     } else {
13929       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13930       if (NewMO.isReg())
13931         NewMO.setIsKill(false);
13932       MIB.addOperand(NewMO);
13933     }
13934   }
13935   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13936
13937   thisMBB->addSuccessor(mainMBB);
13938
13939   // mainMBB:
13940   MachineBasicBlock *origMainMBB = mainMBB;
13941
13942   // Add PHIs.
13943   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13944                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13945   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13946                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13947
13948   unsigned Opc = MI->getOpcode();
13949   switch (Opc) {
13950   default:
13951     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13952   case X86::ATOMAND6432:
13953   case X86::ATOMOR6432:
13954   case X86::ATOMXOR6432:
13955   case X86::ATOMADD6432:
13956   case X86::ATOMSUB6432: {
13957     unsigned HiOpc;
13958     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13959     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13960       .addReg(SrcLoReg);
13961     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13962       .addReg(SrcHiReg);
13963     break;
13964   }
13965   case X86::ATOMNAND6432: {
13966     unsigned HiOpc, NOTOpc;
13967     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13968     unsigned TmpL = MRI.createVirtualRegister(RC);
13969     unsigned TmpH = MRI.createVirtualRegister(RC);
13970     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13971       .addReg(t4L);
13972     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13973       .addReg(t4H);
13974     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13975     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13976     break;
13977   }
13978   case X86::ATOMMAX6432:
13979   case X86::ATOMMIN6432:
13980   case X86::ATOMUMAX6432:
13981   case X86::ATOMUMIN6432: {
13982     unsigned HiOpc;
13983     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13984     unsigned cL = MRI.createVirtualRegister(RC8);
13985     unsigned cH = MRI.createVirtualRegister(RC8);
13986     unsigned cL32 = MRI.createVirtualRegister(RC);
13987     unsigned cH32 = MRI.createVirtualRegister(RC);
13988     unsigned cc = MRI.createVirtualRegister(RC);
13989     // cl := cmp src_lo, lo
13990     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13991       .addReg(SrcLoReg).addReg(t4L);
13992     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13993     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13994     // ch := cmp src_hi, hi
13995     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13996       .addReg(SrcHiReg).addReg(t4H);
13997     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13998     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13999     // cc := if (src_hi == hi) ? cl : ch;
14000     if (Subtarget->hasCMov()) {
14001       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14002         .addReg(cH32).addReg(cL32);
14003     } else {
14004       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14005               .addReg(cH32).addReg(cL32)
14006               .addImm(X86::COND_E);
14007       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14008     }
14009     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14010     if (Subtarget->hasCMov()) {
14011       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14012         .addReg(SrcLoReg).addReg(t4L);
14013       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14014         .addReg(SrcHiReg).addReg(t4H);
14015     } else {
14016       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14017               .addReg(SrcLoReg).addReg(t4L)
14018               .addImm(X86::COND_NE);
14019       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14020       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14021       // 2nd CMOV lowering.
14022       mainMBB->addLiveIn(X86::EFLAGS);
14023       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14024               .addReg(SrcHiReg).addReg(t4H)
14025               .addImm(X86::COND_NE);
14026       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14027       // Replace the original PHI node as mainMBB is changed after CMOV
14028       // lowering.
14029       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14030         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14031       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14032         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14033       PhiL->eraseFromParent();
14034       PhiH->eraseFromParent();
14035     }
14036     break;
14037   }
14038   case X86::ATOMSWAP6432: {
14039     unsigned HiOpc;
14040     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14041     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14042     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14043     break;
14044   }
14045   }
14046
14047   // Copy EDX:EAX back from HiReg:LoReg
14048   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14049   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14050   // Copy ECX:EBX from t1H:t1L
14051   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14052   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14053
14054   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14055   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14056     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14057     if (NewMO.isReg())
14058       NewMO.setIsKill(false);
14059     MIB.addOperand(NewMO);
14060   }
14061   MIB.setMemRefs(MMOBegin, MMOEnd);
14062
14063   // Copy EDX:EAX back to t3H:t3L
14064   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14065   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14066
14067   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14068
14069   mainMBB->addSuccessor(origMainMBB);
14070   mainMBB->addSuccessor(sinkMBB);
14071
14072   // sinkMBB:
14073   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14074           TII->get(TargetOpcode::COPY), DstLoReg)
14075     .addReg(t3L);
14076   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14077           TII->get(TargetOpcode::COPY), DstHiReg)
14078     .addReg(t3H);
14079
14080   MI->eraseFromParent();
14081   return sinkMBB;
14082 }
14083
14084 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14085 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14086 // in the .td file.
14087 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14088                                        const TargetInstrInfo *TII) {
14089   unsigned Opc;
14090   switch (MI->getOpcode()) {
14091   default: llvm_unreachable("illegal opcode!");
14092   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14093   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14094   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14095   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14096   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14097   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14098   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14099   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14100   }
14101
14102   DebugLoc dl = MI->getDebugLoc();
14103   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14104
14105   unsigned NumArgs = MI->getNumOperands();
14106   for (unsigned i = 1; i < NumArgs; ++i) {
14107     MachineOperand &Op = MI->getOperand(i);
14108     if (!(Op.isReg() && Op.isImplicit()))
14109       MIB.addOperand(Op);
14110   }
14111   if (MI->hasOneMemOperand())
14112     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14113
14114   BuildMI(*BB, MI, dl,
14115     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14116     .addReg(X86::XMM0);
14117
14118   MI->eraseFromParent();
14119   return BB;
14120 }
14121
14122 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14123 // defs in an instruction pattern
14124 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14125                                        const TargetInstrInfo *TII) {
14126   unsigned Opc;
14127   switch (MI->getOpcode()) {
14128   default: llvm_unreachable("illegal opcode!");
14129   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
14130   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14131   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
14132   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14133   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
14134   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14135   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
14136   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14137   }
14138
14139   DebugLoc dl = MI->getDebugLoc();
14140   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14141
14142   unsigned NumArgs = MI->getNumOperands(); // remove the results
14143   for (unsigned i = 1; i < NumArgs; ++i) {
14144     MachineOperand &Op = MI->getOperand(i);
14145     if (!(Op.isReg() && Op.isImplicit()))
14146       MIB.addOperand(Op);
14147   }
14148   if (MI->hasOneMemOperand())
14149     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14150
14151   BuildMI(*BB, MI, dl,
14152     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14153     .addReg(X86::ECX);
14154
14155   MI->eraseFromParent();
14156   return BB;
14157 }
14158
14159 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14160                                        const TargetInstrInfo *TII,
14161                                        const X86Subtarget* Subtarget) {
14162   DebugLoc dl = MI->getDebugLoc();
14163
14164   // Address into RAX/EAX, other two args into ECX, EDX.
14165   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14166   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14167   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14168   for (int i = 0; i < X86::AddrNumOperands; ++i)
14169     MIB.addOperand(MI->getOperand(i));
14170
14171   unsigned ValOps = X86::AddrNumOperands;
14172   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14173     .addReg(MI->getOperand(ValOps).getReg());
14174   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14175     .addReg(MI->getOperand(ValOps+1).getReg());
14176
14177   // The instruction doesn't actually take any operands though.
14178   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14179
14180   MI->eraseFromParent(); // The pseudo is gone now.
14181   return BB;
14182 }
14183
14184 MachineBasicBlock *
14185 X86TargetLowering::EmitVAARG64WithCustomInserter(
14186                    MachineInstr *MI,
14187                    MachineBasicBlock *MBB) const {
14188   // Emit va_arg instruction on X86-64.
14189
14190   // Operands to this pseudo-instruction:
14191   // 0  ) Output        : destination address (reg)
14192   // 1-5) Input         : va_list address (addr, i64mem)
14193   // 6  ) ArgSize       : Size (in bytes) of vararg type
14194   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14195   // 8  ) Align         : Alignment of type
14196   // 9  ) EFLAGS (implicit-def)
14197
14198   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14199   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14200
14201   unsigned DestReg = MI->getOperand(0).getReg();
14202   MachineOperand &Base = MI->getOperand(1);
14203   MachineOperand &Scale = MI->getOperand(2);
14204   MachineOperand &Index = MI->getOperand(3);
14205   MachineOperand &Disp = MI->getOperand(4);
14206   MachineOperand &Segment = MI->getOperand(5);
14207   unsigned ArgSize = MI->getOperand(6).getImm();
14208   unsigned ArgMode = MI->getOperand(7).getImm();
14209   unsigned Align = MI->getOperand(8).getImm();
14210
14211   // Memory Reference
14212   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14213   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14214   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14215
14216   // Machine Information
14217   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14218   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14219   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14220   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14221   DebugLoc DL = MI->getDebugLoc();
14222
14223   // struct va_list {
14224   //   i32   gp_offset
14225   //   i32   fp_offset
14226   //   i64   overflow_area (address)
14227   //   i64   reg_save_area (address)
14228   // }
14229   // sizeof(va_list) = 24
14230   // alignment(va_list) = 8
14231
14232   unsigned TotalNumIntRegs = 6;
14233   unsigned TotalNumXMMRegs = 8;
14234   bool UseGPOffset = (ArgMode == 1);
14235   bool UseFPOffset = (ArgMode == 2);
14236   unsigned MaxOffset = TotalNumIntRegs * 8 +
14237                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
14238
14239   /* Align ArgSize to a multiple of 8 */
14240   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
14241   bool NeedsAlign = (Align > 8);
14242
14243   MachineBasicBlock *thisMBB = MBB;
14244   MachineBasicBlock *overflowMBB;
14245   MachineBasicBlock *offsetMBB;
14246   MachineBasicBlock *endMBB;
14247
14248   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
14249   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
14250   unsigned OffsetReg = 0;
14251
14252   if (!UseGPOffset && !UseFPOffset) {
14253     // If we only pull from the overflow region, we don't create a branch.
14254     // We don't need to alter control flow.
14255     OffsetDestReg = 0; // unused
14256     OverflowDestReg = DestReg;
14257
14258     offsetMBB = NULL;
14259     overflowMBB = thisMBB;
14260     endMBB = thisMBB;
14261   } else {
14262     // First emit code to check if gp_offset (or fp_offset) is below the bound.
14263     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
14264     // If not, pull from overflow_area. (branch to overflowMBB)
14265     //
14266     //       thisMBB
14267     //         |     .
14268     //         |        .
14269     //     offsetMBB   overflowMBB
14270     //         |        .
14271     //         |     .
14272     //        endMBB
14273
14274     // Registers for the PHI in endMBB
14275     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
14276     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
14277
14278     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14279     MachineFunction *MF = MBB->getParent();
14280     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14281     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14282     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14283
14284     MachineFunction::iterator MBBIter = MBB;
14285     ++MBBIter;
14286
14287     // Insert the new basic blocks
14288     MF->insert(MBBIter, offsetMBB);
14289     MF->insert(MBBIter, overflowMBB);
14290     MF->insert(MBBIter, endMBB);
14291
14292     // Transfer the remainder of MBB and its successor edges to endMBB.
14293     endMBB->splice(endMBB->begin(), thisMBB,
14294                     llvm::next(MachineBasicBlock::iterator(MI)),
14295                     thisMBB->end());
14296     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
14297
14298     // Make offsetMBB and overflowMBB successors of thisMBB
14299     thisMBB->addSuccessor(offsetMBB);
14300     thisMBB->addSuccessor(overflowMBB);
14301
14302     // endMBB is a successor of both offsetMBB and overflowMBB
14303     offsetMBB->addSuccessor(endMBB);
14304     overflowMBB->addSuccessor(endMBB);
14305
14306     // Load the offset value into a register
14307     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14308     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14309       .addOperand(Base)
14310       .addOperand(Scale)
14311       .addOperand(Index)
14312       .addDisp(Disp, UseFPOffset ? 4 : 0)
14313       .addOperand(Segment)
14314       .setMemRefs(MMOBegin, MMOEnd);
14315
14316     // Check if there is enough room left to pull this argument.
14317     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14318       .addReg(OffsetReg)
14319       .addImm(MaxOffset + 8 - ArgSizeA8);
14320
14321     // Branch to "overflowMBB" if offset >= max
14322     // Fall through to "offsetMBB" otherwise
14323     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14324       .addMBB(overflowMBB);
14325   }
14326
14327   // In offsetMBB, emit code to use the reg_save_area.
14328   if (offsetMBB) {
14329     assert(OffsetReg != 0);
14330
14331     // Read the reg_save_area address.
14332     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14333     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14334       .addOperand(Base)
14335       .addOperand(Scale)
14336       .addOperand(Index)
14337       .addDisp(Disp, 16)
14338       .addOperand(Segment)
14339       .setMemRefs(MMOBegin, MMOEnd);
14340
14341     // Zero-extend the offset
14342     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14343       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14344         .addImm(0)
14345         .addReg(OffsetReg)
14346         .addImm(X86::sub_32bit);
14347
14348     // Add the offset to the reg_save_area to get the final address.
14349     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14350       .addReg(OffsetReg64)
14351       .addReg(RegSaveReg);
14352
14353     // Compute the offset for the next argument
14354     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14355     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14356       .addReg(OffsetReg)
14357       .addImm(UseFPOffset ? 16 : 8);
14358
14359     // Store it back into the va_list.
14360     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14361       .addOperand(Base)
14362       .addOperand(Scale)
14363       .addOperand(Index)
14364       .addDisp(Disp, UseFPOffset ? 4 : 0)
14365       .addOperand(Segment)
14366       .addReg(NextOffsetReg)
14367       .setMemRefs(MMOBegin, MMOEnd);
14368
14369     // Jump to endMBB
14370     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14371       .addMBB(endMBB);
14372   }
14373
14374   //
14375   // Emit code to use overflow area
14376   //
14377
14378   // Load the overflow_area address into a register.
14379   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14380   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14381     .addOperand(Base)
14382     .addOperand(Scale)
14383     .addOperand(Index)
14384     .addDisp(Disp, 8)
14385     .addOperand(Segment)
14386     .setMemRefs(MMOBegin, MMOEnd);
14387
14388   // If we need to align it, do so. Otherwise, just copy the address
14389   // to OverflowDestReg.
14390   if (NeedsAlign) {
14391     // Align the overflow address
14392     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14393     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14394
14395     // aligned_addr = (addr + (align-1)) & ~(align-1)
14396     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14397       .addReg(OverflowAddrReg)
14398       .addImm(Align-1);
14399
14400     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14401       .addReg(TmpReg)
14402       .addImm(~(uint64_t)(Align-1));
14403   } else {
14404     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14405       .addReg(OverflowAddrReg);
14406   }
14407
14408   // Compute the next overflow address after this argument.
14409   // (the overflow address should be kept 8-byte aligned)
14410   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14411   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14412     .addReg(OverflowDestReg)
14413     .addImm(ArgSizeA8);
14414
14415   // Store the new overflow address.
14416   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14417     .addOperand(Base)
14418     .addOperand(Scale)
14419     .addOperand(Index)
14420     .addDisp(Disp, 8)
14421     .addOperand(Segment)
14422     .addReg(NextAddrReg)
14423     .setMemRefs(MMOBegin, MMOEnd);
14424
14425   // If we branched, emit the PHI to the front of endMBB.
14426   if (offsetMBB) {
14427     BuildMI(*endMBB, endMBB->begin(), DL,
14428             TII->get(X86::PHI), DestReg)
14429       .addReg(OffsetDestReg).addMBB(offsetMBB)
14430       .addReg(OverflowDestReg).addMBB(overflowMBB);
14431   }
14432
14433   // Erase the pseudo instruction
14434   MI->eraseFromParent();
14435
14436   return endMBB;
14437 }
14438
14439 MachineBasicBlock *
14440 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14441                                                  MachineInstr *MI,
14442                                                  MachineBasicBlock *MBB) const {
14443   // Emit code to save XMM registers to the stack. The ABI says that the
14444   // number of registers to save is given in %al, so it's theoretically
14445   // possible to do an indirect jump trick to avoid saving all of them,
14446   // however this code takes a simpler approach and just executes all
14447   // of the stores if %al is non-zero. It's less code, and it's probably
14448   // easier on the hardware branch predictor, and stores aren't all that
14449   // expensive anyway.
14450
14451   // Create the new basic blocks. One block contains all the XMM stores,
14452   // and one block is the final destination regardless of whether any
14453   // stores were performed.
14454   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14455   MachineFunction *F = MBB->getParent();
14456   MachineFunction::iterator MBBIter = MBB;
14457   ++MBBIter;
14458   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14459   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14460   F->insert(MBBIter, XMMSaveMBB);
14461   F->insert(MBBIter, EndMBB);
14462
14463   // Transfer the remainder of MBB and its successor edges to EndMBB.
14464   EndMBB->splice(EndMBB->begin(), MBB,
14465                  llvm::next(MachineBasicBlock::iterator(MI)),
14466                  MBB->end());
14467   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14468
14469   // The original block will now fall through to the XMM save block.
14470   MBB->addSuccessor(XMMSaveMBB);
14471   // The XMMSaveMBB will fall through to the end block.
14472   XMMSaveMBB->addSuccessor(EndMBB);
14473
14474   // Now add the instructions.
14475   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14476   DebugLoc DL = MI->getDebugLoc();
14477
14478   unsigned CountReg = MI->getOperand(0).getReg();
14479   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14480   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14481
14482   if (!Subtarget->isTargetWin64()) {
14483     // If %al is 0, branch around the XMM save block.
14484     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14485     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14486     MBB->addSuccessor(EndMBB);
14487   }
14488
14489   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14490   // In the XMM save block, save all the XMM argument registers.
14491   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14492     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14493     MachineMemOperand *MMO =
14494       F->getMachineMemOperand(
14495           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14496         MachineMemOperand::MOStore,
14497         /*Size=*/16, /*Align=*/16);
14498     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14499       .addFrameIndex(RegSaveFrameIndex)
14500       .addImm(/*Scale=*/1)
14501       .addReg(/*IndexReg=*/0)
14502       .addImm(/*Disp=*/Offset)
14503       .addReg(/*Segment=*/0)
14504       .addReg(MI->getOperand(i).getReg())
14505       .addMemOperand(MMO);
14506   }
14507
14508   MI->eraseFromParent();   // The pseudo instruction is gone now.
14509
14510   return EndMBB;
14511 }
14512
14513 // The EFLAGS operand of SelectItr might be missing a kill marker
14514 // because there were multiple uses of EFLAGS, and ISel didn't know
14515 // which to mark. Figure out whether SelectItr should have had a
14516 // kill marker, and set it if it should. Returns the correct kill
14517 // marker value.
14518 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14519                                      MachineBasicBlock* BB,
14520                                      const TargetRegisterInfo* TRI) {
14521   // Scan forward through BB for a use/def of EFLAGS.
14522   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14523   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14524     const MachineInstr& mi = *miI;
14525     if (mi.readsRegister(X86::EFLAGS))
14526       return false;
14527     if (mi.definesRegister(X86::EFLAGS))
14528       break; // Should have kill-flag - update below.
14529   }
14530
14531   // If we hit the end of the block, check whether EFLAGS is live into a
14532   // successor.
14533   if (miI == BB->end()) {
14534     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14535                                           sEnd = BB->succ_end();
14536          sItr != sEnd; ++sItr) {
14537       MachineBasicBlock* succ = *sItr;
14538       if (succ->isLiveIn(X86::EFLAGS))
14539         return false;
14540     }
14541   }
14542
14543   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14544   // out. SelectMI should have a kill flag on EFLAGS.
14545   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14546   return true;
14547 }
14548
14549 MachineBasicBlock *
14550 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14551                                      MachineBasicBlock *BB) const {
14552   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14553   DebugLoc DL = MI->getDebugLoc();
14554
14555   // To "insert" a SELECT_CC instruction, we actually have to insert the
14556   // diamond control-flow pattern.  The incoming instruction knows the
14557   // destination vreg to set, the condition code register to branch on, the
14558   // true/false values to select between, and a branch opcode to use.
14559   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14560   MachineFunction::iterator It = BB;
14561   ++It;
14562
14563   //  thisMBB:
14564   //  ...
14565   //   TrueVal = ...
14566   //   cmpTY ccX, r1, r2
14567   //   bCC copy1MBB
14568   //   fallthrough --> copy0MBB
14569   MachineBasicBlock *thisMBB = BB;
14570   MachineFunction *F = BB->getParent();
14571   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14572   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14573   F->insert(It, copy0MBB);
14574   F->insert(It, sinkMBB);
14575
14576   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14577   // live into the sink and copy blocks.
14578   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14579   if (!MI->killsRegister(X86::EFLAGS) &&
14580       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14581     copy0MBB->addLiveIn(X86::EFLAGS);
14582     sinkMBB->addLiveIn(X86::EFLAGS);
14583   }
14584
14585   // Transfer the remainder of BB and its successor edges to sinkMBB.
14586   sinkMBB->splice(sinkMBB->begin(), BB,
14587                   llvm::next(MachineBasicBlock::iterator(MI)),
14588                   BB->end());
14589   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14590
14591   // Add the true and fallthrough blocks as its successors.
14592   BB->addSuccessor(copy0MBB);
14593   BB->addSuccessor(sinkMBB);
14594
14595   // Create the conditional branch instruction.
14596   unsigned Opc =
14597     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14598   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14599
14600   //  copy0MBB:
14601   //   %FalseValue = ...
14602   //   # fallthrough to sinkMBB
14603   copy0MBB->addSuccessor(sinkMBB);
14604
14605   //  sinkMBB:
14606   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14607   //  ...
14608   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14609           TII->get(X86::PHI), MI->getOperand(0).getReg())
14610     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14611     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14612
14613   MI->eraseFromParent();   // The pseudo instruction is gone now.
14614   return sinkMBB;
14615 }
14616
14617 MachineBasicBlock *
14618 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14619                                         bool Is64Bit) const {
14620   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14621   DebugLoc DL = MI->getDebugLoc();
14622   MachineFunction *MF = BB->getParent();
14623   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14624
14625   assert(getTargetMachine().Options.EnableSegmentedStacks);
14626
14627   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14628   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14629
14630   // BB:
14631   //  ... [Till the alloca]
14632   // If stacklet is not large enough, jump to mallocMBB
14633   //
14634   // bumpMBB:
14635   //  Allocate by subtracting from RSP
14636   //  Jump to continueMBB
14637   //
14638   // mallocMBB:
14639   //  Allocate by call to runtime
14640   //
14641   // continueMBB:
14642   //  ...
14643   //  [rest of original BB]
14644   //
14645
14646   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14647   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14648   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14649
14650   MachineRegisterInfo &MRI = MF->getRegInfo();
14651   const TargetRegisterClass *AddrRegClass =
14652     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14653
14654   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14655     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14656     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14657     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14658     sizeVReg = MI->getOperand(1).getReg(),
14659     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14660
14661   MachineFunction::iterator MBBIter = BB;
14662   ++MBBIter;
14663
14664   MF->insert(MBBIter, bumpMBB);
14665   MF->insert(MBBIter, mallocMBB);
14666   MF->insert(MBBIter, continueMBB);
14667
14668   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14669                       (MachineBasicBlock::iterator(MI)), BB->end());
14670   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14671
14672   // Add code to the main basic block to check if the stack limit has been hit,
14673   // and if so, jump to mallocMBB otherwise to bumpMBB.
14674   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14675   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14676     .addReg(tmpSPVReg).addReg(sizeVReg);
14677   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14678     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14679     .addReg(SPLimitVReg);
14680   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14681
14682   // bumpMBB simply decreases the stack pointer, since we know the current
14683   // stacklet has enough space.
14684   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14685     .addReg(SPLimitVReg);
14686   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14687     .addReg(SPLimitVReg);
14688   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14689
14690   // Calls into a routine in libgcc to allocate more space from the heap.
14691   const uint32_t *RegMask =
14692     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14693   if (Is64Bit) {
14694     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14695       .addReg(sizeVReg);
14696     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14697       .addExternalSymbol("__morestack_allocate_stack_space")
14698       .addRegMask(RegMask)
14699       .addReg(X86::RDI, RegState::Implicit)
14700       .addReg(X86::RAX, RegState::ImplicitDefine);
14701   } else {
14702     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14703       .addImm(12);
14704     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14705     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14706       .addExternalSymbol("__morestack_allocate_stack_space")
14707       .addRegMask(RegMask)
14708       .addReg(X86::EAX, RegState::ImplicitDefine);
14709   }
14710
14711   if (!Is64Bit)
14712     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14713       .addImm(16);
14714
14715   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14716     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14717   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14718
14719   // Set up the CFG correctly.
14720   BB->addSuccessor(bumpMBB);
14721   BB->addSuccessor(mallocMBB);
14722   mallocMBB->addSuccessor(continueMBB);
14723   bumpMBB->addSuccessor(continueMBB);
14724
14725   // Take care of the PHI nodes.
14726   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14727           MI->getOperand(0).getReg())
14728     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14729     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14730
14731   // Delete the original pseudo instruction.
14732   MI->eraseFromParent();
14733
14734   // And we're done.
14735   return continueMBB;
14736 }
14737
14738 MachineBasicBlock *
14739 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14740                                           MachineBasicBlock *BB) const {
14741   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14742   DebugLoc DL = MI->getDebugLoc();
14743
14744   assert(!Subtarget->isTargetEnvMacho());
14745
14746   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14747   // non-trivial part is impdef of ESP.
14748
14749   if (Subtarget->isTargetWin64()) {
14750     if (Subtarget->isTargetCygMing()) {
14751       // ___chkstk(Mingw64):
14752       // Clobbers R10, R11, RAX and EFLAGS.
14753       // Updates RSP.
14754       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14755         .addExternalSymbol("___chkstk")
14756         .addReg(X86::RAX, RegState::Implicit)
14757         .addReg(X86::RSP, RegState::Implicit)
14758         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14759         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14760         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14761     } else {
14762       // __chkstk(MSVCRT): does not update stack pointer.
14763       // Clobbers R10, R11 and EFLAGS.
14764       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14765         .addExternalSymbol("__chkstk")
14766         .addReg(X86::RAX, RegState::Implicit)
14767         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14768       // RAX has the offset to be subtracted from RSP.
14769       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14770         .addReg(X86::RSP)
14771         .addReg(X86::RAX);
14772     }
14773   } else {
14774     const char *StackProbeSymbol =
14775       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14776
14777     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14778       .addExternalSymbol(StackProbeSymbol)
14779       .addReg(X86::EAX, RegState::Implicit)
14780       .addReg(X86::ESP, RegState::Implicit)
14781       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14782       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14783       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14784   }
14785
14786   MI->eraseFromParent();   // The pseudo instruction is gone now.
14787   return BB;
14788 }
14789
14790 MachineBasicBlock *
14791 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14792                                       MachineBasicBlock *BB) const {
14793   // This is pretty easy.  We're taking the value that we received from
14794   // our load from the relocation, sticking it in either RDI (x86-64)
14795   // or EAX and doing an indirect call.  The return value will then
14796   // be in the normal return register.
14797   const X86InstrInfo *TII
14798     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14799   DebugLoc DL = MI->getDebugLoc();
14800   MachineFunction *F = BB->getParent();
14801
14802   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14803   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14804
14805   // Get a register mask for the lowered call.
14806   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14807   // proper register mask.
14808   const uint32_t *RegMask =
14809     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14810   if (Subtarget->is64Bit()) {
14811     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14812                                       TII->get(X86::MOV64rm), X86::RDI)
14813     .addReg(X86::RIP)
14814     .addImm(0).addReg(0)
14815     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14816                       MI->getOperand(3).getTargetFlags())
14817     .addReg(0);
14818     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14819     addDirectMem(MIB, X86::RDI);
14820     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14821   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14822     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14823                                       TII->get(X86::MOV32rm), X86::EAX)
14824     .addReg(0)
14825     .addImm(0).addReg(0)
14826     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14827                       MI->getOperand(3).getTargetFlags())
14828     .addReg(0);
14829     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14830     addDirectMem(MIB, X86::EAX);
14831     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14832   } else {
14833     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14834                                       TII->get(X86::MOV32rm), X86::EAX)
14835     .addReg(TII->getGlobalBaseReg(F))
14836     .addImm(0).addReg(0)
14837     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14838                       MI->getOperand(3).getTargetFlags())
14839     .addReg(0);
14840     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14841     addDirectMem(MIB, X86::EAX);
14842     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14843   }
14844
14845   MI->eraseFromParent(); // The pseudo instruction is gone now.
14846   return BB;
14847 }
14848
14849 MachineBasicBlock *
14850 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14851                                     MachineBasicBlock *MBB) const {
14852   DebugLoc DL = MI->getDebugLoc();
14853   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14854
14855   MachineFunction *MF = MBB->getParent();
14856   MachineRegisterInfo &MRI = MF->getRegInfo();
14857
14858   const BasicBlock *BB = MBB->getBasicBlock();
14859   MachineFunction::iterator I = MBB;
14860   ++I;
14861
14862   // Memory Reference
14863   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14864   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14865
14866   unsigned DstReg;
14867   unsigned MemOpndSlot = 0;
14868
14869   unsigned CurOp = 0;
14870
14871   DstReg = MI->getOperand(CurOp++).getReg();
14872   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14873   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14874   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14875   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14876
14877   MemOpndSlot = CurOp;
14878
14879   MVT PVT = getPointerTy();
14880   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14881          "Invalid Pointer Size!");
14882
14883   // For v = setjmp(buf), we generate
14884   //
14885   // thisMBB:
14886   //  buf[LabelOffset] = restoreMBB
14887   //  SjLjSetup restoreMBB
14888   //
14889   // mainMBB:
14890   //  v_main = 0
14891   //
14892   // sinkMBB:
14893   //  v = phi(main, restore)
14894   //
14895   // restoreMBB:
14896   //  v_restore = 1
14897
14898   MachineBasicBlock *thisMBB = MBB;
14899   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14900   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14901   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14902   MF->insert(I, mainMBB);
14903   MF->insert(I, sinkMBB);
14904   MF->push_back(restoreMBB);
14905
14906   MachineInstrBuilder MIB;
14907
14908   // Transfer the remainder of BB and its successor edges to sinkMBB.
14909   sinkMBB->splice(sinkMBB->begin(), MBB,
14910                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14911   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14912
14913   // thisMBB:
14914   unsigned PtrStoreOpc = 0;
14915   unsigned LabelReg = 0;
14916   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14917   Reloc::Model RM = getTargetMachine().getRelocationModel();
14918   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14919                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14920
14921   // Prepare IP either in reg or imm.
14922   if (!UseImmLabel) {
14923     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14924     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14925     LabelReg = MRI.createVirtualRegister(PtrRC);
14926     if (Subtarget->is64Bit()) {
14927       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14928               .addReg(X86::RIP)
14929               .addImm(0)
14930               .addReg(0)
14931               .addMBB(restoreMBB)
14932               .addReg(0);
14933     } else {
14934       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14935       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14936               .addReg(XII->getGlobalBaseReg(MF))
14937               .addImm(0)
14938               .addReg(0)
14939               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14940               .addReg(0);
14941     }
14942   } else
14943     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14944   // Store IP
14945   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14946   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14947     if (i == X86::AddrDisp)
14948       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14949     else
14950       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14951   }
14952   if (!UseImmLabel)
14953     MIB.addReg(LabelReg);
14954   else
14955     MIB.addMBB(restoreMBB);
14956   MIB.setMemRefs(MMOBegin, MMOEnd);
14957   // Setup
14958   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14959           .addMBB(restoreMBB);
14960
14961   const X86RegisterInfo *RegInfo =
14962     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14963   MIB.addRegMask(RegInfo->getNoPreservedMask());
14964   thisMBB->addSuccessor(mainMBB);
14965   thisMBB->addSuccessor(restoreMBB);
14966
14967   // mainMBB:
14968   //  EAX = 0
14969   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14970   mainMBB->addSuccessor(sinkMBB);
14971
14972   // sinkMBB:
14973   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14974           TII->get(X86::PHI), DstReg)
14975     .addReg(mainDstReg).addMBB(mainMBB)
14976     .addReg(restoreDstReg).addMBB(restoreMBB);
14977
14978   // restoreMBB:
14979   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14980   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14981   restoreMBB->addSuccessor(sinkMBB);
14982
14983   MI->eraseFromParent();
14984   return sinkMBB;
14985 }
14986
14987 MachineBasicBlock *
14988 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14989                                      MachineBasicBlock *MBB) const {
14990   DebugLoc DL = MI->getDebugLoc();
14991   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14992
14993   MachineFunction *MF = MBB->getParent();
14994   MachineRegisterInfo &MRI = MF->getRegInfo();
14995
14996   // Memory Reference
14997   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14998   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14999
15000   MVT PVT = getPointerTy();
15001   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15002          "Invalid Pointer Size!");
15003
15004   const TargetRegisterClass *RC =
15005     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15006   unsigned Tmp = MRI.createVirtualRegister(RC);
15007   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15008   const X86RegisterInfo *RegInfo =
15009     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15010   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15011   unsigned SP = RegInfo->getStackRegister();
15012
15013   MachineInstrBuilder MIB;
15014
15015   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15016   const int64_t SPOffset = 2 * PVT.getStoreSize();
15017
15018   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15019   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15020
15021   // Reload FP
15022   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15023   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15024     MIB.addOperand(MI->getOperand(i));
15025   MIB.setMemRefs(MMOBegin, MMOEnd);
15026   // Reload IP
15027   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15028   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15029     if (i == X86::AddrDisp)
15030       MIB.addDisp(MI->getOperand(i), LabelOffset);
15031     else
15032       MIB.addOperand(MI->getOperand(i));
15033   }
15034   MIB.setMemRefs(MMOBegin, MMOEnd);
15035   // Reload SP
15036   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15037   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15038     if (i == X86::AddrDisp)
15039       MIB.addDisp(MI->getOperand(i), SPOffset);
15040     else
15041       MIB.addOperand(MI->getOperand(i));
15042   }
15043   MIB.setMemRefs(MMOBegin, MMOEnd);
15044   // Jump
15045   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15046
15047   MI->eraseFromParent();
15048   return MBB;
15049 }
15050
15051 MachineBasicBlock *
15052 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15053                                                MachineBasicBlock *BB) const {
15054   switch (MI->getOpcode()) {
15055   default: llvm_unreachable("Unexpected instr type to insert");
15056   case X86::TAILJMPd64:
15057   case X86::TAILJMPr64:
15058   case X86::TAILJMPm64:
15059     llvm_unreachable("TAILJMP64 would not be touched here.");
15060   case X86::TCRETURNdi64:
15061   case X86::TCRETURNri64:
15062   case X86::TCRETURNmi64:
15063     return BB;
15064   case X86::WIN_ALLOCA:
15065     return EmitLoweredWinAlloca(MI, BB);
15066   case X86::SEG_ALLOCA_32:
15067     return EmitLoweredSegAlloca(MI, BB, false);
15068   case X86::SEG_ALLOCA_64:
15069     return EmitLoweredSegAlloca(MI, BB, true);
15070   case X86::TLSCall_32:
15071   case X86::TLSCall_64:
15072     return EmitLoweredTLSCall(MI, BB);
15073   case X86::CMOV_GR8:
15074   case X86::CMOV_FR32:
15075   case X86::CMOV_FR64:
15076   case X86::CMOV_V4F32:
15077   case X86::CMOV_V2F64:
15078   case X86::CMOV_V2I64:
15079   case X86::CMOV_V8F32:
15080   case X86::CMOV_V4F64:
15081   case X86::CMOV_V4I64:
15082   case X86::CMOV_GR16:
15083   case X86::CMOV_GR32:
15084   case X86::CMOV_RFP32:
15085   case X86::CMOV_RFP64:
15086   case X86::CMOV_RFP80:
15087     return EmitLoweredSelect(MI, BB);
15088
15089   case X86::FP32_TO_INT16_IN_MEM:
15090   case X86::FP32_TO_INT32_IN_MEM:
15091   case X86::FP32_TO_INT64_IN_MEM:
15092   case X86::FP64_TO_INT16_IN_MEM:
15093   case X86::FP64_TO_INT32_IN_MEM:
15094   case X86::FP64_TO_INT64_IN_MEM:
15095   case X86::FP80_TO_INT16_IN_MEM:
15096   case X86::FP80_TO_INT32_IN_MEM:
15097   case X86::FP80_TO_INT64_IN_MEM: {
15098     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15099     DebugLoc DL = MI->getDebugLoc();
15100
15101     // Change the floating point control register to use "round towards zero"
15102     // mode when truncating to an integer value.
15103     MachineFunction *F = BB->getParent();
15104     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15105     addFrameReference(BuildMI(*BB, MI, DL,
15106                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
15107
15108     // Load the old value of the high byte of the control word...
15109     unsigned OldCW =
15110       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15111     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15112                       CWFrameIdx);
15113
15114     // Set the high part to be round to zero...
15115     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15116       .addImm(0xC7F);
15117
15118     // Reload the modified control word now...
15119     addFrameReference(BuildMI(*BB, MI, DL,
15120                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15121
15122     // Restore the memory image of control word to original value
15123     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15124       .addReg(OldCW);
15125
15126     // Get the X86 opcode to use.
15127     unsigned Opc;
15128     switch (MI->getOpcode()) {
15129     default: llvm_unreachable("illegal opcode!");
15130     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15131     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15132     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15133     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15134     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15135     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15136     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15137     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15138     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15139     }
15140
15141     X86AddressMode AM;
15142     MachineOperand &Op = MI->getOperand(0);
15143     if (Op.isReg()) {
15144       AM.BaseType = X86AddressMode::RegBase;
15145       AM.Base.Reg = Op.getReg();
15146     } else {
15147       AM.BaseType = X86AddressMode::FrameIndexBase;
15148       AM.Base.FrameIndex = Op.getIndex();
15149     }
15150     Op = MI->getOperand(1);
15151     if (Op.isImm())
15152       AM.Scale = Op.getImm();
15153     Op = MI->getOperand(2);
15154     if (Op.isImm())
15155       AM.IndexReg = Op.getImm();
15156     Op = MI->getOperand(3);
15157     if (Op.isGlobal()) {
15158       AM.GV = Op.getGlobal();
15159     } else {
15160       AM.Disp = Op.getImm();
15161     }
15162     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15163                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15164
15165     // Reload the original control word now.
15166     addFrameReference(BuildMI(*BB, MI, DL,
15167                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15168
15169     MI->eraseFromParent();   // The pseudo instruction is gone now.
15170     return BB;
15171   }
15172     // String/text processing lowering.
15173   case X86::PCMPISTRM128REG:
15174   case X86::VPCMPISTRM128REG:
15175   case X86::PCMPISTRM128MEM:
15176   case X86::VPCMPISTRM128MEM:
15177   case X86::PCMPESTRM128REG:
15178   case X86::VPCMPESTRM128REG:
15179   case X86::PCMPESTRM128MEM:
15180   case X86::VPCMPESTRM128MEM:
15181     assert(Subtarget->hasSSE42() &&
15182            "Target must have SSE4.2 or AVX features enabled");
15183     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15184
15185   // String/text processing lowering.
15186   case X86::PCMPISTRIREG:
15187   case X86::VPCMPISTRIREG:
15188   case X86::PCMPISTRIMEM:
15189   case X86::VPCMPISTRIMEM:
15190   case X86::PCMPESTRIREG:
15191   case X86::VPCMPESTRIREG:
15192   case X86::PCMPESTRIMEM:
15193   case X86::VPCMPESTRIMEM:
15194     assert(Subtarget->hasSSE42() &&
15195            "Target must have SSE4.2 or AVX features enabled");
15196     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15197
15198   // Thread synchronization.
15199   case X86::MONITOR:
15200     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15201
15202   // xbegin
15203   case X86::XBEGIN:
15204     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15205
15206   // Atomic Lowering.
15207   case X86::ATOMAND8:
15208   case X86::ATOMAND16:
15209   case X86::ATOMAND32:
15210   case X86::ATOMAND64:
15211     // Fall through
15212   case X86::ATOMOR8:
15213   case X86::ATOMOR16:
15214   case X86::ATOMOR32:
15215   case X86::ATOMOR64:
15216     // Fall through
15217   case X86::ATOMXOR16:
15218   case X86::ATOMXOR8:
15219   case X86::ATOMXOR32:
15220   case X86::ATOMXOR64:
15221     // Fall through
15222   case X86::ATOMNAND8:
15223   case X86::ATOMNAND16:
15224   case X86::ATOMNAND32:
15225   case X86::ATOMNAND64:
15226     // Fall through
15227   case X86::ATOMMAX8:
15228   case X86::ATOMMAX16:
15229   case X86::ATOMMAX32:
15230   case X86::ATOMMAX64:
15231     // Fall through
15232   case X86::ATOMMIN8:
15233   case X86::ATOMMIN16:
15234   case X86::ATOMMIN32:
15235   case X86::ATOMMIN64:
15236     // Fall through
15237   case X86::ATOMUMAX8:
15238   case X86::ATOMUMAX16:
15239   case X86::ATOMUMAX32:
15240   case X86::ATOMUMAX64:
15241     // Fall through
15242   case X86::ATOMUMIN8:
15243   case X86::ATOMUMIN16:
15244   case X86::ATOMUMIN32:
15245   case X86::ATOMUMIN64:
15246     return EmitAtomicLoadArith(MI, BB);
15247
15248   // This group does 64-bit operations on a 32-bit host.
15249   case X86::ATOMAND6432:
15250   case X86::ATOMOR6432:
15251   case X86::ATOMXOR6432:
15252   case X86::ATOMNAND6432:
15253   case X86::ATOMADD6432:
15254   case X86::ATOMSUB6432:
15255   case X86::ATOMMAX6432:
15256   case X86::ATOMMIN6432:
15257   case X86::ATOMUMAX6432:
15258   case X86::ATOMUMIN6432:
15259   case X86::ATOMSWAP6432:
15260     return EmitAtomicLoadArith6432(MI, BB);
15261
15262   case X86::VASTART_SAVE_XMM_REGS:
15263     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
15264
15265   case X86::VAARG_64:
15266     return EmitVAARG64WithCustomInserter(MI, BB);
15267
15268   case X86::EH_SjLj_SetJmp32:
15269   case X86::EH_SjLj_SetJmp64:
15270     return emitEHSjLjSetJmp(MI, BB);
15271
15272   case X86::EH_SjLj_LongJmp32:
15273   case X86::EH_SjLj_LongJmp64:
15274     return emitEHSjLjLongJmp(MI, BB);
15275   }
15276 }
15277
15278 //===----------------------------------------------------------------------===//
15279 //                           X86 Optimization Hooks
15280 //===----------------------------------------------------------------------===//
15281
15282 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
15283                                                        APInt &KnownZero,
15284                                                        APInt &KnownOne,
15285                                                        const SelectionDAG &DAG,
15286                                                        unsigned Depth) const {
15287   unsigned BitWidth = KnownZero.getBitWidth();
15288   unsigned Opc = Op.getOpcode();
15289   assert((Opc >= ISD::BUILTIN_OP_END ||
15290           Opc == ISD::INTRINSIC_WO_CHAIN ||
15291           Opc == ISD::INTRINSIC_W_CHAIN ||
15292           Opc == ISD::INTRINSIC_VOID) &&
15293          "Should use MaskedValueIsZero if you don't know whether Op"
15294          " is a target node!");
15295
15296   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
15297   switch (Opc) {
15298   default: break;
15299   case X86ISD::ADD:
15300   case X86ISD::SUB:
15301   case X86ISD::ADC:
15302   case X86ISD::SBB:
15303   case X86ISD::SMUL:
15304   case X86ISD::UMUL:
15305   case X86ISD::INC:
15306   case X86ISD::DEC:
15307   case X86ISD::OR:
15308   case X86ISD::XOR:
15309   case X86ISD::AND:
15310     // These nodes' second result is a boolean.
15311     if (Op.getResNo() == 0)
15312       break;
15313     // Fallthrough
15314   case X86ISD::SETCC:
15315     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15316     break;
15317   case ISD::INTRINSIC_WO_CHAIN: {
15318     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15319     unsigned NumLoBits = 0;
15320     switch (IntId) {
15321     default: break;
15322     case Intrinsic::x86_sse_movmsk_ps:
15323     case Intrinsic::x86_avx_movmsk_ps_256:
15324     case Intrinsic::x86_sse2_movmsk_pd:
15325     case Intrinsic::x86_avx_movmsk_pd_256:
15326     case Intrinsic::x86_mmx_pmovmskb:
15327     case Intrinsic::x86_sse2_pmovmskb_128:
15328     case Intrinsic::x86_avx2_pmovmskb: {
15329       // High bits of movmskp{s|d}, pmovmskb are known zero.
15330       switch (IntId) {
15331         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15332         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
15333         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
15334         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
15335         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
15336         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
15337         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
15338         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
15339       }
15340       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15341       break;
15342     }
15343     }
15344     break;
15345   }
15346   }
15347 }
15348
15349 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15350                                                          unsigned Depth) const {
15351   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15352   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15353     return Op.getValueType().getScalarType().getSizeInBits();
15354
15355   // Fallback case.
15356   return 1;
15357 }
15358
15359 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15360 /// node is a GlobalAddress + offset.
15361 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15362                                        const GlobalValue* &GA,
15363                                        int64_t &Offset) const {
15364   if (N->getOpcode() == X86ISD::Wrapper) {
15365     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15366       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15367       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15368       return true;
15369     }
15370   }
15371   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15372 }
15373
15374 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15375 /// same as extracting the high 128-bit part of 256-bit vector and then
15376 /// inserting the result into the low part of a new 256-bit vector
15377 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15378   EVT VT = SVOp->getValueType(0);
15379   unsigned NumElems = VT.getVectorNumElements();
15380
15381   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15382   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15383     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15384         SVOp->getMaskElt(j) >= 0)
15385       return false;
15386
15387   return true;
15388 }
15389
15390 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15391 /// same as extracting the low 128-bit part of 256-bit vector and then
15392 /// inserting the result into the high part of a new 256-bit vector
15393 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15394   EVT VT = SVOp->getValueType(0);
15395   unsigned NumElems = VT.getVectorNumElements();
15396
15397   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15398   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15399     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15400         SVOp->getMaskElt(j) >= 0)
15401       return false;
15402
15403   return true;
15404 }
15405
15406 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15407 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15408                                         TargetLowering::DAGCombinerInfo &DCI,
15409                                         const X86Subtarget* Subtarget) {
15410   SDLoc dl(N);
15411   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15412   SDValue V1 = SVOp->getOperand(0);
15413   SDValue V2 = SVOp->getOperand(1);
15414   EVT VT = SVOp->getValueType(0);
15415   unsigned NumElems = VT.getVectorNumElements();
15416
15417   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15418       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15419     //
15420     //                   0,0,0,...
15421     //                      |
15422     //    V      UNDEF    BUILD_VECTOR    UNDEF
15423     //     \      /           \           /
15424     //  CONCAT_VECTOR         CONCAT_VECTOR
15425     //         \                  /
15426     //          \                /
15427     //          RESULT: V + zero extended
15428     //
15429     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15430         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15431         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15432       return SDValue();
15433
15434     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15435       return SDValue();
15436
15437     // To match the shuffle mask, the first half of the mask should
15438     // be exactly the first vector, and all the rest a splat with the
15439     // first element of the second one.
15440     for (unsigned i = 0; i != NumElems/2; ++i)
15441       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15442           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15443         return SDValue();
15444
15445     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15446     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15447       if (Ld->hasNUsesOfValue(1, 0)) {
15448         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15449         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15450         SDValue ResNode =
15451           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15452                                   array_lengthof(Ops),
15453                                   Ld->getMemoryVT(),
15454                                   Ld->getPointerInfo(),
15455                                   Ld->getAlignment(),
15456                                   false/*isVolatile*/, true/*ReadMem*/,
15457                                   false/*WriteMem*/);
15458
15459         // Make sure the newly-created LOAD is in the same position as Ld in
15460         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15461         // and update uses of Ld's output chain to use the TokenFactor.
15462         if (Ld->hasAnyUseOfValue(1)) {
15463           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15464                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15465           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15466           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15467                                  SDValue(ResNode.getNode(), 1));
15468         }
15469
15470         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15471       }
15472     }
15473
15474     // Emit a zeroed vector and insert the desired subvector on its
15475     // first half.
15476     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15477     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15478     return DCI.CombineTo(N, InsV);
15479   }
15480
15481   //===--------------------------------------------------------------------===//
15482   // Combine some shuffles into subvector extracts and inserts:
15483   //
15484
15485   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15486   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15487     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15488     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15489     return DCI.CombineTo(N, InsV);
15490   }
15491
15492   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15493   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15494     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15495     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15496     return DCI.CombineTo(N, InsV);
15497   }
15498
15499   return SDValue();
15500 }
15501
15502 /// PerformShuffleCombine - Performs several different shuffle combines.
15503 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15504                                      TargetLowering::DAGCombinerInfo &DCI,
15505                                      const X86Subtarget *Subtarget) {
15506   SDLoc dl(N);
15507   EVT VT = N->getValueType(0);
15508
15509   // Don't create instructions with illegal types after legalize types has run.
15510   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15511   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15512     return SDValue();
15513
15514   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15515   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15516       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15517     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15518
15519   // Only handle 128 wide vector from here on.
15520   if (!VT.is128BitVector())
15521     return SDValue();
15522
15523   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15524   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15525   // consecutive, non-overlapping, and in the right order.
15526   SmallVector<SDValue, 16> Elts;
15527   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15528     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15529
15530   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15531 }
15532
15533 /// PerformTruncateCombine - Converts truncate operation to
15534 /// a sequence of vector shuffle operations.
15535 /// It is possible when we truncate 256-bit vector to 128-bit vector
15536 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15537                                       TargetLowering::DAGCombinerInfo &DCI,
15538                                       const X86Subtarget *Subtarget)  {
15539   return SDValue();
15540 }
15541
15542 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15543 /// specific shuffle of a load can be folded into a single element load.
15544 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15545 /// shuffles have been customed lowered so we need to handle those here.
15546 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15547                                          TargetLowering::DAGCombinerInfo &DCI) {
15548   if (DCI.isBeforeLegalizeOps())
15549     return SDValue();
15550
15551   SDValue InVec = N->getOperand(0);
15552   SDValue EltNo = N->getOperand(1);
15553
15554   if (!isa<ConstantSDNode>(EltNo))
15555     return SDValue();
15556
15557   EVT VT = InVec.getValueType();
15558
15559   bool HasShuffleIntoBitcast = false;
15560   if (InVec.getOpcode() == ISD::BITCAST) {
15561     // Don't duplicate a load with other uses.
15562     if (!InVec.hasOneUse())
15563       return SDValue();
15564     EVT BCVT = InVec.getOperand(0).getValueType();
15565     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15566       return SDValue();
15567     InVec = InVec.getOperand(0);
15568     HasShuffleIntoBitcast = true;
15569   }
15570
15571   if (!isTargetShuffle(InVec.getOpcode()))
15572     return SDValue();
15573
15574   // Don't duplicate a load with other uses.
15575   if (!InVec.hasOneUse())
15576     return SDValue();
15577
15578   SmallVector<int, 16> ShuffleMask;
15579   bool UnaryShuffle;
15580   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15581                             UnaryShuffle))
15582     return SDValue();
15583
15584   // Select the input vector, guarding against out of range extract vector.
15585   unsigned NumElems = VT.getVectorNumElements();
15586   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15587   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15588   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15589                                          : InVec.getOperand(1);
15590
15591   // If inputs to shuffle are the same for both ops, then allow 2 uses
15592   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15593
15594   if (LdNode.getOpcode() == ISD::BITCAST) {
15595     // Don't duplicate a load with other uses.
15596     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15597       return SDValue();
15598
15599     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15600     LdNode = LdNode.getOperand(0);
15601   }
15602
15603   if (!ISD::isNormalLoad(LdNode.getNode()))
15604     return SDValue();
15605
15606   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15607
15608   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15609     return SDValue();
15610
15611   if (HasShuffleIntoBitcast) {
15612     // If there's a bitcast before the shuffle, check if the load type and
15613     // alignment is valid.
15614     unsigned Align = LN0->getAlignment();
15615     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15616     unsigned NewAlign = TLI.getDataLayout()->
15617       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15618
15619     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15620       return SDValue();
15621   }
15622
15623   // All checks match so transform back to vector_shuffle so that DAG combiner
15624   // can finish the job
15625   SDLoc dl(N);
15626
15627   // Create shuffle node taking into account the case that its a unary shuffle
15628   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15629   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15630                                  InVec.getOperand(0), Shuffle,
15631                                  &ShuffleMask[0]);
15632   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15633   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15634                      EltNo);
15635 }
15636
15637 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15638 /// generation and convert it from being a bunch of shuffles and extracts
15639 /// to a simple store and scalar loads to extract the elements.
15640 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15641                                          TargetLowering::DAGCombinerInfo &DCI) {
15642   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15643   if (NewOp.getNode())
15644     return NewOp;
15645
15646   SDValue InputVector = N->getOperand(0);
15647   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15648   // from mmx to v2i32 has a single usage.
15649   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15650       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15651       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15652     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15653                        N->getValueType(0),
15654                        InputVector.getNode()->getOperand(0));
15655
15656   // Only operate on vectors of 4 elements, where the alternative shuffling
15657   // gets to be more expensive.
15658   if (InputVector.getValueType() != MVT::v4i32)
15659     return SDValue();
15660
15661   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15662   // single use which is a sign-extend or zero-extend, and all elements are
15663   // used.
15664   SmallVector<SDNode *, 4> Uses;
15665   unsigned ExtractedElements = 0;
15666   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15667        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15668     if (UI.getUse().getResNo() != InputVector.getResNo())
15669       return SDValue();
15670
15671     SDNode *Extract = *UI;
15672     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15673       return SDValue();
15674
15675     if (Extract->getValueType(0) != MVT::i32)
15676       return SDValue();
15677     if (!Extract->hasOneUse())
15678       return SDValue();
15679     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15680         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15681       return SDValue();
15682     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15683       return SDValue();
15684
15685     // Record which element was extracted.
15686     ExtractedElements |=
15687       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15688
15689     Uses.push_back(Extract);
15690   }
15691
15692   // If not all the elements were used, this may not be worthwhile.
15693   if (ExtractedElements != 15)
15694     return SDValue();
15695
15696   // Ok, we've now decided to do the transformation.
15697   SDLoc dl(InputVector);
15698
15699   // Store the value to a temporary stack slot.
15700   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15701   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15702                             MachinePointerInfo(), false, false, 0);
15703
15704   // Replace each use (extract) with a load of the appropriate element.
15705   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15706        UE = Uses.end(); UI != UE; ++UI) {
15707     SDNode *Extract = *UI;
15708
15709     // cOMpute the element's address.
15710     SDValue Idx = Extract->getOperand(1);
15711     unsigned EltSize =
15712         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15713     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15714     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15715     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15716
15717     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15718                                      StackPtr, OffsetVal);
15719
15720     // Load the scalar.
15721     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15722                                      ScalarAddr, MachinePointerInfo(),
15723                                      false, false, false, 0);
15724
15725     // Replace the exact with the load.
15726     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15727   }
15728
15729   // The replacement was made in place; don't return anything.
15730   return SDValue();
15731 }
15732
15733 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15734 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15735                                    SDValue RHS, SelectionDAG &DAG,
15736                                    const X86Subtarget *Subtarget) {
15737   if (!VT.isVector())
15738     return 0;
15739
15740   switch (VT.getSimpleVT().SimpleTy) {
15741   default: return 0;
15742   case MVT::v32i8:
15743   case MVT::v16i16:
15744   case MVT::v8i32:
15745     if (!Subtarget->hasAVX2())
15746       return 0;
15747   case MVT::v16i8:
15748   case MVT::v8i16:
15749   case MVT::v4i32:
15750     if (!Subtarget->hasSSE2())
15751       return 0;
15752   }
15753
15754   // SSE2 has only a small subset of the operations.
15755   bool hasUnsigned = Subtarget->hasSSE41() ||
15756                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15757   bool hasSigned = Subtarget->hasSSE41() ||
15758                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15759
15760   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15761
15762   // Check for x CC y ? x : y.
15763   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15764       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15765     switch (CC) {
15766     default: break;
15767     case ISD::SETULT:
15768     case ISD::SETULE:
15769       return hasUnsigned ? X86ISD::UMIN : 0;
15770     case ISD::SETUGT:
15771     case ISD::SETUGE:
15772       return hasUnsigned ? X86ISD::UMAX : 0;
15773     case ISD::SETLT:
15774     case ISD::SETLE:
15775       return hasSigned ? X86ISD::SMIN : 0;
15776     case ISD::SETGT:
15777     case ISD::SETGE:
15778       return hasSigned ? X86ISD::SMAX : 0;
15779     }
15780   // Check for x CC y ? y : x -- a min/max with reversed arms.
15781   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15782              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15783     switch (CC) {
15784     default: break;
15785     case ISD::SETULT:
15786     case ISD::SETULE:
15787       return hasUnsigned ? X86ISD::UMAX : 0;
15788     case ISD::SETUGT:
15789     case ISD::SETUGE:
15790       return hasUnsigned ? X86ISD::UMIN : 0;
15791     case ISD::SETLT:
15792     case ISD::SETLE:
15793       return hasSigned ? X86ISD::SMAX : 0;
15794     case ISD::SETGT:
15795     case ISD::SETGE:
15796       return hasSigned ? X86ISD::SMIN : 0;
15797     }
15798   }
15799
15800   return 0;
15801 }
15802
15803 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15804 /// nodes.
15805 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15806                                     TargetLowering::DAGCombinerInfo &DCI,
15807                                     const X86Subtarget *Subtarget) {
15808   SDLoc DL(N);
15809   SDValue Cond = N->getOperand(0);
15810   // Get the LHS/RHS of the select.
15811   SDValue LHS = N->getOperand(1);
15812   SDValue RHS = N->getOperand(2);
15813   EVT VT = LHS.getValueType();
15814
15815   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15816   // instructions match the semantics of the common C idiom x<y?x:y but not
15817   // x<=y?x:y, because of how they handle negative zero (which can be
15818   // ignored in unsafe-math mode).
15819   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15820       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15821       (Subtarget->hasSSE2() ||
15822        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15823     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15824
15825     unsigned Opcode = 0;
15826     // Check for x CC y ? x : y.
15827     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15828         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15829       switch (CC) {
15830       default: break;
15831       case ISD::SETULT:
15832         // Converting this to a min would handle NaNs incorrectly, and swapping
15833         // the operands would cause it to handle comparisons between positive
15834         // and negative zero incorrectly.
15835         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15836           if (!DAG.getTarget().Options.UnsafeFPMath &&
15837               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15838             break;
15839           std::swap(LHS, RHS);
15840         }
15841         Opcode = X86ISD::FMIN;
15842         break;
15843       case ISD::SETOLE:
15844         // Converting this to a min would handle comparisons between positive
15845         // and negative zero incorrectly.
15846         if (!DAG.getTarget().Options.UnsafeFPMath &&
15847             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15848           break;
15849         Opcode = X86ISD::FMIN;
15850         break;
15851       case ISD::SETULE:
15852         // Converting this to a min would handle both negative zeros and NaNs
15853         // incorrectly, but we can swap the operands to fix both.
15854         std::swap(LHS, RHS);
15855       case ISD::SETOLT:
15856       case ISD::SETLT:
15857       case ISD::SETLE:
15858         Opcode = X86ISD::FMIN;
15859         break;
15860
15861       case ISD::SETOGE:
15862         // Converting this to a max would handle comparisons between positive
15863         // and negative zero incorrectly.
15864         if (!DAG.getTarget().Options.UnsafeFPMath &&
15865             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15866           break;
15867         Opcode = X86ISD::FMAX;
15868         break;
15869       case ISD::SETUGT:
15870         // Converting this to a max would handle NaNs incorrectly, and swapping
15871         // the operands would cause it to handle comparisons between positive
15872         // and negative zero incorrectly.
15873         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15874           if (!DAG.getTarget().Options.UnsafeFPMath &&
15875               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15876             break;
15877           std::swap(LHS, RHS);
15878         }
15879         Opcode = X86ISD::FMAX;
15880         break;
15881       case ISD::SETUGE:
15882         // Converting this to a max would handle both negative zeros and NaNs
15883         // incorrectly, but we can swap the operands to fix both.
15884         std::swap(LHS, RHS);
15885       case ISD::SETOGT:
15886       case ISD::SETGT:
15887       case ISD::SETGE:
15888         Opcode = X86ISD::FMAX;
15889         break;
15890       }
15891     // Check for x CC y ? y : x -- a min/max with reversed arms.
15892     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15893                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15894       switch (CC) {
15895       default: break;
15896       case ISD::SETOGE:
15897         // Converting this to a min would handle comparisons between positive
15898         // and negative zero incorrectly, and swapping the operands would
15899         // cause it to handle NaNs incorrectly.
15900         if (!DAG.getTarget().Options.UnsafeFPMath &&
15901             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15902           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15903             break;
15904           std::swap(LHS, RHS);
15905         }
15906         Opcode = X86ISD::FMIN;
15907         break;
15908       case ISD::SETUGT:
15909         // Converting this to a min would handle NaNs incorrectly.
15910         if (!DAG.getTarget().Options.UnsafeFPMath &&
15911             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15912           break;
15913         Opcode = X86ISD::FMIN;
15914         break;
15915       case ISD::SETUGE:
15916         // Converting this to a min would handle both negative zeros and NaNs
15917         // incorrectly, but we can swap the operands to fix both.
15918         std::swap(LHS, RHS);
15919       case ISD::SETOGT:
15920       case ISD::SETGT:
15921       case ISD::SETGE:
15922         Opcode = X86ISD::FMIN;
15923         break;
15924
15925       case ISD::SETULT:
15926         // Converting this to a max would handle NaNs incorrectly.
15927         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15928           break;
15929         Opcode = X86ISD::FMAX;
15930         break;
15931       case ISD::SETOLE:
15932         // Converting this to a max would handle comparisons between positive
15933         // and negative zero incorrectly, and swapping the operands would
15934         // cause it to handle NaNs incorrectly.
15935         if (!DAG.getTarget().Options.UnsafeFPMath &&
15936             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15937           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15938             break;
15939           std::swap(LHS, RHS);
15940         }
15941         Opcode = X86ISD::FMAX;
15942         break;
15943       case ISD::SETULE:
15944         // Converting this to a max would handle both negative zeros and NaNs
15945         // incorrectly, but we can swap the operands to fix both.
15946         std::swap(LHS, RHS);
15947       case ISD::SETOLT:
15948       case ISD::SETLT:
15949       case ISD::SETLE:
15950         Opcode = X86ISD::FMAX;
15951         break;
15952       }
15953     }
15954
15955     if (Opcode)
15956       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15957   }
15958
15959   // If this is a select between two integer constants, try to do some
15960   // optimizations.
15961   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15962     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15963       // Don't do this for crazy integer types.
15964       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15965         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15966         // so that TrueC (the true value) is larger than FalseC.
15967         bool NeedsCondInvert = false;
15968
15969         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15970             // Efficiently invertible.
15971             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15972              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15973               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15974           NeedsCondInvert = true;
15975           std::swap(TrueC, FalseC);
15976         }
15977
15978         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15979         if (FalseC->getAPIntValue() == 0 &&
15980             TrueC->getAPIntValue().isPowerOf2()) {
15981           if (NeedsCondInvert) // Invert the condition if needed.
15982             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15983                                DAG.getConstant(1, Cond.getValueType()));
15984
15985           // Zero extend the condition if needed.
15986           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15987
15988           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15989           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15990                              DAG.getConstant(ShAmt, MVT::i8));
15991         }
15992
15993         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15994         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15995           if (NeedsCondInvert) // Invert the condition if needed.
15996             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15997                                DAG.getConstant(1, Cond.getValueType()));
15998
15999           // Zero extend the condition if needed.
16000           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16001                              FalseC->getValueType(0), Cond);
16002           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16003                              SDValue(FalseC, 0));
16004         }
16005
16006         // Optimize cases that will turn into an LEA instruction.  This requires
16007         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16008         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16009           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16010           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16011
16012           bool isFastMultiplier = false;
16013           if (Diff < 10) {
16014             switch ((unsigned char)Diff) {
16015               default: break;
16016               case 1:  // result = add base, cond
16017               case 2:  // result = lea base(    , cond*2)
16018               case 3:  // result = lea base(cond, cond*2)
16019               case 4:  // result = lea base(    , cond*4)
16020               case 5:  // result = lea base(cond, cond*4)
16021               case 8:  // result = lea base(    , cond*8)
16022               case 9:  // result = lea base(cond, cond*8)
16023                 isFastMultiplier = true;
16024                 break;
16025             }
16026           }
16027
16028           if (isFastMultiplier) {
16029             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16030             if (NeedsCondInvert) // Invert the condition if needed.
16031               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16032                                  DAG.getConstant(1, Cond.getValueType()));
16033
16034             // Zero extend the condition if needed.
16035             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16036                                Cond);
16037             // Scale the condition by the difference.
16038             if (Diff != 1)
16039               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16040                                  DAG.getConstant(Diff, Cond.getValueType()));
16041
16042             // Add the base if non-zero.
16043             if (FalseC->getAPIntValue() != 0)
16044               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16045                                  SDValue(FalseC, 0));
16046             return Cond;
16047           }
16048         }
16049       }
16050   }
16051
16052   // Canonicalize max and min:
16053   // (x > y) ? x : y -> (x >= y) ? x : y
16054   // (x < y) ? x : y -> (x <= y) ? x : y
16055   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16056   // the need for an extra compare
16057   // against zero. e.g.
16058   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16059   // subl   %esi, %edi
16060   // testl  %edi, %edi
16061   // movl   $0, %eax
16062   // cmovgl %edi, %eax
16063   // =>
16064   // xorl   %eax, %eax
16065   // subl   %esi, $edi
16066   // cmovsl %eax, %edi
16067   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16068       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16069       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16070     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16071     switch (CC) {
16072     default: break;
16073     case ISD::SETLT:
16074     case ISD::SETGT: {
16075       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16076       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16077                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
16078       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16079     }
16080     }
16081   }
16082
16083   // Match VSELECTs into subs with unsigned saturation.
16084   if (!DCI.isBeforeLegalize() &&
16085       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16086       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16087       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16088        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16089     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16090
16091     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16092     // left side invert the predicate to simplify logic below.
16093     SDValue Other;
16094     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16095       Other = RHS;
16096       CC = ISD::getSetCCInverse(CC, true);
16097     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16098       Other = LHS;
16099     }
16100
16101     if (Other.getNode() && Other->getNumOperands() == 2 &&
16102         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16103       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16104       SDValue CondRHS = Cond->getOperand(1);
16105
16106       // Look for a general sub with unsigned saturation first.
16107       // x >= y ? x-y : 0 --> subus x, y
16108       // x >  y ? x-y : 0 --> subus x, y
16109       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16110           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16111         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16112
16113       // If the RHS is a constant we have to reverse the const canonicalization.
16114       // x > C-1 ? x+-C : 0 --> subus x, C
16115       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16116           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16117         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16118         if (CondRHS.getConstantOperandVal(0) == -A-1)
16119           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16120                              DAG.getConstant(-A, VT));
16121       }
16122
16123       // Another special case: If C was a sign bit, the sub has been
16124       // canonicalized into a xor.
16125       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16126       //        it's safe to decanonicalize the xor?
16127       // x s< 0 ? x^C : 0 --> subus x, C
16128       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16129           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16130           isSplatVector(OpRHS.getNode())) {
16131         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16132         if (A.isSignBit())
16133           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16134       }
16135     }
16136   }
16137
16138   // Try to match a min/max vector operation.
16139   if (!DCI.isBeforeLegalize() &&
16140       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
16141     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
16142       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
16143
16144   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16145   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
16146       Cond.getOpcode() == ISD::SETCC) {
16147
16148     assert(Cond.getValueType().isVector() &&
16149            "vector select expects a vector selector!");
16150
16151     EVT IntVT = Cond.getValueType();
16152     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
16153     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
16154
16155     if (!TValIsAllOnes && !FValIsAllZeros) {
16156       // Try invert the condition if true value is not all 1s and false value
16157       // is not all 0s.
16158       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
16159       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
16160
16161       if (TValIsAllZeros || FValIsAllOnes) {
16162         SDValue CC = Cond.getOperand(2);
16163         ISD::CondCode NewCC =
16164           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
16165                                Cond.getOperand(0).getValueType().isInteger());
16166         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
16167         std::swap(LHS, RHS);
16168         TValIsAllOnes = FValIsAllOnes;
16169         FValIsAllZeros = TValIsAllZeros;
16170       }
16171     }
16172
16173     if (TValIsAllOnes || FValIsAllZeros) {
16174       SDValue Ret;
16175
16176       if (TValIsAllOnes && FValIsAllZeros)
16177         Ret = Cond;
16178       else if (TValIsAllOnes)
16179         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
16180                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
16181       else if (FValIsAllZeros)
16182         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
16183                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
16184
16185       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
16186     }
16187   }
16188
16189   // If we know that this node is legal then we know that it is going to be
16190   // matched by one of the SSE/AVX BLEND instructions. These instructions only
16191   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
16192   // to simplify previous instructions.
16193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16194   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
16195       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
16196     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
16197
16198     // Don't optimize vector selects that map to mask-registers.
16199     if (BitWidth == 1)
16200       return SDValue();
16201
16202     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
16203     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
16204
16205     APInt KnownZero, KnownOne;
16206     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
16207                                           DCI.isBeforeLegalizeOps());
16208     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
16209         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
16210       DCI.CommitTargetLoweringOpt(TLO);
16211   }
16212
16213   return SDValue();
16214 }
16215
16216 // Check whether a boolean test is testing a boolean value generated by
16217 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
16218 // code.
16219 //
16220 // Simplify the following patterns:
16221 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
16222 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
16223 // to (Op EFLAGS Cond)
16224 //
16225 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
16226 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
16227 // to (Op EFLAGS !Cond)
16228 //
16229 // where Op could be BRCOND or CMOV.
16230 //
16231 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
16232   // Quit if not CMP and SUB with its value result used.
16233   if (Cmp.getOpcode() != X86ISD::CMP &&
16234       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
16235       return SDValue();
16236
16237   // Quit if not used as a boolean value.
16238   if (CC != X86::COND_E && CC != X86::COND_NE)
16239     return SDValue();
16240
16241   // Check CMP operands. One of them should be 0 or 1 and the other should be
16242   // an SetCC or extended from it.
16243   SDValue Op1 = Cmp.getOperand(0);
16244   SDValue Op2 = Cmp.getOperand(1);
16245
16246   SDValue SetCC;
16247   const ConstantSDNode* C = 0;
16248   bool needOppositeCond = (CC == X86::COND_E);
16249   bool checkAgainstTrue = false; // Is it a comparison against 1?
16250
16251   if ((C = dyn_cast<ConstantSDNode>(Op1)))
16252     SetCC = Op2;
16253   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
16254     SetCC = Op1;
16255   else // Quit if all operands are not constants.
16256     return SDValue();
16257
16258   if (C->getZExtValue() == 1) {
16259     needOppositeCond = !needOppositeCond;
16260     checkAgainstTrue = true;
16261   } else if (C->getZExtValue() != 0)
16262     // Quit if the constant is neither 0 or 1.
16263     return SDValue();
16264
16265   bool truncatedToBoolWithAnd = false;
16266   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
16267   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
16268          SetCC.getOpcode() == ISD::TRUNCATE ||
16269          SetCC.getOpcode() == ISD::AND) {
16270     if (SetCC.getOpcode() == ISD::AND) {
16271       int OpIdx = -1;
16272       ConstantSDNode *CS;
16273       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
16274           CS->getZExtValue() == 1)
16275         OpIdx = 1;
16276       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
16277           CS->getZExtValue() == 1)
16278         OpIdx = 0;
16279       if (OpIdx == -1)
16280         break;
16281       SetCC = SetCC.getOperand(OpIdx);
16282       truncatedToBoolWithAnd = true;
16283     } else
16284       SetCC = SetCC.getOperand(0);
16285   }
16286
16287   switch (SetCC.getOpcode()) {
16288   case X86ISD::SETCC_CARRY:
16289     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
16290     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
16291     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
16292     // truncated to i1 using 'and'.
16293     if (checkAgainstTrue && !truncatedToBoolWithAnd)
16294       break;
16295     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
16296            "Invalid use of SETCC_CARRY!");
16297     // FALL THROUGH
16298   case X86ISD::SETCC:
16299     // Set the condition code or opposite one if necessary.
16300     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
16301     if (needOppositeCond)
16302       CC = X86::GetOppositeBranchCondition(CC);
16303     return SetCC.getOperand(1);
16304   case X86ISD::CMOV: {
16305     // Check whether false/true value has canonical one, i.e. 0 or 1.
16306     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16307     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16308     // Quit if true value is not a constant.
16309     if (!TVal)
16310       return SDValue();
16311     // Quit if false value is not a constant.
16312     if (!FVal) {
16313       SDValue Op = SetCC.getOperand(0);
16314       // Skip 'zext' or 'trunc' node.
16315       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16316           Op.getOpcode() == ISD::TRUNCATE)
16317         Op = Op.getOperand(0);
16318       // A special case for rdrand/rdseed, where 0 is set if false cond is
16319       // found.
16320       if ((Op.getOpcode() != X86ISD::RDRAND &&
16321            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16322         return SDValue();
16323     }
16324     // Quit if false value is not the constant 0 or 1.
16325     bool FValIsFalse = true;
16326     if (FVal && FVal->getZExtValue() != 0) {
16327       if (FVal->getZExtValue() != 1)
16328         return SDValue();
16329       // If FVal is 1, opposite cond is needed.
16330       needOppositeCond = !needOppositeCond;
16331       FValIsFalse = false;
16332     }
16333     // Quit if TVal is not the constant opposite of FVal.
16334     if (FValIsFalse && TVal->getZExtValue() != 1)
16335       return SDValue();
16336     if (!FValIsFalse && TVal->getZExtValue() != 0)
16337       return SDValue();
16338     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16339     if (needOppositeCond)
16340       CC = X86::GetOppositeBranchCondition(CC);
16341     return SetCC.getOperand(3);
16342   }
16343   }
16344
16345   return SDValue();
16346 }
16347
16348 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16349 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16350                                   TargetLowering::DAGCombinerInfo &DCI,
16351                                   const X86Subtarget *Subtarget) {
16352   SDLoc DL(N);
16353
16354   // If the flag operand isn't dead, don't touch this CMOV.
16355   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16356     return SDValue();
16357
16358   SDValue FalseOp = N->getOperand(0);
16359   SDValue TrueOp = N->getOperand(1);
16360   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16361   SDValue Cond = N->getOperand(3);
16362
16363   if (CC == X86::COND_E || CC == X86::COND_NE) {
16364     switch (Cond.getOpcode()) {
16365     default: break;
16366     case X86ISD::BSR:
16367     case X86ISD::BSF:
16368       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16369       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16370         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16371     }
16372   }
16373
16374   SDValue Flags;
16375
16376   Flags = checkBoolTestSetCCCombine(Cond, CC);
16377   if (Flags.getNode() &&
16378       // Extra check as FCMOV only supports a subset of X86 cond.
16379       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16380     SDValue Ops[] = { FalseOp, TrueOp,
16381                       DAG.getConstant(CC, MVT::i8), Flags };
16382     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16383                        Ops, array_lengthof(Ops));
16384   }
16385
16386   // If this is a select between two integer constants, try to do some
16387   // optimizations.  Note that the operands are ordered the opposite of SELECT
16388   // operands.
16389   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16390     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16391       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16392       // larger than FalseC (the false value).
16393       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16394         CC = X86::GetOppositeBranchCondition(CC);
16395         std::swap(TrueC, FalseC);
16396         std::swap(TrueOp, FalseOp);
16397       }
16398
16399       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16400       // This is efficient for any integer data type (including i8/i16) and
16401       // shift amount.
16402       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16403         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16404                            DAG.getConstant(CC, MVT::i8), Cond);
16405
16406         // Zero extend the condition if needed.
16407         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16408
16409         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16410         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16411                            DAG.getConstant(ShAmt, MVT::i8));
16412         if (N->getNumValues() == 2)  // Dead flag value?
16413           return DCI.CombineTo(N, Cond, SDValue());
16414         return Cond;
16415       }
16416
16417       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16418       // for any integer data type, including i8/i16.
16419       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16420         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16421                            DAG.getConstant(CC, MVT::i8), Cond);
16422
16423         // Zero extend the condition if needed.
16424         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16425                            FalseC->getValueType(0), Cond);
16426         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16427                            SDValue(FalseC, 0));
16428
16429         if (N->getNumValues() == 2)  // Dead flag value?
16430           return DCI.CombineTo(N, Cond, SDValue());
16431         return Cond;
16432       }
16433
16434       // Optimize cases that will turn into an LEA instruction.  This requires
16435       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16436       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16437         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16438         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16439
16440         bool isFastMultiplier = false;
16441         if (Diff < 10) {
16442           switch ((unsigned char)Diff) {
16443           default: break;
16444           case 1:  // result = add base, cond
16445           case 2:  // result = lea base(    , cond*2)
16446           case 3:  // result = lea base(cond, cond*2)
16447           case 4:  // result = lea base(    , cond*4)
16448           case 5:  // result = lea base(cond, cond*4)
16449           case 8:  // result = lea base(    , cond*8)
16450           case 9:  // result = lea base(cond, cond*8)
16451             isFastMultiplier = true;
16452             break;
16453           }
16454         }
16455
16456         if (isFastMultiplier) {
16457           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16458           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16459                              DAG.getConstant(CC, MVT::i8), Cond);
16460           // Zero extend the condition if needed.
16461           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16462                              Cond);
16463           // Scale the condition by the difference.
16464           if (Diff != 1)
16465             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16466                                DAG.getConstant(Diff, Cond.getValueType()));
16467
16468           // Add the base if non-zero.
16469           if (FalseC->getAPIntValue() != 0)
16470             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16471                                SDValue(FalseC, 0));
16472           if (N->getNumValues() == 2)  // Dead flag value?
16473             return DCI.CombineTo(N, Cond, SDValue());
16474           return Cond;
16475         }
16476       }
16477     }
16478   }
16479
16480   // Handle these cases:
16481   //   (select (x != c), e, c) -> select (x != c), e, x),
16482   //   (select (x == c), c, e) -> select (x == c), x, e)
16483   // where the c is an integer constant, and the "select" is the combination
16484   // of CMOV and CMP.
16485   //
16486   // The rationale for this change is that the conditional-move from a constant
16487   // needs two instructions, however, conditional-move from a register needs
16488   // only one instruction.
16489   //
16490   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16491   //  some instruction-combining opportunities. This opt needs to be
16492   //  postponed as late as possible.
16493   //
16494   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16495     // the DCI.xxxx conditions are provided to postpone the optimization as
16496     // late as possible.
16497
16498     ConstantSDNode *CmpAgainst = 0;
16499     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16500         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16501         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16502
16503       if (CC == X86::COND_NE &&
16504           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16505         CC = X86::GetOppositeBranchCondition(CC);
16506         std::swap(TrueOp, FalseOp);
16507       }
16508
16509       if (CC == X86::COND_E &&
16510           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16511         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16512                           DAG.getConstant(CC, MVT::i8), Cond };
16513         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16514                            array_lengthof(Ops));
16515       }
16516     }
16517   }
16518
16519   return SDValue();
16520 }
16521
16522 /// PerformMulCombine - Optimize a single multiply with constant into two
16523 /// in order to implement it with two cheaper instructions, e.g.
16524 /// LEA + SHL, LEA + LEA.
16525 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16526                                  TargetLowering::DAGCombinerInfo &DCI) {
16527   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16528     return SDValue();
16529
16530   EVT VT = N->getValueType(0);
16531   if (VT != MVT::i64)
16532     return SDValue();
16533
16534   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16535   if (!C)
16536     return SDValue();
16537   uint64_t MulAmt = C->getZExtValue();
16538   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16539     return SDValue();
16540
16541   uint64_t MulAmt1 = 0;
16542   uint64_t MulAmt2 = 0;
16543   if ((MulAmt % 9) == 0) {
16544     MulAmt1 = 9;
16545     MulAmt2 = MulAmt / 9;
16546   } else if ((MulAmt % 5) == 0) {
16547     MulAmt1 = 5;
16548     MulAmt2 = MulAmt / 5;
16549   } else if ((MulAmt % 3) == 0) {
16550     MulAmt1 = 3;
16551     MulAmt2 = MulAmt / 3;
16552   }
16553   if (MulAmt2 &&
16554       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16555     SDLoc DL(N);
16556
16557     if (isPowerOf2_64(MulAmt2) &&
16558         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16559       // If second multiplifer is pow2, issue it first. We want the multiply by
16560       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16561       // is an add.
16562       std::swap(MulAmt1, MulAmt2);
16563
16564     SDValue NewMul;
16565     if (isPowerOf2_64(MulAmt1))
16566       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16567                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16568     else
16569       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16570                            DAG.getConstant(MulAmt1, VT));
16571
16572     if (isPowerOf2_64(MulAmt2))
16573       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16574                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16575     else
16576       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16577                            DAG.getConstant(MulAmt2, VT));
16578
16579     // Do not add new nodes to DAG combiner worklist.
16580     DCI.CombineTo(N, NewMul, false);
16581   }
16582   return SDValue();
16583 }
16584
16585 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16586   SDValue N0 = N->getOperand(0);
16587   SDValue N1 = N->getOperand(1);
16588   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16589   EVT VT = N0.getValueType();
16590
16591   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16592   // since the result of setcc_c is all zero's or all ones.
16593   if (VT.isInteger() && !VT.isVector() &&
16594       N1C && N0.getOpcode() == ISD::AND &&
16595       N0.getOperand(1).getOpcode() == ISD::Constant) {
16596     SDValue N00 = N0.getOperand(0);
16597     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16598         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16599           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16600          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16601       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16602       APInt ShAmt = N1C->getAPIntValue();
16603       Mask = Mask.shl(ShAmt);
16604       if (Mask != 0)
16605         return DAG.getNode(ISD::AND, SDLoc(N), VT,
16606                            N00, DAG.getConstant(Mask, VT));
16607     }
16608   }
16609
16610   // Hardware support for vector shifts is sparse which makes us scalarize the
16611   // vector operations in many cases. Also, on sandybridge ADD is faster than
16612   // shl.
16613   // (shl V, 1) -> add V,V
16614   if (isSplatVector(N1.getNode())) {
16615     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16616     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16617     // We shift all of the values by one. In many cases we do not have
16618     // hardware support for this operation. This is better expressed as an ADD
16619     // of two values.
16620     if (N1C && (1 == N1C->getZExtValue())) {
16621       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16622     }
16623   }
16624
16625   return SDValue();
16626 }
16627
16628 /// \brief Returns a vector of 0s if the node in input is a vector logical
16629 /// shift by a constant amount which is known to be bigger than or equal 
16630 /// to the vector element size in bits.
16631 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
16632                                       const X86Subtarget *Subtarget) {
16633   EVT VT = N->getValueType(0);
16634
16635   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
16636       (!Subtarget->hasInt256() ||
16637        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
16638     return SDValue();
16639
16640   SDValue Amt = N->getOperand(1);
16641   SDLoc DL(N);
16642   if (isSplatVector(Amt.getNode())) {
16643     SDValue SclrAmt = Amt->getOperand(0);
16644     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
16645       APInt ShiftAmt = C->getAPIntValue();
16646       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
16647
16648       // SSE2/AVX2 logical shifts always return a vector of 0s
16649       // if the shift amount is bigger than or equal to 
16650       // the element size. The constant shift amount will be
16651       // encoded as a 8-bit immediate.
16652       if (ShiftAmt.trunc(8).uge(MaxAmount))
16653         return getZeroVector(VT, Subtarget, DAG, DL);
16654     }
16655   }
16656
16657   return SDValue();
16658 }
16659
16660 /// PerformShiftCombine - Combine shifts.
16661 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16662                                    TargetLowering::DAGCombinerInfo &DCI,
16663                                    const X86Subtarget *Subtarget) {
16664   if (N->getOpcode() == ISD::SHL) {
16665     SDValue V = PerformSHLCombine(N, DAG);
16666     if (V.getNode()) return V;
16667   }
16668
16669   if (N->getOpcode() != ISD::SRA) {
16670     // Try to fold this logical shift into a zero vector.
16671     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
16672     if (V.getNode()) return V;
16673   }
16674
16675   return SDValue();
16676 }
16677
16678 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16679 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16680 // and friends.  Likewise for OR -> CMPNEQSS.
16681 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16682                             TargetLowering::DAGCombinerInfo &DCI,
16683                             const X86Subtarget *Subtarget) {
16684   unsigned opcode;
16685
16686   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16687   // we're requiring SSE2 for both.
16688   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16689     SDValue N0 = N->getOperand(0);
16690     SDValue N1 = N->getOperand(1);
16691     SDValue CMP0 = N0->getOperand(1);
16692     SDValue CMP1 = N1->getOperand(1);
16693     SDLoc DL(N);
16694
16695     // The SETCCs should both refer to the same CMP.
16696     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16697       return SDValue();
16698
16699     SDValue CMP00 = CMP0->getOperand(0);
16700     SDValue CMP01 = CMP0->getOperand(1);
16701     EVT     VT    = CMP00.getValueType();
16702
16703     if (VT == MVT::f32 || VT == MVT::f64) {
16704       bool ExpectingFlags = false;
16705       // Check for any users that want flags:
16706       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16707            !ExpectingFlags && UI != UE; ++UI)
16708         switch (UI->getOpcode()) {
16709         default:
16710         case ISD::BR_CC:
16711         case ISD::BRCOND:
16712         case ISD::SELECT:
16713           ExpectingFlags = true;
16714           break;
16715         case ISD::CopyToReg:
16716         case ISD::SIGN_EXTEND:
16717         case ISD::ZERO_EXTEND:
16718         case ISD::ANY_EXTEND:
16719           break;
16720         }
16721
16722       if (!ExpectingFlags) {
16723         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16724         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16725
16726         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16727           X86::CondCode tmp = cc0;
16728           cc0 = cc1;
16729           cc1 = tmp;
16730         }
16731
16732         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16733             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16734           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16735           X86ISD::NodeType NTOperator = is64BitFP ?
16736             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16737           // FIXME: need symbolic constants for these magic numbers.
16738           // See X86ATTInstPrinter.cpp:printSSECC().
16739           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16740           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16741                                               DAG.getConstant(x86cc, MVT::i8));
16742           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16743                                               OnesOrZeroesF);
16744           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16745                                       DAG.getConstant(1, MVT::i32));
16746           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16747           return OneBitOfTruth;
16748         }
16749       }
16750     }
16751   }
16752   return SDValue();
16753 }
16754
16755 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16756 /// so it can be folded inside ANDNP.
16757 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16758   EVT VT = N->getValueType(0);
16759
16760   // Match direct AllOnes for 128 and 256-bit vectors
16761   if (ISD::isBuildVectorAllOnes(N))
16762     return true;
16763
16764   // Look through a bit convert.
16765   if (N->getOpcode() == ISD::BITCAST)
16766     N = N->getOperand(0).getNode();
16767
16768   // Sometimes the operand may come from a insert_subvector building a 256-bit
16769   // allones vector
16770   if (VT.is256BitVector() &&
16771       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16772     SDValue V1 = N->getOperand(0);
16773     SDValue V2 = N->getOperand(1);
16774
16775     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16776         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16777         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16778         ISD::isBuildVectorAllOnes(V2.getNode()))
16779       return true;
16780   }
16781
16782   return false;
16783 }
16784
16785 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16786 // register. In most cases we actually compare or select YMM-sized registers
16787 // and mixing the two types creates horrible code. This method optimizes
16788 // some of the transition sequences.
16789 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16790                                  TargetLowering::DAGCombinerInfo &DCI,
16791                                  const X86Subtarget *Subtarget) {
16792   EVT VT = N->getValueType(0);
16793   if (!VT.is256BitVector())
16794     return SDValue();
16795
16796   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16797           N->getOpcode() == ISD::ZERO_EXTEND ||
16798           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16799
16800   SDValue Narrow = N->getOperand(0);
16801   EVT NarrowVT = Narrow->getValueType(0);
16802   if (!NarrowVT.is128BitVector())
16803     return SDValue();
16804
16805   if (Narrow->getOpcode() != ISD::XOR &&
16806       Narrow->getOpcode() != ISD::AND &&
16807       Narrow->getOpcode() != ISD::OR)
16808     return SDValue();
16809
16810   SDValue N0  = Narrow->getOperand(0);
16811   SDValue N1  = Narrow->getOperand(1);
16812   SDLoc DL(Narrow);
16813
16814   // The Left side has to be a trunc.
16815   if (N0.getOpcode() != ISD::TRUNCATE)
16816     return SDValue();
16817
16818   // The type of the truncated inputs.
16819   EVT WideVT = N0->getOperand(0)->getValueType(0);
16820   if (WideVT != VT)
16821     return SDValue();
16822
16823   // The right side has to be a 'trunc' or a constant vector.
16824   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16825   bool RHSConst = (isSplatVector(N1.getNode()) &&
16826                    isa<ConstantSDNode>(N1->getOperand(0)));
16827   if (!RHSTrunc && !RHSConst)
16828     return SDValue();
16829
16830   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16831
16832   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16833     return SDValue();
16834
16835   // Set N0 and N1 to hold the inputs to the new wide operation.
16836   N0 = N0->getOperand(0);
16837   if (RHSConst) {
16838     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16839                      N1->getOperand(0));
16840     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16841     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16842   } else if (RHSTrunc) {
16843     N1 = N1->getOperand(0);
16844   }
16845
16846   // Generate the wide operation.
16847   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16848   unsigned Opcode = N->getOpcode();
16849   switch (Opcode) {
16850   case ISD::ANY_EXTEND:
16851     return Op;
16852   case ISD::ZERO_EXTEND: {
16853     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16854     APInt Mask = APInt::getAllOnesValue(InBits);
16855     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16856     return DAG.getNode(ISD::AND, DL, VT,
16857                        Op, DAG.getConstant(Mask, VT));
16858   }
16859   case ISD::SIGN_EXTEND:
16860     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16861                        Op, DAG.getValueType(NarrowVT));
16862   default:
16863     llvm_unreachable("Unexpected opcode");
16864   }
16865 }
16866
16867 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16868                                  TargetLowering::DAGCombinerInfo &DCI,
16869                                  const X86Subtarget *Subtarget) {
16870   EVT VT = N->getValueType(0);
16871   if (DCI.isBeforeLegalizeOps())
16872     return SDValue();
16873
16874   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16875   if (R.getNode())
16876     return R;
16877
16878   // Create BLSI, and BLSR instructions
16879   // BLSI is X & (-X)
16880   // BLSR is X & (X-1)
16881   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16882     SDValue N0 = N->getOperand(0);
16883     SDValue N1 = N->getOperand(1);
16884     SDLoc DL(N);
16885
16886     // Check LHS for neg
16887     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16888         isZero(N0.getOperand(0)))
16889       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16890
16891     // Check RHS for neg
16892     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16893         isZero(N1.getOperand(0)))
16894       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16895
16896     // Check LHS for X-1
16897     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16898         isAllOnes(N0.getOperand(1)))
16899       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16900
16901     // Check RHS for X-1
16902     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16903         isAllOnes(N1.getOperand(1)))
16904       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16905
16906     return SDValue();
16907   }
16908
16909   // Want to form ANDNP nodes:
16910   // 1) In the hopes of then easily combining them with OR and AND nodes
16911   //    to form PBLEND/PSIGN.
16912   // 2) To match ANDN packed intrinsics
16913   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16914     return SDValue();
16915
16916   SDValue N0 = N->getOperand(0);
16917   SDValue N1 = N->getOperand(1);
16918   SDLoc DL(N);
16919
16920   // Check LHS for vnot
16921   if (N0.getOpcode() == ISD::XOR &&
16922       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16923       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16924     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16925
16926   // Check RHS for vnot
16927   if (N1.getOpcode() == ISD::XOR &&
16928       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16929       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16930     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16931
16932   return SDValue();
16933 }
16934
16935 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16936                                 TargetLowering::DAGCombinerInfo &DCI,
16937                                 const X86Subtarget *Subtarget) {
16938   EVT VT = N->getValueType(0);
16939   if (DCI.isBeforeLegalizeOps())
16940     return SDValue();
16941
16942   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16943   if (R.getNode())
16944     return R;
16945
16946   SDValue N0 = N->getOperand(0);
16947   SDValue N1 = N->getOperand(1);
16948
16949   // look for psign/blend
16950   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16951     if (!Subtarget->hasSSSE3() ||
16952         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16953       return SDValue();
16954
16955     // Canonicalize pandn to RHS
16956     if (N0.getOpcode() == X86ISD::ANDNP)
16957       std::swap(N0, N1);
16958     // or (and (m, y), (pandn m, x))
16959     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16960       SDValue Mask = N1.getOperand(0);
16961       SDValue X    = N1.getOperand(1);
16962       SDValue Y;
16963       if (N0.getOperand(0) == Mask)
16964         Y = N0.getOperand(1);
16965       if (N0.getOperand(1) == Mask)
16966         Y = N0.getOperand(0);
16967
16968       // Check to see if the mask appeared in both the AND and ANDNP and
16969       if (!Y.getNode())
16970         return SDValue();
16971
16972       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16973       // Look through mask bitcast.
16974       if (Mask.getOpcode() == ISD::BITCAST)
16975         Mask = Mask.getOperand(0);
16976       if (X.getOpcode() == ISD::BITCAST)
16977         X = X.getOperand(0);
16978       if (Y.getOpcode() == ISD::BITCAST)
16979         Y = Y.getOperand(0);
16980
16981       EVT MaskVT = Mask.getValueType();
16982
16983       // Validate that the Mask operand is a vector sra node.
16984       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16985       // there is no psrai.b
16986       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16987       unsigned SraAmt = ~0;
16988       if (Mask.getOpcode() == ISD::SRA) {
16989         SDValue Amt = Mask.getOperand(1);
16990         if (isSplatVector(Amt.getNode())) {
16991           SDValue SclrAmt = Amt->getOperand(0);
16992           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16993             SraAmt = C->getZExtValue();
16994         }
16995       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16996         SDValue SraC = Mask.getOperand(1);
16997         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16998       }
16999       if ((SraAmt + 1) != EltBits)
17000         return SDValue();
17001
17002       SDLoc DL(N);
17003
17004       // Now we know we at least have a plendvb with the mask val.  See if
17005       // we can form a psignb/w/d.
17006       // psign = x.type == y.type == mask.type && y = sub(0, x);
17007       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17008           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17009           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17010         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17011                "Unsupported VT for PSIGN");
17012         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17013         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17014       }
17015       // PBLENDVB only available on SSE 4.1
17016       if (!Subtarget->hasSSE41())
17017         return SDValue();
17018
17019       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
17020
17021       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
17022       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
17023       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
17024       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
17025       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17026     }
17027   }
17028
17029   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
17030     return SDValue();
17031
17032   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
17033   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
17034     std::swap(N0, N1);
17035   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
17036     return SDValue();
17037   if (!N0.hasOneUse() || !N1.hasOneUse())
17038     return SDValue();
17039
17040   SDValue ShAmt0 = N0.getOperand(1);
17041   if (ShAmt0.getValueType() != MVT::i8)
17042     return SDValue();
17043   SDValue ShAmt1 = N1.getOperand(1);
17044   if (ShAmt1.getValueType() != MVT::i8)
17045     return SDValue();
17046   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17047     ShAmt0 = ShAmt0.getOperand(0);
17048   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17049     ShAmt1 = ShAmt1.getOperand(0);
17050
17051   SDLoc DL(N);
17052   unsigned Opc = X86ISD::SHLD;
17053   SDValue Op0 = N0.getOperand(0);
17054   SDValue Op1 = N1.getOperand(0);
17055   if (ShAmt0.getOpcode() == ISD::SUB) {
17056     Opc = X86ISD::SHRD;
17057     std::swap(Op0, Op1);
17058     std::swap(ShAmt0, ShAmt1);
17059   }
17060
17061   unsigned Bits = VT.getSizeInBits();
17062   if (ShAmt1.getOpcode() == ISD::SUB) {
17063     SDValue Sum = ShAmt1.getOperand(0);
17064     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17065       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17066       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17067         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17068       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17069         return DAG.getNode(Opc, DL, VT,
17070                            Op0, Op1,
17071                            DAG.getNode(ISD::TRUNCATE, DL,
17072                                        MVT::i8, ShAmt0));
17073     }
17074   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17075     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17076     if (ShAmt0C &&
17077         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
17078       return DAG.getNode(Opc, DL, VT,
17079                          N0.getOperand(0), N1.getOperand(0),
17080                          DAG.getNode(ISD::TRUNCATE, DL,
17081                                        MVT::i8, ShAmt0));
17082   }
17083
17084   return SDValue();
17085 }
17086
17087 // Generate NEG and CMOV for integer abs.
17088 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
17089   EVT VT = N->getValueType(0);
17090
17091   // Since X86 does not have CMOV for 8-bit integer, we don't convert
17092   // 8-bit integer abs to NEG and CMOV.
17093   if (VT.isInteger() && VT.getSizeInBits() == 8)
17094     return SDValue();
17095
17096   SDValue N0 = N->getOperand(0);
17097   SDValue N1 = N->getOperand(1);
17098   SDLoc DL(N);
17099
17100   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
17101   // and change it to SUB and CMOV.
17102   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
17103       N0.getOpcode() == ISD::ADD &&
17104       N0.getOperand(1) == N1 &&
17105       N1.getOpcode() == ISD::SRA &&
17106       N1.getOperand(0) == N0.getOperand(0))
17107     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
17108       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
17109         // Generate SUB & CMOV.
17110         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
17111                                   DAG.getConstant(0, VT), N0.getOperand(0));
17112
17113         SDValue Ops[] = { N0.getOperand(0), Neg,
17114                           DAG.getConstant(X86::COND_GE, MVT::i8),
17115                           SDValue(Neg.getNode(), 1) };
17116         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
17117                            Ops, array_lengthof(Ops));
17118       }
17119   return SDValue();
17120 }
17121
17122 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
17123 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
17124                                  TargetLowering::DAGCombinerInfo &DCI,
17125                                  const X86Subtarget *Subtarget) {
17126   EVT VT = N->getValueType(0);
17127   if (DCI.isBeforeLegalizeOps())
17128     return SDValue();
17129
17130   if (Subtarget->hasCMov()) {
17131     SDValue RV = performIntegerAbsCombine(N, DAG);
17132     if (RV.getNode())
17133       return RV;
17134   }
17135
17136   // Try forming BMI if it is available.
17137   if (!Subtarget->hasBMI())
17138     return SDValue();
17139
17140   if (VT != MVT::i32 && VT != MVT::i64)
17141     return SDValue();
17142
17143   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
17144
17145   // Create BLSMSK instructions by finding X ^ (X-1)
17146   SDValue N0 = N->getOperand(0);
17147   SDValue N1 = N->getOperand(1);
17148   SDLoc DL(N);
17149
17150   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17151       isAllOnes(N0.getOperand(1)))
17152     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
17153
17154   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17155       isAllOnes(N1.getOperand(1)))
17156     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
17157
17158   return SDValue();
17159 }
17160
17161 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
17162 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
17163                                   TargetLowering::DAGCombinerInfo &DCI,
17164                                   const X86Subtarget *Subtarget) {
17165   LoadSDNode *Ld = cast<LoadSDNode>(N);
17166   EVT RegVT = Ld->getValueType(0);
17167   EVT MemVT = Ld->getMemoryVT();
17168   SDLoc dl(Ld);
17169   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17170   unsigned RegSz = RegVT.getSizeInBits();
17171
17172   // On Sandybridge unaligned 256bit loads are inefficient.
17173   ISD::LoadExtType Ext = Ld->getExtensionType();
17174   unsigned Alignment = Ld->getAlignment();
17175   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
17176   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
17177       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
17178     unsigned NumElems = RegVT.getVectorNumElements();
17179     if (NumElems < 2)
17180       return SDValue();
17181
17182     SDValue Ptr = Ld->getBasePtr();
17183     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
17184
17185     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17186                                   NumElems/2);
17187     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17188                                 Ld->getPointerInfo(), Ld->isVolatile(),
17189                                 Ld->isNonTemporal(), Ld->isInvariant(),
17190                                 Alignment);
17191     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17192     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17193                                 Ld->getPointerInfo(), Ld->isVolatile(),
17194                                 Ld->isNonTemporal(), Ld->isInvariant(),
17195                                 std::min(16U, Alignment));
17196     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17197                              Load1.getValue(1),
17198                              Load2.getValue(1));
17199
17200     SDValue NewVec = DAG.getUNDEF(RegVT);
17201     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
17202     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
17203     return DCI.CombineTo(N, NewVec, TF, true);
17204   }
17205
17206   // If this is a vector EXT Load then attempt to optimize it using a
17207   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
17208   // expansion is still better than scalar code.
17209   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
17210   // emit a shuffle and a arithmetic shift.
17211   // TODO: It is possible to support ZExt by zeroing the undef values
17212   // during the shuffle phase or after the shuffle.
17213   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
17214       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
17215     assert(MemVT != RegVT && "Cannot extend to the same type");
17216     assert(MemVT.isVector() && "Must load a vector from memory");
17217
17218     unsigned NumElems = RegVT.getVectorNumElements();
17219     unsigned MemSz = MemVT.getSizeInBits();
17220     assert(RegSz > MemSz && "Register size must be greater than the mem size");
17221
17222     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
17223       return SDValue();
17224
17225     // All sizes must be a power of two.
17226     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
17227       return SDValue();
17228
17229     // Attempt to load the original value using scalar loads.
17230     // Find the largest scalar type that divides the total loaded size.
17231     MVT SclrLoadTy = MVT::i8;
17232     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17233          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17234       MVT Tp = (MVT::SimpleValueType)tp;
17235       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
17236         SclrLoadTy = Tp;
17237       }
17238     }
17239
17240     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17241     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
17242         (64 <= MemSz))
17243       SclrLoadTy = MVT::f64;
17244
17245     // Calculate the number of scalar loads that we need to perform
17246     // in order to load our vector from memory.
17247     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
17248     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
17249       return SDValue();
17250
17251     unsigned loadRegZize = RegSz;
17252     if (Ext == ISD::SEXTLOAD && RegSz == 256)
17253       loadRegZize /= 2;
17254
17255     // Represent our vector as a sequence of elements which are the
17256     // largest scalar that we can load.
17257     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
17258       loadRegZize/SclrLoadTy.getSizeInBits());
17259
17260     // Represent the data using the same element type that is stored in
17261     // memory. In practice, we ''widen'' MemVT.
17262     EVT WideVecVT =
17263           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17264                        loadRegZize/MemVT.getScalarType().getSizeInBits());
17265
17266     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
17267       "Invalid vector type");
17268
17269     // We can't shuffle using an illegal type.
17270     if (!TLI.isTypeLegal(WideVecVT))
17271       return SDValue();
17272
17273     SmallVector<SDValue, 8> Chains;
17274     SDValue Ptr = Ld->getBasePtr();
17275     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
17276                                         TLI.getPointerTy());
17277     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
17278
17279     for (unsigned i = 0; i < NumLoads; ++i) {
17280       // Perform a single load.
17281       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
17282                                        Ptr, Ld->getPointerInfo(),
17283                                        Ld->isVolatile(), Ld->isNonTemporal(),
17284                                        Ld->isInvariant(), Ld->getAlignment());
17285       Chains.push_back(ScalarLoad.getValue(1));
17286       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
17287       // another round of DAGCombining.
17288       if (i == 0)
17289         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
17290       else
17291         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
17292                           ScalarLoad, DAG.getIntPtrConstant(i));
17293
17294       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17295     }
17296
17297     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17298                                Chains.size());
17299
17300     // Bitcast the loaded value to a vector of the original element type, in
17301     // the size of the target vector type.
17302     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
17303     unsigned SizeRatio = RegSz/MemSz;
17304
17305     if (Ext == ISD::SEXTLOAD) {
17306       // If we have SSE4.1 we can directly emit a VSEXT node.
17307       if (Subtarget->hasSSE41()) {
17308         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
17309         return DCI.CombineTo(N, Sext, TF, true);
17310       }
17311
17312       // Otherwise we'll shuffle the small elements in the high bits of the
17313       // larger type and perform an arithmetic shift. If the shift is not legal
17314       // it's better to scalarize.
17315       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
17316         return SDValue();
17317
17318       // Redistribute the loaded elements into the different locations.
17319       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17320       for (unsigned i = 0; i != NumElems; ++i)
17321         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
17322
17323       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17324                                            DAG.getUNDEF(WideVecVT),
17325                                            &ShuffleVec[0]);
17326
17327       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17328
17329       // Build the arithmetic shift.
17330       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
17331                      MemVT.getVectorElementType().getSizeInBits();
17332       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
17333                           DAG.getConstant(Amt, RegVT));
17334
17335       return DCI.CombineTo(N, Shuff, TF, true);
17336     }
17337
17338     // Redistribute the loaded elements into the different locations.
17339     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17340     for (unsigned i = 0; i != NumElems; ++i)
17341       ShuffleVec[i*SizeRatio] = i;
17342
17343     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17344                                          DAG.getUNDEF(WideVecVT),
17345                                          &ShuffleVec[0]);
17346
17347     // Bitcast to the requested type.
17348     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17349     // Replace the original load with the new sequence
17350     // and return the new chain.
17351     return DCI.CombineTo(N, Shuff, TF, true);
17352   }
17353
17354   return SDValue();
17355 }
17356
17357 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17358 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17359                                    const X86Subtarget *Subtarget) {
17360   StoreSDNode *St = cast<StoreSDNode>(N);
17361   EVT VT = St->getValue().getValueType();
17362   EVT StVT = St->getMemoryVT();
17363   SDLoc dl(St);
17364   SDValue StoredVal = St->getOperand(1);
17365   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17366
17367   // If we are saving a concatenation of two XMM registers, perform two stores.
17368   // On Sandy Bridge, 256-bit memory operations are executed by two
17369   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17370   // memory  operation.
17371   unsigned Alignment = St->getAlignment();
17372   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17373   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17374       StVT == VT && !IsAligned) {
17375     unsigned NumElems = VT.getVectorNumElements();
17376     if (NumElems < 2)
17377       return SDValue();
17378
17379     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17380     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17381
17382     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17383     SDValue Ptr0 = St->getBasePtr();
17384     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17385
17386     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17387                                 St->getPointerInfo(), St->isVolatile(),
17388                                 St->isNonTemporal(), Alignment);
17389     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17390                                 St->getPointerInfo(), St->isVolatile(),
17391                                 St->isNonTemporal(),
17392                                 std::min(16U, Alignment));
17393     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17394   }
17395
17396   // Optimize trunc store (of multiple scalars) to shuffle and store.
17397   // First, pack all of the elements in one place. Next, store to memory
17398   // in fewer chunks.
17399   if (St->isTruncatingStore() && VT.isVector()) {
17400     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17401     unsigned NumElems = VT.getVectorNumElements();
17402     assert(StVT != VT && "Cannot truncate to the same type");
17403     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17404     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17405
17406     // From, To sizes and ElemCount must be pow of two
17407     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17408     // We are going to use the original vector elt for storing.
17409     // Accumulated smaller vector elements must be a multiple of the store size.
17410     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17411
17412     unsigned SizeRatio  = FromSz / ToSz;
17413
17414     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17415
17416     // Create a type on which we perform the shuffle
17417     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17418             StVT.getScalarType(), NumElems*SizeRatio);
17419
17420     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17421
17422     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17423     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17424     for (unsigned i = 0; i != NumElems; ++i)
17425       ShuffleVec[i] = i * SizeRatio;
17426
17427     // Can't shuffle using an illegal type.
17428     if (!TLI.isTypeLegal(WideVecVT))
17429       return SDValue();
17430
17431     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17432                                          DAG.getUNDEF(WideVecVT),
17433                                          &ShuffleVec[0]);
17434     // At this point all of the data is stored at the bottom of the
17435     // register. We now need to save it to mem.
17436
17437     // Find the largest store unit
17438     MVT StoreType = MVT::i8;
17439     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17440          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17441       MVT Tp = (MVT::SimpleValueType)tp;
17442       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17443         StoreType = Tp;
17444     }
17445
17446     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17447     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17448         (64 <= NumElems * ToSz))
17449       StoreType = MVT::f64;
17450
17451     // Bitcast the original vector into a vector of store-size units
17452     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17453             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17454     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17455     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17456     SmallVector<SDValue, 8> Chains;
17457     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17458                                         TLI.getPointerTy());
17459     SDValue Ptr = St->getBasePtr();
17460
17461     // Perform one or more big stores into memory.
17462     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17463       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17464                                    StoreType, ShuffWide,
17465                                    DAG.getIntPtrConstant(i));
17466       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17467                                 St->getPointerInfo(), St->isVolatile(),
17468                                 St->isNonTemporal(), St->getAlignment());
17469       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17470       Chains.push_back(Ch);
17471     }
17472
17473     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17474                                Chains.size());
17475   }
17476
17477   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17478   // the FP state in cases where an emms may be missing.
17479   // A preferable solution to the general problem is to figure out the right
17480   // places to insert EMMS.  This qualifies as a quick hack.
17481
17482   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17483   if (VT.getSizeInBits() != 64)
17484     return SDValue();
17485
17486   const Function *F = DAG.getMachineFunction().getFunction();
17487   bool NoImplicitFloatOps = F->getAttributes().
17488     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17489   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17490                      && Subtarget->hasSSE2();
17491   if ((VT.isVector() ||
17492        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17493       isa<LoadSDNode>(St->getValue()) &&
17494       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17495       St->getChain().hasOneUse() && !St->isVolatile()) {
17496     SDNode* LdVal = St->getValue().getNode();
17497     LoadSDNode *Ld = 0;
17498     int TokenFactorIndex = -1;
17499     SmallVector<SDValue, 8> Ops;
17500     SDNode* ChainVal = St->getChain().getNode();
17501     // Must be a store of a load.  We currently handle two cases:  the load
17502     // is a direct child, and it's under an intervening TokenFactor.  It is
17503     // possible to dig deeper under nested TokenFactors.
17504     if (ChainVal == LdVal)
17505       Ld = cast<LoadSDNode>(St->getChain());
17506     else if (St->getValue().hasOneUse() &&
17507              ChainVal->getOpcode() == ISD::TokenFactor) {
17508       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17509         if (ChainVal->getOperand(i).getNode() == LdVal) {
17510           TokenFactorIndex = i;
17511           Ld = cast<LoadSDNode>(St->getValue());
17512         } else
17513           Ops.push_back(ChainVal->getOperand(i));
17514       }
17515     }
17516
17517     if (!Ld || !ISD::isNormalLoad(Ld))
17518       return SDValue();
17519
17520     // If this is not the MMX case, i.e. we are just turning i64 load/store
17521     // into f64 load/store, avoid the transformation if there are multiple
17522     // uses of the loaded value.
17523     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17524       return SDValue();
17525
17526     SDLoc LdDL(Ld);
17527     SDLoc StDL(N);
17528     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17529     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17530     // pair instead.
17531     if (Subtarget->is64Bit() || F64IsLegal) {
17532       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17533       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17534                                   Ld->getPointerInfo(), Ld->isVolatile(),
17535                                   Ld->isNonTemporal(), Ld->isInvariant(),
17536                                   Ld->getAlignment());
17537       SDValue NewChain = NewLd.getValue(1);
17538       if (TokenFactorIndex != -1) {
17539         Ops.push_back(NewChain);
17540         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17541                                Ops.size());
17542       }
17543       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17544                           St->getPointerInfo(),
17545                           St->isVolatile(), St->isNonTemporal(),
17546                           St->getAlignment());
17547     }
17548
17549     // Otherwise, lower to two pairs of 32-bit loads / stores.
17550     SDValue LoAddr = Ld->getBasePtr();
17551     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17552                                  DAG.getConstant(4, MVT::i32));
17553
17554     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17555                                Ld->getPointerInfo(),
17556                                Ld->isVolatile(), Ld->isNonTemporal(),
17557                                Ld->isInvariant(), Ld->getAlignment());
17558     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17559                                Ld->getPointerInfo().getWithOffset(4),
17560                                Ld->isVolatile(), Ld->isNonTemporal(),
17561                                Ld->isInvariant(),
17562                                MinAlign(Ld->getAlignment(), 4));
17563
17564     SDValue NewChain = LoLd.getValue(1);
17565     if (TokenFactorIndex != -1) {
17566       Ops.push_back(LoLd);
17567       Ops.push_back(HiLd);
17568       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17569                              Ops.size());
17570     }
17571
17572     LoAddr = St->getBasePtr();
17573     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17574                          DAG.getConstant(4, MVT::i32));
17575
17576     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17577                                 St->getPointerInfo(),
17578                                 St->isVolatile(), St->isNonTemporal(),
17579                                 St->getAlignment());
17580     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17581                                 St->getPointerInfo().getWithOffset(4),
17582                                 St->isVolatile(),
17583                                 St->isNonTemporal(),
17584                                 MinAlign(St->getAlignment(), 4));
17585     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17586   }
17587   return SDValue();
17588 }
17589
17590 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17591 /// and return the operands for the horizontal operation in LHS and RHS.  A
17592 /// horizontal operation performs the binary operation on successive elements
17593 /// of its first operand, then on successive elements of its second operand,
17594 /// returning the resulting values in a vector.  For example, if
17595 ///   A = < float a0, float a1, float a2, float a3 >
17596 /// and
17597 ///   B = < float b0, float b1, float b2, float b3 >
17598 /// then the result of doing a horizontal operation on A and B is
17599 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17600 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17601 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17602 /// set to A, RHS to B, and the routine returns 'true'.
17603 /// Note that the binary operation should have the property that if one of the
17604 /// operands is UNDEF then the result is UNDEF.
17605 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17606   // Look for the following pattern: if
17607   //   A = < float a0, float a1, float a2, float a3 >
17608   //   B = < float b0, float b1, float b2, float b3 >
17609   // and
17610   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17611   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17612   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17613   // which is A horizontal-op B.
17614
17615   // At least one of the operands should be a vector shuffle.
17616   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17617       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17618     return false;
17619
17620   EVT VT = LHS.getValueType();
17621
17622   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17623          "Unsupported vector type for horizontal add/sub");
17624
17625   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17626   // operate independently on 128-bit lanes.
17627   unsigned NumElts = VT.getVectorNumElements();
17628   unsigned NumLanes = VT.getSizeInBits()/128;
17629   unsigned NumLaneElts = NumElts / NumLanes;
17630   assert((NumLaneElts % 2 == 0) &&
17631          "Vector type should have an even number of elements in each lane");
17632   unsigned HalfLaneElts = NumLaneElts/2;
17633
17634   // View LHS in the form
17635   //   LHS = VECTOR_SHUFFLE A, B, LMask
17636   // If LHS is not a shuffle then pretend it is the shuffle
17637   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17638   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17639   // type VT.
17640   SDValue A, B;
17641   SmallVector<int, 16> LMask(NumElts);
17642   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17643     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17644       A = LHS.getOperand(0);
17645     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17646       B = LHS.getOperand(1);
17647     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17648     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17649   } else {
17650     if (LHS.getOpcode() != ISD::UNDEF)
17651       A = LHS;
17652     for (unsigned i = 0; i != NumElts; ++i)
17653       LMask[i] = i;
17654   }
17655
17656   // Likewise, view RHS in the form
17657   //   RHS = VECTOR_SHUFFLE C, D, RMask
17658   SDValue C, D;
17659   SmallVector<int, 16> RMask(NumElts);
17660   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17661     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17662       C = RHS.getOperand(0);
17663     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17664       D = RHS.getOperand(1);
17665     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17666     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17667   } else {
17668     if (RHS.getOpcode() != ISD::UNDEF)
17669       C = RHS;
17670     for (unsigned i = 0; i != NumElts; ++i)
17671       RMask[i] = i;
17672   }
17673
17674   // Check that the shuffles are both shuffling the same vectors.
17675   if (!(A == C && B == D) && !(A == D && B == C))
17676     return false;
17677
17678   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17679   if (!A.getNode() && !B.getNode())
17680     return false;
17681
17682   // If A and B occur in reverse order in RHS, then "swap" them (which means
17683   // rewriting the mask).
17684   if (A != C)
17685     CommuteVectorShuffleMask(RMask, NumElts);
17686
17687   // At this point LHS and RHS are equivalent to
17688   //   LHS = VECTOR_SHUFFLE A, B, LMask
17689   //   RHS = VECTOR_SHUFFLE A, B, RMask
17690   // Check that the masks correspond to performing a horizontal operation.
17691   for (unsigned i = 0; i != NumElts; ++i) {
17692     int LIdx = LMask[i], RIdx = RMask[i];
17693
17694     // Ignore any UNDEF components.
17695     if (LIdx < 0 || RIdx < 0 ||
17696         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17697         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17698       continue;
17699
17700     // Check that successive elements are being operated on.  If not, this is
17701     // not a horizontal operation.
17702     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17703     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17704     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17705     if (!(LIdx == Index && RIdx == Index + 1) &&
17706         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17707       return false;
17708   }
17709
17710   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17711   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17712   return true;
17713 }
17714
17715 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17716 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17717                                   const X86Subtarget *Subtarget) {
17718   EVT VT = N->getValueType(0);
17719   SDValue LHS = N->getOperand(0);
17720   SDValue RHS = N->getOperand(1);
17721
17722   // Try to synthesize horizontal adds from adds of shuffles.
17723   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17724        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17725       isHorizontalBinOp(LHS, RHS, true))
17726     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17727   return SDValue();
17728 }
17729
17730 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17731 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17732                                   const X86Subtarget *Subtarget) {
17733   EVT VT = N->getValueType(0);
17734   SDValue LHS = N->getOperand(0);
17735   SDValue RHS = N->getOperand(1);
17736
17737   // Try to synthesize horizontal subs from subs of shuffles.
17738   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17739        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17740       isHorizontalBinOp(LHS, RHS, false))
17741     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17742   return SDValue();
17743 }
17744
17745 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17746 /// X86ISD::FXOR nodes.
17747 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17748   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17749   // F[X]OR(0.0, x) -> x
17750   // F[X]OR(x, 0.0) -> x
17751   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17752     if (C->getValueAPF().isPosZero())
17753       return N->getOperand(1);
17754   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17755     if (C->getValueAPF().isPosZero())
17756       return N->getOperand(0);
17757   return SDValue();
17758 }
17759
17760 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17761 /// X86ISD::FMAX nodes.
17762 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17763   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17764
17765   // Only perform optimizations if UnsafeMath is used.
17766   if (!DAG.getTarget().Options.UnsafeFPMath)
17767     return SDValue();
17768
17769   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17770   // into FMINC and FMAXC, which are Commutative operations.
17771   unsigned NewOp = 0;
17772   switch (N->getOpcode()) {
17773     default: llvm_unreachable("unknown opcode");
17774     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17775     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17776   }
17777
17778   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
17779                      N->getOperand(0), N->getOperand(1));
17780 }
17781
17782 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17783 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17784   // FAND(0.0, x) -> 0.0
17785   // FAND(x, 0.0) -> 0.0
17786   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17787     if (C->getValueAPF().isPosZero())
17788       return N->getOperand(0);
17789   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17790     if (C->getValueAPF().isPosZero())
17791       return N->getOperand(1);
17792   return SDValue();
17793 }
17794
17795 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
17796 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
17797   // FANDN(x, 0.0) -> 0.0
17798   // FANDN(0.0, x) -> x
17799   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17800     if (C->getValueAPF().isPosZero())
17801       return N->getOperand(1);
17802   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17803     if (C->getValueAPF().isPosZero())
17804       return N->getOperand(1);
17805   return SDValue();
17806 }
17807
17808 static SDValue PerformBTCombine(SDNode *N,
17809                                 SelectionDAG &DAG,
17810                                 TargetLowering::DAGCombinerInfo &DCI) {
17811   // BT ignores high bits in the bit index operand.
17812   SDValue Op1 = N->getOperand(1);
17813   if (Op1.hasOneUse()) {
17814     unsigned BitWidth = Op1.getValueSizeInBits();
17815     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17816     APInt KnownZero, KnownOne;
17817     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17818                                           !DCI.isBeforeLegalizeOps());
17819     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17820     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17821         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17822       DCI.CommitTargetLoweringOpt(TLO);
17823   }
17824   return SDValue();
17825 }
17826
17827 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17828   SDValue Op = N->getOperand(0);
17829   if (Op.getOpcode() == ISD::BITCAST)
17830     Op = Op.getOperand(0);
17831   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17832   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17833       VT.getVectorElementType().getSizeInBits() ==
17834       OpVT.getVectorElementType().getSizeInBits()) {
17835     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
17836   }
17837   return SDValue();
17838 }
17839
17840 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17841                                                const X86Subtarget *Subtarget) {
17842   EVT VT = N->getValueType(0);
17843   if (!VT.isVector())
17844     return SDValue();
17845
17846   SDValue N0 = N->getOperand(0);
17847   SDValue N1 = N->getOperand(1);
17848   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17849   SDLoc dl(N);
17850
17851   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17852   // both SSE and AVX2 since there is no sign-extended shift right
17853   // operation on a vector with 64-bit elements.
17854   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17855   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17856   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17857       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17858     SDValue N00 = N0.getOperand(0);
17859
17860     // EXTLOAD has a better solution on AVX2,
17861     // it may be replaced with X86ISD::VSEXT node.
17862     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17863       if (!ISD::isNormalLoad(N00.getNode()))
17864         return SDValue();
17865
17866     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17867         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17868                                   N00, N1);
17869       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17870     }
17871   }
17872   return SDValue();
17873 }
17874
17875 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17876                                   TargetLowering::DAGCombinerInfo &DCI,
17877                                   const X86Subtarget *Subtarget) {
17878   if (!DCI.isBeforeLegalizeOps())
17879     return SDValue();
17880
17881   if (!Subtarget->hasFp256())
17882     return SDValue();
17883
17884   EVT VT = N->getValueType(0);
17885   if (VT.isVector() && VT.getSizeInBits() == 256) {
17886     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17887     if (R.getNode())
17888       return R;
17889   }
17890
17891   return SDValue();
17892 }
17893
17894 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17895                                  const X86Subtarget* Subtarget) {
17896   SDLoc dl(N);
17897   EVT VT = N->getValueType(0);
17898
17899   // Let legalize expand this if it isn't a legal type yet.
17900   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17901     return SDValue();
17902
17903   EVT ScalarVT = VT.getScalarType();
17904   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17905       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17906     return SDValue();
17907
17908   SDValue A = N->getOperand(0);
17909   SDValue B = N->getOperand(1);
17910   SDValue C = N->getOperand(2);
17911
17912   bool NegA = (A.getOpcode() == ISD::FNEG);
17913   bool NegB = (B.getOpcode() == ISD::FNEG);
17914   bool NegC = (C.getOpcode() == ISD::FNEG);
17915
17916   // Negative multiplication when NegA xor NegB
17917   bool NegMul = (NegA != NegB);
17918   if (NegA)
17919     A = A.getOperand(0);
17920   if (NegB)
17921     B = B.getOperand(0);
17922   if (NegC)
17923     C = C.getOperand(0);
17924
17925   unsigned Opcode;
17926   if (!NegMul)
17927     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17928   else
17929     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17930
17931   return DAG.getNode(Opcode, dl, VT, A, B, C);
17932 }
17933
17934 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17935                                   TargetLowering::DAGCombinerInfo &DCI,
17936                                   const X86Subtarget *Subtarget) {
17937   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17938   //           (and (i32 x86isd::setcc_carry), 1)
17939   // This eliminates the zext. This transformation is necessary because
17940   // ISD::SETCC is always legalized to i8.
17941   SDLoc dl(N);
17942   SDValue N0 = N->getOperand(0);
17943   EVT VT = N->getValueType(0);
17944
17945   if (N0.getOpcode() == ISD::AND &&
17946       N0.hasOneUse() &&
17947       N0.getOperand(0).hasOneUse()) {
17948     SDValue N00 = N0.getOperand(0);
17949     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17950       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17951       if (!C || C->getZExtValue() != 1)
17952         return SDValue();
17953       return DAG.getNode(ISD::AND, dl, VT,
17954                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17955                                      N00.getOperand(0), N00.getOperand(1)),
17956                          DAG.getConstant(1, VT));
17957     }
17958   }
17959
17960   if (VT.is256BitVector()) {
17961     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17962     if (R.getNode())
17963       return R;
17964   }
17965
17966   return SDValue();
17967 }
17968
17969 // Optimize x == -y --> x+y == 0
17970 //          x != -y --> x+y != 0
17971 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17972   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17973   SDValue LHS = N->getOperand(0);
17974   SDValue RHS = N->getOperand(1);
17975
17976   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17977     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17978       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17979         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17980                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17981         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17982                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17983       }
17984   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17985     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17986       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17987         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17988                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17989         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17990                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17991       }
17992   return SDValue();
17993 }
17994
17995 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17996 // as "sbb reg,reg", since it can be extended without zext and produces
17997 // an all-ones bit which is more useful than 0/1 in some cases.
17998 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17999   return DAG.getNode(ISD::AND, DL, MVT::i8,
18000                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
18001                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
18002                      DAG.getConstant(1, MVT::i8));
18003 }
18004
18005 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
18006 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
18007                                    TargetLowering::DAGCombinerInfo &DCI,
18008                                    const X86Subtarget *Subtarget) {
18009   SDLoc DL(N);
18010   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
18011   SDValue EFLAGS = N->getOperand(1);
18012
18013   if (CC == X86::COND_A) {
18014     // Try to convert COND_A into COND_B in an attempt to facilitate
18015     // materializing "setb reg".
18016     //
18017     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
18018     // cannot take an immediate as its first operand.
18019     //
18020     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
18021         EFLAGS.getValueType().isInteger() &&
18022         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
18023       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
18024                                    EFLAGS.getNode()->getVTList(),
18025                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
18026       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
18027       return MaterializeSETB(DL, NewEFLAGS, DAG);
18028     }
18029   }
18030
18031   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
18032   // a zext and produces an all-ones bit which is more useful than 0/1 in some
18033   // cases.
18034   if (CC == X86::COND_B)
18035     return MaterializeSETB(DL, EFLAGS, DAG);
18036
18037   SDValue Flags;
18038
18039   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18040   if (Flags.getNode()) {
18041     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18042     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
18043   }
18044
18045   return SDValue();
18046 }
18047
18048 // Optimize branch condition evaluation.
18049 //
18050 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18051                                     TargetLowering::DAGCombinerInfo &DCI,
18052                                     const X86Subtarget *Subtarget) {
18053   SDLoc DL(N);
18054   SDValue Chain = N->getOperand(0);
18055   SDValue Dest = N->getOperand(1);
18056   SDValue EFLAGS = N->getOperand(3);
18057   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18058
18059   SDValue Flags;
18060
18061   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18062   if (Flags.getNode()) {
18063     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18064     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18065                        Flags);
18066   }
18067
18068   return SDValue();
18069 }
18070
18071 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18072                                         const X86TargetLowering *XTLI) {
18073   SDValue Op0 = N->getOperand(0);
18074   EVT InVT = Op0->getValueType(0);
18075
18076   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
18077   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
18078     SDLoc dl(N);
18079     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
18080     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
18081     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
18082   }
18083
18084   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
18085   // a 32-bit target where SSE doesn't support i64->FP operations.
18086   if (Op0.getOpcode() == ISD::LOAD) {
18087     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
18088     EVT VT = Ld->getValueType(0);
18089     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
18090         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
18091         !XTLI->getSubtarget()->is64Bit() &&
18092         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18093       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
18094                                           Ld->getChain(), Op0, DAG);
18095       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
18096       return FILDChain;
18097     }
18098   }
18099   return SDValue();
18100 }
18101
18102 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
18103 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
18104                                  X86TargetLowering::DAGCombinerInfo &DCI) {
18105   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
18106   // the result is either zero or one (depending on the input carry bit).
18107   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
18108   if (X86::isZeroNode(N->getOperand(0)) &&
18109       X86::isZeroNode(N->getOperand(1)) &&
18110       // We don't have a good way to replace an EFLAGS use, so only do this when
18111       // dead right now.
18112       SDValue(N, 1).use_empty()) {
18113     SDLoc DL(N);
18114     EVT VT = N->getValueType(0);
18115     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
18116     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
18117                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
18118                                            DAG.getConstant(X86::COND_B,MVT::i8),
18119                                            N->getOperand(2)),
18120                                DAG.getConstant(1, VT));
18121     return DCI.CombineTo(N, Res1, CarryOut);
18122   }
18123
18124   return SDValue();
18125 }
18126
18127 // fold (add Y, (sete  X, 0)) -> adc  0, Y
18128 //      (add Y, (setne X, 0)) -> sbb -1, Y
18129 //      (sub (sete  X, 0), Y) -> sbb  0, Y
18130 //      (sub (setne X, 0), Y) -> adc -1, Y
18131 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
18132   SDLoc DL(N);
18133
18134   // Look through ZExts.
18135   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
18136   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
18137     return SDValue();
18138
18139   SDValue SetCC = Ext.getOperand(0);
18140   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
18141     return SDValue();
18142
18143   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
18144   if (CC != X86::COND_E && CC != X86::COND_NE)
18145     return SDValue();
18146
18147   SDValue Cmp = SetCC.getOperand(1);
18148   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
18149       !X86::isZeroNode(Cmp.getOperand(1)) ||
18150       !Cmp.getOperand(0).getValueType().isInteger())
18151     return SDValue();
18152
18153   SDValue CmpOp0 = Cmp.getOperand(0);
18154   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
18155                                DAG.getConstant(1, CmpOp0.getValueType()));
18156
18157   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
18158   if (CC == X86::COND_NE)
18159     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
18160                        DL, OtherVal.getValueType(), OtherVal,
18161                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
18162   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
18163                      DL, OtherVal.getValueType(), OtherVal,
18164                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
18165 }
18166
18167 /// PerformADDCombine - Do target-specific dag combines on integer adds.
18168 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
18169                                  const X86Subtarget *Subtarget) {
18170   EVT VT = N->getValueType(0);
18171   SDValue Op0 = N->getOperand(0);
18172   SDValue Op1 = N->getOperand(1);
18173
18174   // Try to synthesize horizontal adds from adds of shuffles.
18175   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18176        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18177       isHorizontalBinOp(Op0, Op1, true))
18178     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
18179
18180   return OptimizeConditionalInDecrement(N, DAG);
18181 }
18182
18183 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
18184                                  const X86Subtarget *Subtarget) {
18185   SDValue Op0 = N->getOperand(0);
18186   SDValue Op1 = N->getOperand(1);
18187
18188   // X86 can't encode an immediate LHS of a sub. See if we can push the
18189   // negation into a preceding instruction.
18190   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
18191     // If the RHS of the sub is a XOR with one use and a constant, invert the
18192     // immediate. Then add one to the LHS of the sub so we can turn
18193     // X-Y -> X+~Y+1, saving one register.
18194     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
18195         isa<ConstantSDNode>(Op1.getOperand(1))) {
18196       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
18197       EVT VT = Op0.getValueType();
18198       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
18199                                    Op1.getOperand(0),
18200                                    DAG.getConstant(~XorC, VT));
18201       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
18202                          DAG.getConstant(C->getAPIntValue()+1, VT));
18203     }
18204   }
18205
18206   // Try to synthesize horizontal adds from adds of shuffles.
18207   EVT VT = N->getValueType(0);
18208   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18209        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18210       isHorizontalBinOp(Op0, Op1, true))
18211     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
18212
18213   return OptimizeConditionalInDecrement(N, DAG);
18214 }
18215
18216 /// performVZEXTCombine - Performs build vector combines
18217 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
18218                                         TargetLowering::DAGCombinerInfo &DCI,
18219                                         const X86Subtarget *Subtarget) {
18220   // (vzext (bitcast (vzext (x)) -> (vzext x)
18221   SDValue In = N->getOperand(0);
18222   while (In.getOpcode() == ISD::BITCAST)
18223     In = In.getOperand(0);
18224
18225   if (In.getOpcode() != X86ISD::VZEXT)
18226     return SDValue();
18227
18228   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
18229                      In.getOperand(0));
18230 }
18231
18232 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
18233                                              DAGCombinerInfo &DCI) const {
18234   SelectionDAG &DAG = DCI.DAG;
18235   switch (N->getOpcode()) {
18236   default: break;
18237   case ISD::EXTRACT_VECTOR_ELT:
18238     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
18239   case ISD::VSELECT:
18240   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
18241   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
18242   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
18243   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
18244   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
18245   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
18246   case ISD::SHL:
18247   case ISD::SRA:
18248   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
18249   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
18250   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
18251   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
18252   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
18253   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
18254   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
18255   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
18256   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
18257   case X86ISD::FXOR:
18258   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
18259   case X86ISD::FMIN:
18260   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
18261   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
18262   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
18263   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
18264   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
18265   case ISD::ANY_EXTEND:
18266   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
18267   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
18268   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
18269   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
18270   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
18271   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
18272   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
18273   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
18274   case X86ISD::SHUFP:       // Handle all target specific shuffles
18275   case X86ISD::PALIGNR:
18276   case X86ISD::UNPCKH:
18277   case X86ISD::UNPCKL:
18278   case X86ISD::MOVHLPS:
18279   case X86ISD::MOVLHPS:
18280   case X86ISD::PSHUFD:
18281   case X86ISD::PSHUFHW:
18282   case X86ISD::PSHUFLW:
18283   case X86ISD::MOVSS:
18284   case X86ISD::MOVSD:
18285   case X86ISD::VPERMILP:
18286   case X86ISD::VPERM2X128:
18287   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
18288   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
18289   }
18290
18291   return SDValue();
18292 }
18293
18294 /// isTypeDesirableForOp - Return true if the target has native support for
18295 /// the specified value type and it is 'desirable' to use the type for the
18296 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
18297 /// instruction encodings are longer and some i16 instructions are slow.
18298 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
18299   if (!isTypeLegal(VT))
18300     return false;
18301   if (VT != MVT::i16)
18302     return true;
18303
18304   switch (Opc) {
18305   default:
18306     return true;
18307   case ISD::LOAD:
18308   case ISD::SIGN_EXTEND:
18309   case ISD::ZERO_EXTEND:
18310   case ISD::ANY_EXTEND:
18311   case ISD::SHL:
18312   case ISD::SRL:
18313   case ISD::SUB:
18314   case ISD::ADD:
18315   case ISD::MUL:
18316   case ISD::AND:
18317   case ISD::OR:
18318   case ISD::XOR:
18319     return false;
18320   }
18321 }
18322
18323 /// IsDesirableToPromoteOp - This method query the target whether it is
18324 /// beneficial for dag combiner to promote the specified node. If true, it
18325 /// should return the desired promotion type by reference.
18326 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
18327   EVT VT = Op.getValueType();
18328   if (VT != MVT::i16)
18329     return false;
18330
18331   bool Promote = false;
18332   bool Commute = false;
18333   switch (Op.getOpcode()) {
18334   default: break;
18335   case ISD::LOAD: {
18336     LoadSDNode *LD = cast<LoadSDNode>(Op);
18337     // If the non-extending load has a single use and it's not live out, then it
18338     // might be folded.
18339     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
18340                                                      Op.hasOneUse()*/) {
18341       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18342              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
18343         // The only case where we'd want to promote LOAD (rather then it being
18344         // promoted as an operand is when it's only use is liveout.
18345         if (UI->getOpcode() != ISD::CopyToReg)
18346           return false;
18347       }
18348     }
18349     Promote = true;
18350     break;
18351   }
18352   case ISD::SIGN_EXTEND:
18353   case ISD::ZERO_EXTEND:
18354   case ISD::ANY_EXTEND:
18355     Promote = true;
18356     break;
18357   case ISD::SHL:
18358   case ISD::SRL: {
18359     SDValue N0 = Op.getOperand(0);
18360     // Look out for (store (shl (load), x)).
18361     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
18362       return false;
18363     Promote = true;
18364     break;
18365   }
18366   case ISD::ADD:
18367   case ISD::MUL:
18368   case ISD::AND:
18369   case ISD::OR:
18370   case ISD::XOR:
18371     Commute = true;
18372     // fallthrough
18373   case ISD::SUB: {
18374     SDValue N0 = Op.getOperand(0);
18375     SDValue N1 = Op.getOperand(1);
18376     if (!Commute && MayFoldLoad(N1))
18377       return false;
18378     // Avoid disabling potential load folding opportunities.
18379     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18380       return false;
18381     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18382       return false;
18383     Promote = true;
18384   }
18385   }
18386
18387   PVT = MVT::i32;
18388   return Promote;
18389 }
18390
18391 //===----------------------------------------------------------------------===//
18392 //                           X86 Inline Assembly Support
18393 //===----------------------------------------------------------------------===//
18394
18395 namespace {
18396   // Helper to match a string separated by whitespace.
18397   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18398     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18399
18400     for (unsigned i = 0, e = args.size(); i != e; ++i) {
18401       StringRef piece(*args[i]);
18402       if (!s.startswith(piece)) // Check if the piece matches.
18403         return false;
18404
18405       s = s.substr(piece.size());
18406       StringRef::size_type pos = s.find_first_not_of(" \t");
18407       if (pos == 0) // We matched a prefix.
18408         return false;
18409
18410       s = s.substr(pos);
18411     }
18412
18413     return s.empty();
18414   }
18415   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18416 }
18417
18418 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18419   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18420
18421   std::string AsmStr = IA->getAsmString();
18422
18423   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18424   if (!Ty || Ty->getBitWidth() % 16 != 0)
18425     return false;
18426
18427   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18428   SmallVector<StringRef, 4> AsmPieces;
18429   SplitString(AsmStr, AsmPieces, ";\n");
18430
18431   switch (AsmPieces.size()) {
18432   default: return false;
18433   case 1:
18434     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18435     // we will turn this bswap into something that will be lowered to logical
18436     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18437     // lower so don't worry about this.
18438     // bswap $0
18439     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18440         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18441         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18442         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18443         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18444         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18445       // No need to check constraints, nothing other than the equivalent of
18446       // "=r,0" would be valid here.
18447       return IntrinsicLowering::LowerToByteSwap(CI);
18448     }
18449
18450     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18451     if (CI->getType()->isIntegerTy(16) &&
18452         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18453         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18454          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18455       AsmPieces.clear();
18456       const std::string &ConstraintsStr = IA->getConstraintString();
18457       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18458       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18459       if (AsmPieces.size() == 4 &&
18460           AsmPieces[0] == "~{cc}" &&
18461           AsmPieces[1] == "~{dirflag}" &&
18462           AsmPieces[2] == "~{flags}" &&
18463           AsmPieces[3] == "~{fpsr}")
18464       return IntrinsicLowering::LowerToByteSwap(CI);
18465     }
18466     break;
18467   case 3:
18468     if (CI->getType()->isIntegerTy(32) &&
18469         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18470         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18471         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18472         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18473       AsmPieces.clear();
18474       const std::string &ConstraintsStr = IA->getConstraintString();
18475       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18476       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18477       if (AsmPieces.size() == 4 &&
18478           AsmPieces[0] == "~{cc}" &&
18479           AsmPieces[1] == "~{dirflag}" &&
18480           AsmPieces[2] == "~{flags}" &&
18481           AsmPieces[3] == "~{fpsr}")
18482         return IntrinsicLowering::LowerToByteSwap(CI);
18483     }
18484
18485     if (CI->getType()->isIntegerTy(64)) {
18486       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18487       if (Constraints.size() >= 2 &&
18488           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18489           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18490         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18491         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18492             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18493             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18494           return IntrinsicLowering::LowerToByteSwap(CI);
18495       }
18496     }
18497     break;
18498   }
18499   return false;
18500 }
18501
18502 /// getConstraintType - Given a constraint letter, return the type of
18503 /// constraint it is for this target.
18504 X86TargetLowering::ConstraintType
18505 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18506   if (Constraint.size() == 1) {
18507     switch (Constraint[0]) {
18508     case 'R':
18509     case 'q':
18510     case 'Q':
18511     case 'f':
18512     case 't':
18513     case 'u':
18514     case 'y':
18515     case 'x':
18516     case 'Y':
18517     case 'l':
18518       return C_RegisterClass;
18519     case 'a':
18520     case 'b':
18521     case 'c':
18522     case 'd':
18523     case 'S':
18524     case 'D':
18525     case 'A':
18526       return C_Register;
18527     case 'I':
18528     case 'J':
18529     case 'K':
18530     case 'L':
18531     case 'M':
18532     case 'N':
18533     case 'G':
18534     case 'C':
18535     case 'e':
18536     case 'Z':
18537       return C_Other;
18538     default:
18539       break;
18540     }
18541   }
18542   return TargetLowering::getConstraintType(Constraint);
18543 }
18544
18545 /// Examine constraint type and operand type and determine a weight value.
18546 /// This object must already have been set up with the operand type
18547 /// and the current alternative constraint selected.
18548 TargetLowering::ConstraintWeight
18549   X86TargetLowering::getSingleConstraintMatchWeight(
18550     AsmOperandInfo &info, const char *constraint) const {
18551   ConstraintWeight weight = CW_Invalid;
18552   Value *CallOperandVal = info.CallOperandVal;
18553     // If we don't have a value, we can't do a match,
18554     // but allow it at the lowest weight.
18555   if (CallOperandVal == NULL)
18556     return CW_Default;
18557   Type *type = CallOperandVal->getType();
18558   // Look at the constraint type.
18559   switch (*constraint) {
18560   default:
18561     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18562   case 'R':
18563   case 'q':
18564   case 'Q':
18565   case 'a':
18566   case 'b':
18567   case 'c':
18568   case 'd':
18569   case 'S':
18570   case 'D':
18571   case 'A':
18572     if (CallOperandVal->getType()->isIntegerTy())
18573       weight = CW_SpecificReg;
18574     break;
18575   case 'f':
18576   case 't':
18577   case 'u':
18578     if (type->isFloatingPointTy())
18579       weight = CW_SpecificReg;
18580     break;
18581   case 'y':
18582     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18583       weight = CW_SpecificReg;
18584     break;
18585   case 'x':
18586   case 'Y':
18587     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18588         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18589       weight = CW_Register;
18590     break;
18591   case 'I':
18592     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18593       if (C->getZExtValue() <= 31)
18594         weight = CW_Constant;
18595     }
18596     break;
18597   case 'J':
18598     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18599       if (C->getZExtValue() <= 63)
18600         weight = CW_Constant;
18601     }
18602     break;
18603   case 'K':
18604     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18605       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18606         weight = CW_Constant;
18607     }
18608     break;
18609   case 'L':
18610     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18611       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18612         weight = CW_Constant;
18613     }
18614     break;
18615   case 'M':
18616     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18617       if (C->getZExtValue() <= 3)
18618         weight = CW_Constant;
18619     }
18620     break;
18621   case 'N':
18622     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18623       if (C->getZExtValue() <= 0xff)
18624         weight = CW_Constant;
18625     }
18626     break;
18627   case 'G':
18628   case 'C':
18629     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18630       weight = CW_Constant;
18631     }
18632     break;
18633   case 'e':
18634     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18635       if ((C->getSExtValue() >= -0x80000000LL) &&
18636           (C->getSExtValue() <= 0x7fffffffLL))
18637         weight = CW_Constant;
18638     }
18639     break;
18640   case 'Z':
18641     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18642       if (C->getZExtValue() <= 0xffffffff)
18643         weight = CW_Constant;
18644     }
18645     break;
18646   }
18647   return weight;
18648 }
18649
18650 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18651 /// with another that has more specific requirements based on the type of the
18652 /// corresponding operand.
18653 const char *X86TargetLowering::
18654 LowerXConstraint(EVT ConstraintVT) const {
18655   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18656   // 'f' like normal targets.
18657   if (ConstraintVT.isFloatingPoint()) {
18658     if (Subtarget->hasSSE2())
18659       return "Y";
18660     if (Subtarget->hasSSE1())
18661       return "x";
18662   }
18663
18664   return TargetLowering::LowerXConstraint(ConstraintVT);
18665 }
18666
18667 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18668 /// vector.  If it is invalid, don't add anything to Ops.
18669 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18670                                                      std::string &Constraint,
18671                                                      std::vector<SDValue>&Ops,
18672                                                      SelectionDAG &DAG) const {
18673   SDValue Result(0, 0);
18674
18675   // Only support length 1 constraints for now.
18676   if (Constraint.length() > 1) return;
18677
18678   char ConstraintLetter = Constraint[0];
18679   switch (ConstraintLetter) {
18680   default: break;
18681   case 'I':
18682     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18683       if (C->getZExtValue() <= 31) {
18684         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18685         break;
18686       }
18687     }
18688     return;
18689   case 'J':
18690     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18691       if (C->getZExtValue() <= 63) {
18692         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18693         break;
18694       }
18695     }
18696     return;
18697   case 'K':
18698     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18699       if (isInt<8>(C->getSExtValue())) {
18700         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18701         break;
18702       }
18703     }
18704     return;
18705   case 'N':
18706     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18707       if (C->getZExtValue() <= 255) {
18708         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18709         break;
18710       }
18711     }
18712     return;
18713   case 'e': {
18714     // 32-bit signed value
18715     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18716       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18717                                            C->getSExtValue())) {
18718         // Widen to 64 bits here to get it sign extended.
18719         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18720         break;
18721       }
18722     // FIXME gcc accepts some relocatable values here too, but only in certain
18723     // memory models; it's complicated.
18724     }
18725     return;
18726   }
18727   case 'Z': {
18728     // 32-bit unsigned value
18729     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18730       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18731                                            C->getZExtValue())) {
18732         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18733         break;
18734       }
18735     }
18736     // FIXME gcc accepts some relocatable values here too, but only in certain
18737     // memory models; it's complicated.
18738     return;
18739   }
18740   case 'i': {
18741     // Literal immediates are always ok.
18742     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18743       // Widen to 64 bits here to get it sign extended.
18744       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18745       break;
18746     }
18747
18748     // In any sort of PIC mode addresses need to be computed at runtime by
18749     // adding in a register or some sort of table lookup.  These can't
18750     // be used as immediates.
18751     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18752       return;
18753
18754     // If we are in non-pic codegen mode, we allow the address of a global (with
18755     // an optional displacement) to be used with 'i'.
18756     GlobalAddressSDNode *GA = 0;
18757     int64_t Offset = 0;
18758
18759     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18760     while (1) {
18761       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18762         Offset += GA->getOffset();
18763         break;
18764       } else if (Op.getOpcode() == ISD::ADD) {
18765         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18766           Offset += C->getZExtValue();
18767           Op = Op.getOperand(0);
18768           continue;
18769         }
18770       } else if (Op.getOpcode() == ISD::SUB) {
18771         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18772           Offset += -C->getZExtValue();
18773           Op = Op.getOperand(0);
18774           continue;
18775         }
18776       }
18777
18778       // Otherwise, this isn't something we can handle, reject it.
18779       return;
18780     }
18781
18782     const GlobalValue *GV = GA->getGlobal();
18783     // If we require an extra load to get this address, as in PIC mode, we
18784     // can't accept it.
18785     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18786                                                         getTargetMachine())))
18787       return;
18788
18789     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
18790                                         GA->getValueType(0), Offset);
18791     break;
18792   }
18793   }
18794
18795   if (Result.getNode()) {
18796     Ops.push_back(Result);
18797     return;
18798   }
18799   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18800 }
18801
18802 std::pair<unsigned, const TargetRegisterClass*>
18803 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18804                                                 MVT VT) const {
18805   // First, see if this is a constraint that directly corresponds to an LLVM
18806   // register class.
18807   if (Constraint.size() == 1) {
18808     // GCC Constraint Letters
18809     switch (Constraint[0]) {
18810     default: break;
18811       // TODO: Slight differences here in allocation order and leaving
18812       // RIP in the class. Do they matter any more here than they do
18813       // in the normal allocation?
18814     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18815       if (Subtarget->is64Bit()) {
18816         if (VT == MVT::i32 || VT == MVT::f32)
18817           return std::make_pair(0U, &X86::GR32RegClass);
18818         if (VT == MVT::i16)
18819           return std::make_pair(0U, &X86::GR16RegClass);
18820         if (VT == MVT::i8 || VT == MVT::i1)
18821           return std::make_pair(0U, &X86::GR8RegClass);
18822         if (VT == MVT::i64 || VT == MVT::f64)
18823           return std::make_pair(0U, &X86::GR64RegClass);
18824         break;
18825       }
18826       // 32-bit fallthrough
18827     case 'Q':   // Q_REGS
18828       if (VT == MVT::i32 || VT == MVT::f32)
18829         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18830       if (VT == MVT::i16)
18831         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18832       if (VT == MVT::i8 || VT == MVT::i1)
18833         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18834       if (VT == MVT::i64)
18835         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18836       break;
18837     case 'r':   // GENERAL_REGS
18838     case 'l':   // INDEX_REGS
18839       if (VT == MVT::i8 || VT == MVT::i1)
18840         return std::make_pair(0U, &X86::GR8RegClass);
18841       if (VT == MVT::i16)
18842         return std::make_pair(0U, &X86::GR16RegClass);
18843       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18844         return std::make_pair(0U, &X86::GR32RegClass);
18845       return std::make_pair(0U, &X86::GR64RegClass);
18846     case 'R':   // LEGACY_REGS
18847       if (VT == MVT::i8 || VT == MVT::i1)
18848         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18849       if (VT == MVT::i16)
18850         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18851       if (VT == MVT::i32 || !Subtarget->is64Bit())
18852         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18853       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18854     case 'f':  // FP Stack registers.
18855       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18856       // value to the correct fpstack register class.
18857       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18858         return std::make_pair(0U, &X86::RFP32RegClass);
18859       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18860         return std::make_pair(0U, &X86::RFP64RegClass);
18861       return std::make_pair(0U, &X86::RFP80RegClass);
18862     case 'y':   // MMX_REGS if MMX allowed.
18863       if (!Subtarget->hasMMX()) break;
18864       return std::make_pair(0U, &X86::VR64RegClass);
18865     case 'Y':   // SSE_REGS if SSE2 allowed
18866       if (!Subtarget->hasSSE2()) break;
18867       // FALL THROUGH.
18868     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18869       if (!Subtarget->hasSSE1()) break;
18870
18871       switch (VT.SimpleTy) {
18872       default: break;
18873       // Scalar SSE types.
18874       case MVT::f32:
18875       case MVT::i32:
18876         return std::make_pair(0U, &X86::FR32RegClass);
18877       case MVT::f64:
18878       case MVT::i64:
18879         return std::make_pair(0U, &X86::FR64RegClass);
18880       // Vector types.
18881       case MVT::v16i8:
18882       case MVT::v8i16:
18883       case MVT::v4i32:
18884       case MVT::v2i64:
18885       case MVT::v4f32:
18886       case MVT::v2f64:
18887         return std::make_pair(0U, &X86::VR128RegClass);
18888       // AVX types.
18889       case MVT::v32i8:
18890       case MVT::v16i16:
18891       case MVT::v8i32:
18892       case MVT::v4i64:
18893       case MVT::v8f32:
18894       case MVT::v4f64:
18895         return std::make_pair(0U, &X86::VR256RegClass);
18896       case MVT::v8f64:
18897       case MVT::v16f32:
18898       case MVT::v16i32:
18899       case MVT::v8i64:
18900         return std::make_pair(0U, &X86::VR512RegClass);
18901       }
18902       break;
18903     }
18904   }
18905
18906   // Use the default implementation in TargetLowering to convert the register
18907   // constraint into a member of a register class.
18908   std::pair<unsigned, const TargetRegisterClass*> Res;
18909   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18910
18911   // Not found as a standard register?
18912   if (Res.second == 0) {
18913     // Map st(0) -> st(7) -> ST0
18914     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18915         tolower(Constraint[1]) == 's' &&
18916         tolower(Constraint[2]) == 't' &&
18917         Constraint[3] == '(' &&
18918         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18919         Constraint[5] == ')' &&
18920         Constraint[6] == '}') {
18921
18922       Res.first = X86::ST0+Constraint[4]-'0';
18923       Res.second = &X86::RFP80RegClass;
18924       return Res;
18925     }
18926
18927     // GCC allows "st(0)" to be called just plain "st".
18928     if (StringRef("{st}").equals_lower(Constraint)) {
18929       Res.first = X86::ST0;
18930       Res.second = &X86::RFP80RegClass;
18931       return Res;
18932     }
18933
18934     // flags -> EFLAGS
18935     if (StringRef("{flags}").equals_lower(Constraint)) {
18936       Res.first = X86::EFLAGS;
18937       Res.second = &X86::CCRRegClass;
18938       return Res;
18939     }
18940
18941     // 'A' means EAX + EDX.
18942     if (Constraint == "A") {
18943       Res.first = X86::EAX;
18944       Res.second = &X86::GR32_ADRegClass;
18945       return Res;
18946     }
18947     return Res;
18948   }
18949
18950   // Otherwise, check to see if this is a register class of the wrong value
18951   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18952   // turn into {ax},{dx}.
18953   if (Res.second->hasType(VT))
18954     return Res;   // Correct type already, nothing to do.
18955
18956   // All of the single-register GCC register classes map their values onto
18957   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18958   // really want an 8-bit or 32-bit register, map to the appropriate register
18959   // class and return the appropriate register.
18960   if (Res.second == &X86::GR16RegClass) {
18961     if (VT == MVT::i8 || VT == MVT::i1) {
18962       unsigned DestReg = 0;
18963       switch (Res.first) {
18964       default: break;
18965       case X86::AX: DestReg = X86::AL; break;
18966       case X86::DX: DestReg = X86::DL; break;
18967       case X86::CX: DestReg = X86::CL; break;
18968       case X86::BX: DestReg = X86::BL; break;
18969       }
18970       if (DestReg) {
18971         Res.first = DestReg;
18972         Res.second = &X86::GR8RegClass;
18973       }
18974     } else if (VT == MVT::i32 || VT == MVT::f32) {
18975       unsigned DestReg = 0;
18976       switch (Res.first) {
18977       default: break;
18978       case X86::AX: DestReg = X86::EAX; break;
18979       case X86::DX: DestReg = X86::EDX; break;
18980       case X86::CX: DestReg = X86::ECX; break;
18981       case X86::BX: DestReg = X86::EBX; break;
18982       case X86::SI: DestReg = X86::ESI; break;
18983       case X86::DI: DestReg = X86::EDI; break;
18984       case X86::BP: DestReg = X86::EBP; break;
18985       case X86::SP: DestReg = X86::ESP; break;
18986       }
18987       if (DestReg) {
18988         Res.first = DestReg;
18989         Res.second = &X86::GR32RegClass;
18990       }
18991     } else if (VT == MVT::i64 || VT == MVT::f64) {
18992       unsigned DestReg = 0;
18993       switch (Res.first) {
18994       default: break;
18995       case X86::AX: DestReg = X86::RAX; break;
18996       case X86::DX: DestReg = X86::RDX; break;
18997       case X86::CX: DestReg = X86::RCX; break;
18998       case X86::BX: DestReg = X86::RBX; break;
18999       case X86::SI: DestReg = X86::RSI; break;
19000       case X86::DI: DestReg = X86::RDI; break;
19001       case X86::BP: DestReg = X86::RBP; break;
19002       case X86::SP: DestReg = X86::RSP; break;
19003       }
19004       if (DestReg) {
19005         Res.first = DestReg;
19006         Res.second = &X86::GR64RegClass;
19007       }
19008     }
19009   } else if (Res.second == &X86::FR32RegClass ||
19010              Res.second == &X86::FR64RegClass ||
19011              Res.second == &X86::VR128RegClass ||
19012              Res.second == &X86::VR256RegClass ||
19013              Res.second == &X86::FR32XRegClass ||
19014              Res.second == &X86::FR64XRegClass ||
19015              Res.second == &X86::VR128XRegClass ||
19016              Res.second == &X86::VR256XRegClass ||
19017              Res.second == &X86::VR512RegClass) {
19018     // Handle references to XMM physical registers that got mapped into the
19019     // wrong class.  This can happen with constraints like {xmm0} where the
19020     // target independent register mapper will just pick the first match it can
19021     // find, ignoring the required type.
19022
19023     if (VT == MVT::f32 || VT == MVT::i32)
19024       Res.second = &X86::FR32RegClass;
19025     else if (VT == MVT::f64 || VT == MVT::i64)
19026       Res.second = &X86::FR64RegClass;
19027     else if (X86::VR128RegClass.hasType(VT))
19028       Res.second = &X86::VR128RegClass;
19029     else if (X86::VR256RegClass.hasType(VT))
19030       Res.second = &X86::VR256RegClass;
19031     else if (X86::VR512RegClass.hasType(VT))
19032       Res.second = &X86::VR512RegClass;
19033   }
19034
19035   return Res;
19036 }