4e71f368e6ac458f6dbb3e63173e463e6c2ea584
[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::SELECT, VT, Promote);
1438       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1439     }
1440   }// has  AVX-512
1441
1442   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1443   // of this type with custom code.
1444   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1445            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1446     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1447                        Custom);
1448   }
1449
1450   // We want to custom lower some of our intrinsics.
1451   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1452   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1453
1454   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1455   // handle type legalization for these operations here.
1456   //
1457   // FIXME: We really should do custom legalization for addition and
1458   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1459   // than generic legalization for 64-bit multiplication-with-overflow, though.
1460   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1461     // Add/Sub/Mul with overflow operations are custom lowered.
1462     MVT VT = IntVTs[i];
1463     setOperationAction(ISD::SADDO, VT, Custom);
1464     setOperationAction(ISD::UADDO, VT, Custom);
1465     setOperationAction(ISD::SSUBO, VT, Custom);
1466     setOperationAction(ISD::USUBO, VT, Custom);
1467     setOperationAction(ISD::SMULO, VT, Custom);
1468     setOperationAction(ISD::UMULO, VT, Custom);
1469   }
1470
1471   // There are no 8-bit 3-address imul/mul instructions
1472   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1473   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1474
1475   if (!Subtarget->is64Bit()) {
1476     // These libcalls are not available in 32-bit.
1477     setLibcallName(RTLIB::SHL_I128, 0);
1478     setLibcallName(RTLIB::SRL_I128, 0);
1479     setLibcallName(RTLIB::SRA_I128, 0);
1480   }
1481
1482   // Combine sin / cos into one node or libcall if possible.
1483   if (Subtarget->hasSinCos()) {
1484     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1485     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1486     if (Subtarget->isTargetDarwin()) {
1487       // For MacOSX, we don't want to the normal expansion of a libcall to
1488       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1489       // traffic.
1490       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1491       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1492     }
1493   }
1494
1495   // We have target-specific dag combine patterns for the following nodes:
1496   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1497   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1498   setTargetDAGCombine(ISD::VSELECT);
1499   setTargetDAGCombine(ISD::SELECT);
1500   setTargetDAGCombine(ISD::SHL);
1501   setTargetDAGCombine(ISD::SRA);
1502   setTargetDAGCombine(ISD::SRL);
1503   setTargetDAGCombine(ISD::OR);
1504   setTargetDAGCombine(ISD::AND);
1505   setTargetDAGCombine(ISD::ADD);
1506   setTargetDAGCombine(ISD::FADD);
1507   setTargetDAGCombine(ISD::FSUB);
1508   setTargetDAGCombine(ISD::FMA);
1509   setTargetDAGCombine(ISD::SUB);
1510   setTargetDAGCombine(ISD::LOAD);
1511   setTargetDAGCombine(ISD::STORE);
1512   setTargetDAGCombine(ISD::ZERO_EXTEND);
1513   setTargetDAGCombine(ISD::ANY_EXTEND);
1514   setTargetDAGCombine(ISD::SIGN_EXTEND);
1515   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1516   setTargetDAGCombine(ISD::TRUNCATE);
1517   setTargetDAGCombine(ISD::SINT_TO_FP);
1518   setTargetDAGCombine(ISD::SETCC);
1519   if (Subtarget->is64Bit())
1520     setTargetDAGCombine(ISD::MUL);
1521   setTargetDAGCombine(ISD::XOR);
1522
1523   computeRegisterProperties();
1524
1525   // On Darwin, -Os means optimize for size without hurting performance,
1526   // do not reduce the limit.
1527   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1528   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1529   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1530   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1531   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1532   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1533   setPrefLoopAlignment(4); // 2^4 bytes.
1534
1535   // Predictable cmov don't hurt on atom because it's in-order.
1536   PredictableSelectIsExpensive = !Subtarget->isAtom();
1537
1538   setPrefFunctionAlignment(4); // 2^4 bytes.
1539 }
1540
1541 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1542   if (!VT.isVector()) return MVT::i8;
1543   return VT.changeVectorElementTypeToInteger();
1544 }
1545
1546 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1547 /// the desired ByVal argument alignment.
1548 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1549   if (MaxAlign == 16)
1550     return;
1551   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1552     if (VTy->getBitWidth() == 128)
1553       MaxAlign = 16;
1554   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1555     unsigned EltAlign = 0;
1556     getMaxByValAlign(ATy->getElementType(), EltAlign);
1557     if (EltAlign > MaxAlign)
1558       MaxAlign = EltAlign;
1559   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1560     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1561       unsigned EltAlign = 0;
1562       getMaxByValAlign(STy->getElementType(i), EltAlign);
1563       if (EltAlign > MaxAlign)
1564         MaxAlign = EltAlign;
1565       if (MaxAlign == 16)
1566         break;
1567     }
1568   }
1569 }
1570
1571 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1572 /// function arguments in the caller parameter area. For X86, aggregates
1573 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1574 /// are at 4-byte boundaries.
1575 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1576   if (Subtarget->is64Bit()) {
1577     // Max of 8 and alignment of type.
1578     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1579     if (TyAlign > 8)
1580       return TyAlign;
1581     return 8;
1582   }
1583
1584   unsigned Align = 4;
1585   if (Subtarget->hasSSE1())
1586     getMaxByValAlign(Ty, Align);
1587   return Align;
1588 }
1589
1590 /// getOptimalMemOpType - Returns the target specific optimal type for load
1591 /// and store operations as a result of memset, memcpy, and memmove
1592 /// lowering. If DstAlign is zero that means it's safe to destination
1593 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1594 /// means there isn't a need to check it against alignment requirement,
1595 /// probably because the source does not need to be loaded. If 'IsMemset' is
1596 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1597 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1598 /// source is constant so it does not need to be loaded.
1599 /// It returns EVT::Other if the type should be determined using generic
1600 /// target-independent logic.
1601 EVT
1602 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1603                                        unsigned DstAlign, unsigned SrcAlign,
1604                                        bool IsMemset, bool ZeroMemset,
1605                                        bool MemcpyStrSrc,
1606                                        MachineFunction &MF) const {
1607   const Function *F = MF.getFunction();
1608   if ((!IsMemset || ZeroMemset) &&
1609       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1610                                        Attribute::NoImplicitFloat)) {
1611     if (Size >= 16 &&
1612         (Subtarget->isUnalignedMemAccessFast() ||
1613          ((DstAlign == 0 || DstAlign >= 16) &&
1614           (SrcAlign == 0 || SrcAlign >= 16)))) {
1615       if (Size >= 32) {
1616         if (Subtarget->hasInt256())
1617           return MVT::v8i32;
1618         if (Subtarget->hasFp256())
1619           return MVT::v8f32;
1620       }
1621       if (Subtarget->hasSSE2())
1622         return MVT::v4i32;
1623       if (Subtarget->hasSSE1())
1624         return MVT::v4f32;
1625     } else if (!MemcpyStrSrc && Size >= 8 &&
1626                !Subtarget->is64Bit() &&
1627                Subtarget->hasSSE2()) {
1628       // Do not use f64 to lower memcpy if source is string constant. It's
1629       // better to use i32 to avoid the loads.
1630       return MVT::f64;
1631     }
1632   }
1633   if (Subtarget->is64Bit() && Size >= 8)
1634     return MVT::i64;
1635   return MVT::i32;
1636 }
1637
1638 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1639   if (VT == MVT::f32)
1640     return X86ScalarSSEf32;
1641   else if (VT == MVT::f64)
1642     return X86ScalarSSEf64;
1643   return true;
1644 }
1645
1646 bool
1647 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1648   if (Fast)
1649     *Fast = Subtarget->isUnalignedMemAccessFast();
1650   return true;
1651 }
1652
1653 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1654 /// current function.  The returned value is a member of the
1655 /// MachineJumpTableInfo::JTEntryKind enum.
1656 unsigned X86TargetLowering::getJumpTableEncoding() const {
1657   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1658   // symbol.
1659   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1660       Subtarget->isPICStyleGOT())
1661     return MachineJumpTableInfo::EK_Custom32;
1662
1663   // Otherwise, use the normal jump table encoding heuristics.
1664   return TargetLowering::getJumpTableEncoding();
1665 }
1666
1667 const MCExpr *
1668 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1669                                              const MachineBasicBlock *MBB,
1670                                              unsigned uid,MCContext &Ctx) const{
1671   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1672          Subtarget->isPICStyleGOT());
1673   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1674   // entries.
1675   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1676                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1677 }
1678
1679 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1680 /// jumptable.
1681 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1682                                                     SelectionDAG &DAG) const {
1683   if (!Subtarget->is64Bit())
1684     // This doesn't have SDLoc associated with it, but is not really the
1685     // same as a Register.
1686     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1687   return Table;
1688 }
1689
1690 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1691 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1692 /// MCExpr.
1693 const MCExpr *X86TargetLowering::
1694 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1695                              MCContext &Ctx) const {
1696   // X86-64 uses RIP relative addressing based on the jump table label.
1697   if (Subtarget->isPICStyleRIPRel())
1698     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1699
1700   // Otherwise, the reference is relative to the PIC base.
1701   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1702 }
1703
1704 // FIXME: Why this routine is here? Move to RegInfo!
1705 std::pair<const TargetRegisterClass*, uint8_t>
1706 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1707   const TargetRegisterClass *RRC = 0;
1708   uint8_t Cost = 1;
1709   switch (VT.SimpleTy) {
1710   default:
1711     return TargetLowering::findRepresentativeClass(VT);
1712   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1713     RRC = Subtarget->is64Bit() ?
1714       (const TargetRegisterClass*)&X86::GR64RegClass :
1715       (const TargetRegisterClass*)&X86::GR32RegClass;
1716     break;
1717   case MVT::x86mmx:
1718     RRC = &X86::VR64RegClass;
1719     break;
1720   case MVT::f32: case MVT::f64:
1721   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1722   case MVT::v4f32: case MVT::v2f64:
1723   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1724   case MVT::v4f64:
1725     RRC = &X86::VR128RegClass;
1726     break;
1727   }
1728   return std::make_pair(RRC, Cost);
1729 }
1730
1731 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1732                                                unsigned &Offset) const {
1733   if (!Subtarget->isTargetLinux())
1734     return false;
1735
1736   if (Subtarget->is64Bit()) {
1737     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1738     Offset = 0x28;
1739     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1740       AddressSpace = 256;
1741     else
1742       AddressSpace = 257;
1743   } else {
1744     // %gs:0x14 on i386
1745     Offset = 0x14;
1746     AddressSpace = 256;
1747   }
1748   return true;
1749 }
1750
1751 //===----------------------------------------------------------------------===//
1752 //               Return Value Calling Convention Implementation
1753 //===----------------------------------------------------------------------===//
1754
1755 #include "X86GenCallingConv.inc"
1756
1757 bool
1758 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1759                                   MachineFunction &MF, bool isVarArg,
1760                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1761                         LLVMContext &Context) const {
1762   SmallVector<CCValAssign, 16> RVLocs;
1763   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1764                  RVLocs, Context);
1765   return CCInfo.CheckReturn(Outs, RetCC_X86);
1766 }
1767
1768 SDValue
1769 X86TargetLowering::LowerReturn(SDValue Chain,
1770                                CallingConv::ID CallConv, bool isVarArg,
1771                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1772                                const SmallVectorImpl<SDValue> &OutVals,
1773                                SDLoc dl, SelectionDAG &DAG) const {
1774   MachineFunction &MF = DAG.getMachineFunction();
1775   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1776
1777   SmallVector<CCValAssign, 16> RVLocs;
1778   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1779                  RVLocs, *DAG.getContext());
1780   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1781
1782   SDValue Flag;
1783   SmallVector<SDValue, 6> RetOps;
1784   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1785   // Operand #1 = Bytes To Pop
1786   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1787                    MVT::i16));
1788
1789   // Copy the result values into the output registers.
1790   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1791     CCValAssign &VA = RVLocs[i];
1792     assert(VA.isRegLoc() && "Can only return in registers!");
1793     SDValue ValToCopy = OutVals[i];
1794     EVT ValVT = ValToCopy.getValueType();
1795
1796     // Promote values to the appropriate types
1797     if (VA.getLocInfo() == CCValAssign::SExt)
1798       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1799     else if (VA.getLocInfo() == CCValAssign::ZExt)
1800       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1801     else if (VA.getLocInfo() == CCValAssign::AExt)
1802       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1803     else if (VA.getLocInfo() == CCValAssign::BCvt)
1804       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1805
1806     // If this is x86-64, and we disabled SSE, we can't return FP values,
1807     // or SSE or MMX vectors.
1808     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1809          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1810           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1811       report_fatal_error("SSE register return with SSE disabled");
1812     }
1813     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1814     // llvm-gcc has never done it right and no one has noticed, so this
1815     // should be OK for now.
1816     if (ValVT == MVT::f64 &&
1817         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1818       report_fatal_error("SSE2 register return with SSE2 disabled");
1819
1820     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1821     // the RET instruction and handled by the FP Stackifier.
1822     if (VA.getLocReg() == X86::ST0 ||
1823         VA.getLocReg() == X86::ST1) {
1824       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1825       // change the value to the FP stack register class.
1826       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1827         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1828       RetOps.push_back(ValToCopy);
1829       // Don't emit a copytoreg.
1830       continue;
1831     }
1832
1833     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1834     // which is returned in RAX / RDX.
1835     if (Subtarget->is64Bit()) {
1836       if (ValVT == MVT::x86mmx) {
1837         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1838           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1839           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1840                                   ValToCopy);
1841           // If we don't have SSE2 available, convert to v4f32 so the generated
1842           // register is legal.
1843           if (!Subtarget->hasSSE2())
1844             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1845         }
1846       }
1847     }
1848
1849     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1850     Flag = Chain.getValue(1);
1851     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1852   }
1853
1854   // The x86-64 ABIs require that for returning structs by value we copy
1855   // the sret argument into %rax/%eax (depending on ABI) for the return.
1856   // Win32 requires us to put the sret argument to %eax as well.
1857   // We saved the argument into a virtual register in the entry block,
1858   // so now we copy the value out and into %rax/%eax.
1859   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1860       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1861     MachineFunction &MF = DAG.getMachineFunction();
1862     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1863     unsigned Reg = FuncInfo->getSRetReturnReg();
1864     assert(Reg &&
1865            "SRetReturnReg should have been set in LowerFormalArguments().");
1866     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1867
1868     unsigned RetValReg
1869         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1870           X86::RAX : X86::EAX;
1871     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1872     Flag = Chain.getValue(1);
1873
1874     // RAX/EAX now acts like a return value.
1875     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1876   }
1877
1878   RetOps[0] = Chain;  // Update chain.
1879
1880   // Add the flag if we have it.
1881   if (Flag.getNode())
1882     RetOps.push_back(Flag);
1883
1884   return DAG.getNode(X86ISD::RET_FLAG, dl,
1885                      MVT::Other, &RetOps[0], RetOps.size());
1886 }
1887
1888 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1889   if (N->getNumValues() != 1)
1890     return false;
1891   if (!N->hasNUsesOfValue(1, 0))
1892     return false;
1893
1894   SDValue TCChain = Chain;
1895   SDNode *Copy = *N->use_begin();
1896   if (Copy->getOpcode() == ISD::CopyToReg) {
1897     // If the copy has a glue operand, we conservatively assume it isn't safe to
1898     // perform a tail call.
1899     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1900       return false;
1901     TCChain = Copy->getOperand(0);
1902   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1903     return false;
1904
1905   bool HasRet = false;
1906   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1907        UI != UE; ++UI) {
1908     if (UI->getOpcode() != X86ISD::RET_FLAG)
1909       return false;
1910     HasRet = true;
1911   }
1912
1913   if (!HasRet)
1914     return false;
1915
1916   Chain = TCChain;
1917   return true;
1918 }
1919
1920 MVT
1921 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1922                                             ISD::NodeType ExtendKind) const {
1923   MVT ReturnMVT;
1924   // TODO: Is this also valid on 32-bit?
1925   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1926     ReturnMVT = MVT::i8;
1927   else
1928     ReturnMVT = MVT::i32;
1929
1930   MVT MinVT = getRegisterType(ReturnMVT);
1931   return VT.bitsLT(MinVT) ? MinVT : VT;
1932 }
1933
1934 /// LowerCallResult - Lower the result values of a call into the
1935 /// appropriate copies out of appropriate physical registers.
1936 ///
1937 SDValue
1938 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1939                                    CallingConv::ID CallConv, bool isVarArg,
1940                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1941                                    SDLoc dl, SelectionDAG &DAG,
1942                                    SmallVectorImpl<SDValue> &InVals) const {
1943
1944   // Assign locations to each value returned by this call.
1945   SmallVector<CCValAssign, 16> RVLocs;
1946   bool Is64Bit = Subtarget->is64Bit();
1947   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1948                  getTargetMachine(), RVLocs, *DAG.getContext());
1949   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1950
1951   // Copy all of the result registers out of their specified physreg.
1952   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1953     CCValAssign &VA = RVLocs[i];
1954     EVT CopyVT = VA.getValVT();
1955
1956     // If this is x86-64, and we disabled SSE, we can't return FP values
1957     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1958         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1959       report_fatal_error("SSE register return with SSE disabled");
1960     }
1961
1962     SDValue Val;
1963
1964     // If this is a call to a function that returns an fp value on the floating
1965     // point stack, we must guarantee the value is popped from the stack, so
1966     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1967     // if the return value is not used. We use the FpPOP_RETVAL instruction
1968     // instead.
1969     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1970       // If we prefer to use the value in xmm registers, copy it out as f80 and
1971       // use a truncate to move it from fp stack reg to xmm reg.
1972       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1973       SDValue Ops[] = { Chain, InFlag };
1974       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1975                                          MVT::Other, MVT::Glue, Ops), 1);
1976       Val = Chain.getValue(0);
1977
1978       // Round the f80 to the right size, which also moves it to the appropriate
1979       // xmm register.
1980       if (CopyVT != VA.getValVT())
1981         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1982                           // This truncation won't change the value.
1983                           DAG.getIntPtrConstant(1));
1984     } else {
1985       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1986                                  CopyVT, InFlag).getValue(1);
1987       Val = Chain.getValue(0);
1988     }
1989     InFlag = Chain.getValue(2);
1990     InVals.push_back(Val);
1991   }
1992
1993   return Chain;
1994 }
1995
1996 //===----------------------------------------------------------------------===//
1997 //                C & StdCall & Fast Calling Convention implementation
1998 //===----------------------------------------------------------------------===//
1999 //  StdCall calling convention seems to be standard for many Windows' API
2000 //  routines and around. It differs from C calling convention just a little:
2001 //  callee should clean up the stack, not caller. Symbols should be also
2002 //  decorated in some fancy way :) It doesn't support any vector arguments.
2003 //  For info on fast calling convention see Fast Calling Convention (tail call)
2004 //  implementation LowerX86_32FastCCCallTo.
2005
2006 /// CallIsStructReturn - Determines whether a call uses struct return
2007 /// semantics.
2008 enum StructReturnType {
2009   NotStructReturn,
2010   RegStructReturn,
2011   StackStructReturn
2012 };
2013 static StructReturnType
2014 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2015   if (Outs.empty())
2016     return NotStructReturn;
2017
2018   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2019   if (!Flags.isSRet())
2020     return NotStructReturn;
2021   if (Flags.isInReg())
2022     return RegStructReturn;
2023   return StackStructReturn;
2024 }
2025
2026 /// ArgsAreStructReturn - Determines whether a function uses struct
2027 /// return semantics.
2028 static StructReturnType
2029 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2030   if (Ins.empty())
2031     return NotStructReturn;
2032
2033   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2034   if (!Flags.isSRet())
2035     return NotStructReturn;
2036   if (Flags.isInReg())
2037     return RegStructReturn;
2038   return StackStructReturn;
2039 }
2040
2041 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2042 /// by "Src" to address "Dst" with size and alignment information specified by
2043 /// the specific parameter attribute. The copy will be passed as a byval
2044 /// function parameter.
2045 static SDValue
2046 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2047                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2048                           SDLoc dl) {
2049   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2050
2051   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2052                        /*isVolatile*/false, /*AlwaysInline=*/true,
2053                        MachinePointerInfo(), MachinePointerInfo());
2054 }
2055
2056 /// IsTailCallConvention - Return true if the calling convention is one that
2057 /// supports tail call optimization.
2058 static bool IsTailCallConvention(CallingConv::ID CC) {
2059   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2060           CC == CallingConv::HiPE);
2061 }
2062
2063 /// \brief Return true if the calling convention is a C calling convention.
2064 static bool IsCCallConvention(CallingConv::ID CC) {
2065   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2066           CC == CallingConv::X86_64_SysV);
2067 }
2068
2069 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2070   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2071     return false;
2072
2073   CallSite CS(CI);
2074   CallingConv::ID CalleeCC = CS.getCallingConv();
2075   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2076     return false;
2077
2078   return true;
2079 }
2080
2081 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2082 /// a tailcall target by changing its ABI.
2083 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2084                                    bool GuaranteedTailCallOpt) {
2085   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2086 }
2087
2088 SDValue
2089 X86TargetLowering::LowerMemArgument(SDValue Chain,
2090                                     CallingConv::ID CallConv,
2091                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2092                                     SDLoc dl, SelectionDAG &DAG,
2093                                     const CCValAssign &VA,
2094                                     MachineFrameInfo *MFI,
2095                                     unsigned i) const {
2096   // Create the nodes corresponding to a load from this parameter slot.
2097   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2098   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2099                               getTargetMachine().Options.GuaranteedTailCallOpt);
2100   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2101   EVT ValVT;
2102
2103   // If value is passed by pointer we have address passed instead of the value
2104   // itself.
2105   if (VA.getLocInfo() == CCValAssign::Indirect)
2106     ValVT = VA.getLocVT();
2107   else
2108     ValVT = VA.getValVT();
2109
2110   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2111   // changed with more analysis.
2112   // In case of tail call optimization mark all arguments mutable. Since they
2113   // could be overwritten by lowering of arguments in case of a tail call.
2114   if (Flags.isByVal()) {
2115     unsigned Bytes = Flags.getByValSize();
2116     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2117     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2118     return DAG.getFrameIndex(FI, getPointerTy());
2119   } else {
2120     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2121                                     VA.getLocMemOffset(), isImmutable);
2122     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2123     return DAG.getLoad(ValVT, dl, Chain, FIN,
2124                        MachinePointerInfo::getFixedStack(FI),
2125                        false, false, false, 0);
2126   }
2127 }
2128
2129 SDValue
2130 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2131                                         CallingConv::ID CallConv,
2132                                         bool isVarArg,
2133                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2134                                         SDLoc dl,
2135                                         SelectionDAG &DAG,
2136                                         SmallVectorImpl<SDValue> &InVals)
2137                                           const {
2138   MachineFunction &MF = DAG.getMachineFunction();
2139   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2140
2141   const Function* Fn = MF.getFunction();
2142   if (Fn->hasExternalLinkage() &&
2143       Subtarget->isTargetCygMing() &&
2144       Fn->getName() == "main")
2145     FuncInfo->setForceFramePointer(true);
2146
2147   MachineFrameInfo *MFI = MF.getFrameInfo();
2148   bool Is64Bit = Subtarget->is64Bit();
2149   bool IsWindows = Subtarget->isTargetWindows();
2150   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2151
2152   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2153          "Var args not supported with calling convention fastcc, ghc or hipe");
2154
2155   // Assign locations to all of the incoming arguments.
2156   SmallVector<CCValAssign, 16> ArgLocs;
2157   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2158                  ArgLocs, *DAG.getContext());
2159
2160   // Allocate shadow area for Win64
2161   if (IsWin64)
2162     CCInfo.AllocateStack(32, 8);
2163
2164   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2165
2166   unsigned LastVal = ~0U;
2167   SDValue ArgValue;
2168   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2169     CCValAssign &VA = ArgLocs[i];
2170     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2171     // places.
2172     assert(VA.getValNo() != LastVal &&
2173            "Don't support value assigned to multiple locs yet");
2174     (void)LastVal;
2175     LastVal = VA.getValNo();
2176
2177     if (VA.isRegLoc()) {
2178       EVT RegVT = VA.getLocVT();
2179       const TargetRegisterClass *RC;
2180       if (RegVT == MVT::i32)
2181         RC = &X86::GR32RegClass;
2182       else if (Is64Bit && RegVT == MVT::i64)
2183         RC = &X86::GR64RegClass;
2184       else if (RegVT == MVT::f32)
2185         RC = &X86::FR32RegClass;
2186       else if (RegVT == MVT::f64)
2187         RC = &X86::FR64RegClass;
2188       else if (RegVT.is512BitVector())
2189         RC = &X86::VR512RegClass;
2190       else if (RegVT.is256BitVector())
2191         RC = &X86::VR256RegClass;
2192       else if (RegVT.is128BitVector())
2193         RC = &X86::VR128RegClass;
2194       else if (RegVT == MVT::x86mmx)
2195         RC = &X86::VR64RegClass;
2196       else if (RegVT == MVT::v8i1)
2197         RC = &X86::VK8RegClass;
2198       else if (RegVT == MVT::v16i1)
2199         RC = &X86::VK16RegClass;
2200       else
2201         llvm_unreachable("Unknown argument type!");
2202
2203       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2204       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2205
2206       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2207       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2208       // right size.
2209       if (VA.getLocInfo() == CCValAssign::SExt)
2210         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2211                                DAG.getValueType(VA.getValVT()));
2212       else if (VA.getLocInfo() == CCValAssign::ZExt)
2213         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2214                                DAG.getValueType(VA.getValVT()));
2215       else if (VA.getLocInfo() == CCValAssign::BCvt)
2216         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2217
2218       if (VA.isExtInLoc()) {
2219         // Handle MMX values passed in XMM regs.
2220         if (RegVT.isVector())
2221           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2222         else
2223           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2224       }
2225     } else {
2226       assert(VA.isMemLoc());
2227       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2228     }
2229
2230     // If value is passed via pointer - do a load.
2231     if (VA.getLocInfo() == CCValAssign::Indirect)
2232       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2233                              MachinePointerInfo(), false, false, false, 0);
2234
2235     InVals.push_back(ArgValue);
2236   }
2237
2238   // The x86-64 ABIs require that for returning structs by value we copy
2239   // the sret argument into %rax/%eax (depending on ABI) for the return.
2240   // Win32 requires us to put the sret argument to %eax as well.
2241   // Save the argument into a virtual register so that we can access it
2242   // from the return points.
2243   if (MF.getFunction()->hasStructRetAttr() &&
2244       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2245     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2246     unsigned Reg = FuncInfo->getSRetReturnReg();
2247     if (!Reg) {
2248       MVT PtrTy = getPointerTy();
2249       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2250       FuncInfo->setSRetReturnReg(Reg);
2251     }
2252     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2253     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2254   }
2255
2256   unsigned StackSize = CCInfo.getNextStackOffset();
2257   // Align stack specially for tail calls.
2258   if (FuncIsMadeTailCallSafe(CallConv,
2259                              MF.getTarget().Options.GuaranteedTailCallOpt))
2260     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2261
2262   // If the function takes variable number of arguments, make a frame index for
2263   // the start of the first vararg value... for expansion of llvm.va_start.
2264   if (isVarArg) {
2265     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2266                     CallConv != CallingConv::X86_ThisCall)) {
2267       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2268     }
2269     if (Is64Bit) {
2270       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2271
2272       // FIXME: We should really autogenerate these arrays
2273       static const uint16_t GPR64ArgRegsWin64[] = {
2274         X86::RCX, X86::RDX, X86::R8,  X86::R9
2275       };
2276       static const uint16_t GPR64ArgRegs64Bit[] = {
2277         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2278       };
2279       static const uint16_t XMMArgRegs64Bit[] = {
2280         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2281         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2282       };
2283       const uint16_t *GPR64ArgRegs;
2284       unsigned NumXMMRegs = 0;
2285
2286       if (IsWin64) {
2287         // The XMM registers which might contain var arg parameters are shadowed
2288         // in their paired GPR.  So we only need to save the GPR to their home
2289         // slots.
2290         TotalNumIntRegs = 4;
2291         GPR64ArgRegs = GPR64ArgRegsWin64;
2292       } else {
2293         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2294         GPR64ArgRegs = GPR64ArgRegs64Bit;
2295
2296         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2297                                                 TotalNumXMMRegs);
2298       }
2299       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2300                                                        TotalNumIntRegs);
2301
2302       bool NoImplicitFloatOps = Fn->getAttributes().
2303         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2304       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2305              "SSE register cannot be used when SSE is disabled!");
2306       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2307                NoImplicitFloatOps) &&
2308              "SSE register cannot be used when SSE is disabled!");
2309       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2310           !Subtarget->hasSSE1())
2311         // Kernel mode asks for SSE to be disabled, so don't push them
2312         // on the stack.
2313         TotalNumXMMRegs = 0;
2314
2315       if (IsWin64) {
2316         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2317         // Get to the caller-allocated home save location.  Add 8 to account
2318         // for the return address.
2319         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2320         FuncInfo->setRegSaveFrameIndex(
2321           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2322         // Fixup to set vararg frame on shadow area (4 x i64).
2323         if (NumIntRegs < 4)
2324           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2325       } else {
2326         // For X86-64, if there are vararg parameters that are passed via
2327         // registers, then we must store them to their spots on the stack so
2328         // they may be loaded by deferencing the result of va_next.
2329         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2330         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2331         FuncInfo->setRegSaveFrameIndex(
2332           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2333                                false));
2334       }
2335
2336       // Store the integer parameter registers.
2337       SmallVector<SDValue, 8> MemOps;
2338       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2339                                         getPointerTy());
2340       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2341       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2342         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2343                                   DAG.getIntPtrConstant(Offset));
2344         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2345                                      &X86::GR64RegClass);
2346         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2347         SDValue Store =
2348           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2349                        MachinePointerInfo::getFixedStack(
2350                          FuncInfo->getRegSaveFrameIndex(), Offset),
2351                        false, false, 0);
2352         MemOps.push_back(Store);
2353         Offset += 8;
2354       }
2355
2356       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2357         // Now store the XMM (fp + vector) parameter registers.
2358         SmallVector<SDValue, 11> SaveXMMOps;
2359         SaveXMMOps.push_back(Chain);
2360
2361         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2362         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2363         SaveXMMOps.push_back(ALVal);
2364
2365         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2366                                FuncInfo->getRegSaveFrameIndex()));
2367         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2368                                FuncInfo->getVarArgsFPOffset()));
2369
2370         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2371           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2372                                        &X86::VR128RegClass);
2373           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2374           SaveXMMOps.push_back(Val);
2375         }
2376         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2377                                      MVT::Other,
2378                                      &SaveXMMOps[0], SaveXMMOps.size()));
2379       }
2380
2381       if (!MemOps.empty())
2382         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2383                             &MemOps[0], MemOps.size());
2384     }
2385   }
2386
2387   // Some CCs need callee pop.
2388   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2389                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2390     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2391   } else {
2392     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2393     // If this is an sret function, the return should pop the hidden pointer.
2394     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2395         argsAreStructReturn(Ins) == StackStructReturn)
2396       FuncInfo->setBytesToPopOnReturn(4);
2397   }
2398
2399   if (!Is64Bit) {
2400     // RegSaveFrameIndex is X86-64 only.
2401     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2402     if (CallConv == CallingConv::X86_FastCall ||
2403         CallConv == CallingConv::X86_ThisCall)
2404       // fastcc functions can't have varargs.
2405       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2406   }
2407
2408   FuncInfo->setArgumentStackSize(StackSize);
2409
2410   return Chain;
2411 }
2412
2413 SDValue
2414 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2415                                     SDValue StackPtr, SDValue Arg,
2416                                     SDLoc dl, SelectionDAG &DAG,
2417                                     const CCValAssign &VA,
2418                                     ISD::ArgFlagsTy Flags) const {
2419   unsigned LocMemOffset = VA.getLocMemOffset();
2420   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2421   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2422   if (Flags.isByVal())
2423     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2424
2425   return DAG.getStore(Chain, dl, Arg, PtrOff,
2426                       MachinePointerInfo::getStack(LocMemOffset),
2427                       false, false, 0);
2428 }
2429
2430 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2431 /// optimization is performed and it is required.
2432 SDValue
2433 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2434                                            SDValue &OutRetAddr, SDValue Chain,
2435                                            bool IsTailCall, bool Is64Bit,
2436                                            int FPDiff, SDLoc dl) const {
2437   // Adjust the Return address stack slot.
2438   EVT VT = getPointerTy();
2439   OutRetAddr = getReturnAddressFrameIndex(DAG);
2440
2441   // Load the "old" Return address.
2442   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2443                            false, false, false, 0);
2444   return SDValue(OutRetAddr.getNode(), 1);
2445 }
2446
2447 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2448 /// optimization is performed and it is required (FPDiff!=0).
2449 static SDValue
2450 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2451                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2452                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2453   // Store the return address to the appropriate stack slot.
2454   if (!FPDiff) return Chain;
2455   // Calculate the new stack slot for the return address.
2456   int NewReturnAddrFI =
2457     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2458                                          false);
2459   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2460   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2461                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2462                        false, false, 0);
2463   return Chain;
2464 }
2465
2466 SDValue
2467 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2468                              SmallVectorImpl<SDValue> &InVals) const {
2469   SelectionDAG &DAG                     = CLI.DAG;
2470   SDLoc &dl                             = CLI.DL;
2471   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2472   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2473   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2474   SDValue Chain                         = CLI.Chain;
2475   SDValue Callee                        = CLI.Callee;
2476   CallingConv::ID CallConv              = CLI.CallConv;
2477   bool &isTailCall                      = CLI.IsTailCall;
2478   bool isVarArg                         = CLI.IsVarArg;
2479
2480   MachineFunction &MF = DAG.getMachineFunction();
2481   bool Is64Bit        = Subtarget->is64Bit();
2482   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2483   bool IsWindows      = Subtarget->isTargetWindows();
2484   StructReturnType SR = callIsStructReturn(Outs);
2485   bool IsSibcall      = false;
2486
2487   if (MF.getTarget().Options.DisableTailCalls)
2488     isTailCall = false;
2489
2490   if (isTailCall) {
2491     // Check if it's really possible to do a tail call.
2492     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2493                     isVarArg, SR != NotStructReturn,
2494                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2495                     Outs, OutVals, Ins, DAG);
2496
2497     // Sibcalls are automatically detected tailcalls which do not require
2498     // ABI changes.
2499     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2500       IsSibcall = true;
2501
2502     if (isTailCall)
2503       ++NumTailCalls;
2504   }
2505
2506   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2507          "Var args not supported with calling convention fastcc, ghc or hipe");
2508
2509   // Analyze operands of the call, assigning locations to each operand.
2510   SmallVector<CCValAssign, 16> ArgLocs;
2511   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2512                  ArgLocs, *DAG.getContext());
2513
2514   // Allocate shadow area for Win64
2515   if (IsWin64)
2516     CCInfo.AllocateStack(32, 8);
2517
2518   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2519
2520   // Get a count of how many bytes are to be pushed on the stack.
2521   unsigned NumBytes = CCInfo.getNextStackOffset();
2522   if (IsSibcall)
2523     // This is a sibcall. The memory operands are available in caller's
2524     // own caller's stack.
2525     NumBytes = 0;
2526   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2527            IsTailCallConvention(CallConv))
2528     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2529
2530   int FPDiff = 0;
2531   if (isTailCall && !IsSibcall) {
2532     // Lower arguments at fp - stackoffset + fpdiff.
2533     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2534     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2535
2536     FPDiff = NumBytesCallerPushed - NumBytes;
2537
2538     // Set the delta of movement of the returnaddr stackslot.
2539     // But only set if delta is greater than previous delta.
2540     if (FPDiff < X86Info->getTCReturnAddrDelta())
2541       X86Info->setTCReturnAddrDelta(FPDiff);
2542   }
2543
2544   if (!IsSibcall)
2545     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2546                                  dl);
2547
2548   SDValue RetAddrFrIdx;
2549   // Load return address for tail calls.
2550   if (isTailCall && FPDiff)
2551     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2552                                     Is64Bit, FPDiff, dl);
2553
2554   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2555   SmallVector<SDValue, 8> MemOpChains;
2556   SDValue StackPtr;
2557
2558   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2559   // of tail call optimization arguments are handle later.
2560   const X86RegisterInfo *RegInfo =
2561     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2562   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2563     CCValAssign &VA = ArgLocs[i];
2564     EVT RegVT = VA.getLocVT();
2565     SDValue Arg = OutVals[i];
2566     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2567     bool isByVal = Flags.isByVal();
2568
2569     // Promote the value if needed.
2570     switch (VA.getLocInfo()) {
2571     default: llvm_unreachable("Unknown loc info!");
2572     case CCValAssign::Full: break;
2573     case CCValAssign::SExt:
2574       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2575       break;
2576     case CCValAssign::ZExt:
2577       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2578       break;
2579     case CCValAssign::AExt:
2580       if (RegVT.is128BitVector()) {
2581         // Special case: passing MMX values in XMM registers.
2582         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2583         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2584         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2585       } else
2586         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2587       break;
2588     case CCValAssign::BCvt:
2589       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2590       break;
2591     case CCValAssign::Indirect: {
2592       // Store the argument.
2593       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2594       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2595       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2596                            MachinePointerInfo::getFixedStack(FI),
2597                            false, false, 0);
2598       Arg = SpillSlot;
2599       break;
2600     }
2601     }
2602
2603     if (VA.isRegLoc()) {
2604       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2605       if (isVarArg && IsWin64) {
2606         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2607         // shadow reg if callee is a varargs function.
2608         unsigned ShadowReg = 0;
2609         switch (VA.getLocReg()) {
2610         case X86::XMM0: ShadowReg = X86::RCX; break;
2611         case X86::XMM1: ShadowReg = X86::RDX; break;
2612         case X86::XMM2: ShadowReg = X86::R8; break;
2613         case X86::XMM3: ShadowReg = X86::R9; break;
2614         }
2615         if (ShadowReg)
2616           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2617       }
2618     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2619       assert(VA.isMemLoc());
2620       if (StackPtr.getNode() == 0)
2621         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2622                                       getPointerTy());
2623       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2624                                              dl, DAG, VA, Flags));
2625     }
2626   }
2627
2628   if (!MemOpChains.empty())
2629     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2630                         &MemOpChains[0], MemOpChains.size());
2631
2632   if (Subtarget->isPICStyleGOT()) {
2633     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2634     // GOT pointer.
2635     if (!isTailCall) {
2636       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2637                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2638     } else {
2639       // If we are tail calling and generating PIC/GOT style code load the
2640       // address of the callee into ECX. The value in ecx is used as target of
2641       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2642       // for tail calls on PIC/GOT architectures. Normally we would just put the
2643       // address of GOT into ebx and then call target@PLT. But for tail calls
2644       // ebx would be restored (since ebx is callee saved) before jumping to the
2645       // target@PLT.
2646
2647       // Note: The actual moving to ECX is done further down.
2648       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2649       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2650           !G->getGlobal()->hasProtectedVisibility())
2651         Callee = LowerGlobalAddress(Callee, DAG);
2652       else if (isa<ExternalSymbolSDNode>(Callee))
2653         Callee = LowerExternalSymbol(Callee, DAG);
2654     }
2655   }
2656
2657   if (Is64Bit && isVarArg && !IsWin64) {
2658     // From AMD64 ABI document:
2659     // For calls that may call functions that use varargs or stdargs
2660     // (prototype-less calls or calls to functions containing ellipsis (...) in
2661     // the declaration) %al is used as hidden argument to specify the number
2662     // of SSE registers used. The contents of %al do not need to match exactly
2663     // the number of registers, but must be an ubound on the number of SSE
2664     // registers used and is in the range 0 - 8 inclusive.
2665
2666     // Count the number of XMM registers allocated.
2667     static const uint16_t XMMArgRegs[] = {
2668       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2669       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2670     };
2671     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2672     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2673            && "SSE registers cannot be used when SSE is disabled");
2674
2675     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2676                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2677   }
2678
2679   // For tail calls lower the arguments to the 'real' stack slot.
2680   if (isTailCall) {
2681     // Force all the incoming stack arguments to be loaded from the stack
2682     // before any new outgoing arguments are stored to the stack, because the
2683     // outgoing stack slots may alias the incoming argument stack slots, and
2684     // the alias isn't otherwise explicit. This is slightly more conservative
2685     // than necessary, because it means that each store effectively depends
2686     // on every argument instead of just those arguments it would clobber.
2687     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2688
2689     SmallVector<SDValue, 8> MemOpChains2;
2690     SDValue FIN;
2691     int FI = 0;
2692     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2693       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2694         CCValAssign &VA = ArgLocs[i];
2695         if (VA.isRegLoc())
2696           continue;
2697         assert(VA.isMemLoc());
2698         SDValue Arg = OutVals[i];
2699         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2700         // Create frame index.
2701         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2702         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2703         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2704         FIN = DAG.getFrameIndex(FI, getPointerTy());
2705
2706         if (Flags.isByVal()) {
2707           // Copy relative to framepointer.
2708           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2709           if (StackPtr.getNode() == 0)
2710             StackPtr = DAG.getCopyFromReg(Chain, dl,
2711                                           RegInfo->getStackRegister(),
2712                                           getPointerTy());
2713           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2714
2715           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2716                                                            ArgChain,
2717                                                            Flags, DAG, dl));
2718         } else {
2719           // Store relative to framepointer.
2720           MemOpChains2.push_back(
2721             DAG.getStore(ArgChain, dl, Arg, FIN,
2722                          MachinePointerInfo::getFixedStack(FI),
2723                          false, false, 0));
2724         }
2725       }
2726     }
2727
2728     if (!MemOpChains2.empty())
2729       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2730                           &MemOpChains2[0], MemOpChains2.size());
2731
2732     // Store the return address to the appropriate stack slot.
2733     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2734                                      getPointerTy(), RegInfo->getSlotSize(),
2735                                      FPDiff, dl);
2736   }
2737
2738   // Build a sequence of copy-to-reg nodes chained together with token chain
2739   // and flag operands which copy the outgoing args into registers.
2740   SDValue InFlag;
2741   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2742     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2743                              RegsToPass[i].second, InFlag);
2744     InFlag = Chain.getValue(1);
2745   }
2746
2747   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2748     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2749     // In the 64-bit large code model, we have to make all calls
2750     // through a register, since the call instruction's 32-bit
2751     // pc-relative offset may not be large enough to hold the whole
2752     // address.
2753   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2754     // If the callee is a GlobalAddress node (quite common, every direct call
2755     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2756     // it.
2757
2758     // We should use extra load for direct calls to dllimported functions in
2759     // non-JIT mode.
2760     const GlobalValue *GV = G->getGlobal();
2761     if (!GV->hasDLLImportLinkage()) {
2762       unsigned char OpFlags = 0;
2763       bool ExtraLoad = false;
2764       unsigned WrapperKind = ISD::DELETED_NODE;
2765
2766       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2767       // external symbols most go through the PLT in PIC mode.  If the symbol
2768       // has hidden or protected visibility, or if it is static or local, then
2769       // we don't need to use the PLT - we can directly call it.
2770       if (Subtarget->isTargetELF() &&
2771           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2772           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2773         OpFlags = X86II::MO_PLT;
2774       } else if (Subtarget->isPICStyleStubAny() &&
2775                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2776                  (!Subtarget->getTargetTriple().isMacOSX() ||
2777                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2778         // PC-relative references to external symbols should go through $stub,
2779         // unless we're building with the leopard linker or later, which
2780         // automatically synthesizes these stubs.
2781         OpFlags = X86II::MO_DARWIN_STUB;
2782       } else if (Subtarget->isPICStyleRIPRel() &&
2783                  isa<Function>(GV) &&
2784                  cast<Function>(GV)->getAttributes().
2785                    hasAttribute(AttributeSet::FunctionIndex,
2786                                 Attribute::NonLazyBind)) {
2787         // If the function is marked as non-lazy, generate an indirect call
2788         // which loads from the GOT directly. This avoids runtime overhead
2789         // at the cost of eager binding (and one extra byte of encoding).
2790         OpFlags = X86II::MO_GOTPCREL;
2791         WrapperKind = X86ISD::WrapperRIP;
2792         ExtraLoad = true;
2793       }
2794
2795       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2796                                           G->getOffset(), OpFlags);
2797
2798       // Add a wrapper if needed.
2799       if (WrapperKind != ISD::DELETED_NODE)
2800         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2801       // Add extra indirection if needed.
2802       if (ExtraLoad)
2803         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2804                              MachinePointerInfo::getGOT(),
2805                              false, false, false, 0);
2806     }
2807   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2808     unsigned char OpFlags = 0;
2809
2810     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2811     // external symbols should go through the PLT.
2812     if (Subtarget->isTargetELF() &&
2813         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2814       OpFlags = X86II::MO_PLT;
2815     } else if (Subtarget->isPICStyleStubAny() &&
2816                (!Subtarget->getTargetTriple().isMacOSX() ||
2817                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2818       // PC-relative references to external symbols should go through $stub,
2819       // unless we're building with the leopard linker or later, which
2820       // automatically synthesizes these stubs.
2821       OpFlags = X86II::MO_DARWIN_STUB;
2822     }
2823
2824     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2825                                          OpFlags);
2826   }
2827
2828   // Returns a chain & a flag for retval copy to use.
2829   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2830   SmallVector<SDValue, 8> Ops;
2831
2832   if (!IsSibcall && isTailCall) {
2833     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2834                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2835     InFlag = Chain.getValue(1);
2836   }
2837
2838   Ops.push_back(Chain);
2839   Ops.push_back(Callee);
2840
2841   if (isTailCall)
2842     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2843
2844   // Add argument registers to the end of the list so that they are known live
2845   // into the call.
2846   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2847     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2848                                   RegsToPass[i].second.getValueType()));
2849
2850   // Add a register mask operand representing the call-preserved registers.
2851   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2852   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2853   assert(Mask && "Missing call preserved mask for calling convention");
2854   Ops.push_back(DAG.getRegisterMask(Mask));
2855
2856   if (InFlag.getNode())
2857     Ops.push_back(InFlag);
2858
2859   if (isTailCall) {
2860     // We used to do:
2861     //// If this is the first return lowered for this function, add the regs
2862     //// to the liveout set for the function.
2863     // This isn't right, although it's probably harmless on x86; liveouts
2864     // should be computed from returns not tail calls.  Consider a void
2865     // function making a tail call to a function returning int.
2866     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2867   }
2868
2869   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2870   InFlag = Chain.getValue(1);
2871
2872   // Create the CALLSEQ_END node.
2873   unsigned NumBytesForCalleeToPush;
2874   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2875                        getTargetMachine().Options.GuaranteedTailCallOpt))
2876     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2877   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2878            SR == StackStructReturn)
2879     // If this is a call to a struct-return function, the callee
2880     // pops the hidden struct pointer, so we have to push it back.
2881     // This is common for Darwin/X86, Linux & Mingw32 targets.
2882     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2883     NumBytesForCalleeToPush = 4;
2884   else
2885     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2886
2887   // Returns a flag for retval copy to use.
2888   if (!IsSibcall) {
2889     Chain = DAG.getCALLSEQ_END(Chain,
2890                                DAG.getIntPtrConstant(NumBytes, true),
2891                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2892                                                      true),
2893                                InFlag, dl);
2894     InFlag = Chain.getValue(1);
2895   }
2896
2897   // Handle result values, copying them out of physregs into vregs that we
2898   // return.
2899   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2900                          Ins, dl, DAG, InVals);
2901 }
2902
2903 //===----------------------------------------------------------------------===//
2904 //                Fast Calling Convention (tail call) implementation
2905 //===----------------------------------------------------------------------===//
2906
2907 //  Like std call, callee cleans arguments, convention except that ECX is
2908 //  reserved for storing the tail called function address. Only 2 registers are
2909 //  free for argument passing (inreg). Tail call optimization is performed
2910 //  provided:
2911 //                * tailcallopt is enabled
2912 //                * caller/callee are fastcc
2913 //  On X86_64 architecture with GOT-style position independent code only local
2914 //  (within module) calls are supported at the moment.
2915 //  To keep the stack aligned according to platform abi the function
2916 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2917 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2918 //  If a tail called function callee has more arguments than the caller the
2919 //  caller needs to make sure that there is room to move the RETADDR to. This is
2920 //  achieved by reserving an area the size of the argument delta right after the
2921 //  original REtADDR, but before the saved framepointer or the spilled registers
2922 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2923 //  stack layout:
2924 //    arg1
2925 //    arg2
2926 //    RETADDR
2927 //    [ new RETADDR
2928 //      move area ]
2929 //    (possible EBP)
2930 //    ESI
2931 //    EDI
2932 //    local1 ..
2933
2934 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2935 /// for a 16 byte align requirement.
2936 unsigned
2937 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2938                                                SelectionDAG& DAG) const {
2939   MachineFunction &MF = DAG.getMachineFunction();
2940   const TargetMachine &TM = MF.getTarget();
2941   const X86RegisterInfo *RegInfo =
2942     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2943   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2944   unsigned StackAlignment = TFI.getStackAlignment();
2945   uint64_t AlignMask = StackAlignment - 1;
2946   int64_t Offset = StackSize;
2947   unsigned SlotSize = RegInfo->getSlotSize();
2948   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2949     // Number smaller than 12 so just add the difference.
2950     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2951   } else {
2952     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2953     Offset = ((~AlignMask) & Offset) + StackAlignment +
2954       (StackAlignment-SlotSize);
2955   }
2956   return Offset;
2957 }
2958
2959 /// MatchingStackOffset - Return true if the given stack call argument is
2960 /// already available in the same position (relatively) of the caller's
2961 /// incoming argument stack.
2962 static
2963 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2964                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2965                          const X86InstrInfo *TII) {
2966   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2967   int FI = INT_MAX;
2968   if (Arg.getOpcode() == ISD::CopyFromReg) {
2969     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2970     if (!TargetRegisterInfo::isVirtualRegister(VR))
2971       return false;
2972     MachineInstr *Def = MRI->getVRegDef(VR);
2973     if (!Def)
2974       return false;
2975     if (!Flags.isByVal()) {
2976       if (!TII->isLoadFromStackSlot(Def, FI))
2977         return false;
2978     } else {
2979       unsigned Opcode = Def->getOpcode();
2980       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2981           Def->getOperand(1).isFI()) {
2982         FI = Def->getOperand(1).getIndex();
2983         Bytes = Flags.getByValSize();
2984       } else
2985         return false;
2986     }
2987   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2988     if (Flags.isByVal())
2989       // ByVal argument is passed in as a pointer but it's now being
2990       // dereferenced. e.g.
2991       // define @foo(%struct.X* %A) {
2992       //   tail call @bar(%struct.X* byval %A)
2993       // }
2994       return false;
2995     SDValue Ptr = Ld->getBasePtr();
2996     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2997     if (!FINode)
2998       return false;
2999     FI = FINode->getIndex();
3000   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3001     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3002     FI = FINode->getIndex();
3003     Bytes = Flags.getByValSize();
3004   } else
3005     return false;
3006
3007   assert(FI != INT_MAX);
3008   if (!MFI->isFixedObjectIndex(FI))
3009     return false;
3010   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3011 }
3012
3013 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3014 /// for tail call optimization. Targets which want to do tail call
3015 /// optimization should implement this function.
3016 bool
3017 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3018                                                      CallingConv::ID CalleeCC,
3019                                                      bool isVarArg,
3020                                                      bool isCalleeStructRet,
3021                                                      bool isCallerStructRet,
3022                                                      Type *RetTy,
3023                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3024                                     const SmallVectorImpl<SDValue> &OutVals,
3025                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3026                                                      SelectionDAG &DAG) const {
3027   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3028     return false;
3029
3030   // If -tailcallopt is specified, make fastcc functions tail-callable.
3031   const MachineFunction &MF = DAG.getMachineFunction();
3032   const Function *CallerF = MF.getFunction();
3033
3034   // If the function return type is x86_fp80 and the callee return type is not,
3035   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3036   // perform a tailcall optimization here.
3037   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3038     return false;
3039
3040   CallingConv::ID CallerCC = CallerF->getCallingConv();
3041   bool CCMatch = CallerCC == CalleeCC;
3042   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3043   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3044
3045   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3046     if (IsTailCallConvention(CalleeCC) && CCMatch)
3047       return true;
3048     return false;
3049   }
3050
3051   // Look for obvious safe cases to perform tail call optimization that do not
3052   // require ABI changes. This is what gcc calls sibcall.
3053
3054   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3055   // emit a special epilogue.
3056   const X86RegisterInfo *RegInfo =
3057     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3058   if (RegInfo->needsStackRealignment(MF))
3059     return false;
3060
3061   // Also avoid sibcall optimization if either caller or callee uses struct
3062   // return semantics.
3063   if (isCalleeStructRet || isCallerStructRet)
3064     return false;
3065
3066   // An stdcall caller is expected to clean up its arguments; the callee
3067   // isn't going to do that.
3068   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
3069     return false;
3070
3071   // Do not sibcall optimize vararg calls unless all arguments are passed via
3072   // registers.
3073   if (isVarArg && !Outs.empty()) {
3074
3075     // Optimizing for varargs on Win64 is unlikely to be safe without
3076     // additional testing.
3077     if (IsCalleeWin64 || IsCallerWin64)
3078       return false;
3079
3080     SmallVector<CCValAssign, 16> ArgLocs;
3081     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3082                    getTargetMachine(), ArgLocs, *DAG.getContext());
3083
3084     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3085     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3086       if (!ArgLocs[i].isRegLoc())
3087         return false;
3088   }
3089
3090   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3091   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3092   // this into a sibcall.
3093   bool Unused = false;
3094   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3095     if (!Ins[i].Used) {
3096       Unused = true;
3097       break;
3098     }
3099   }
3100   if (Unused) {
3101     SmallVector<CCValAssign, 16> RVLocs;
3102     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3103                    getTargetMachine(), RVLocs, *DAG.getContext());
3104     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3105     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3106       CCValAssign &VA = RVLocs[i];
3107       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3108         return false;
3109     }
3110   }
3111
3112   // If the calling conventions do not match, then we'd better make sure the
3113   // results are returned in the same way as what the caller expects.
3114   if (!CCMatch) {
3115     SmallVector<CCValAssign, 16> RVLocs1;
3116     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3117                     getTargetMachine(), RVLocs1, *DAG.getContext());
3118     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3119
3120     SmallVector<CCValAssign, 16> RVLocs2;
3121     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3122                     getTargetMachine(), RVLocs2, *DAG.getContext());
3123     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3124
3125     if (RVLocs1.size() != RVLocs2.size())
3126       return false;
3127     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3128       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3129         return false;
3130       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3131         return false;
3132       if (RVLocs1[i].isRegLoc()) {
3133         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3134           return false;
3135       } else {
3136         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3137           return false;
3138       }
3139     }
3140   }
3141
3142   // If the callee takes no arguments then go on to check the results of the
3143   // call.
3144   if (!Outs.empty()) {
3145     // Check if stack adjustment is needed. For now, do not do this if any
3146     // argument is passed on the stack.
3147     SmallVector<CCValAssign, 16> ArgLocs;
3148     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3149                    getTargetMachine(), ArgLocs, *DAG.getContext());
3150
3151     // Allocate shadow area for Win64
3152     if (IsCalleeWin64)
3153       CCInfo.AllocateStack(32, 8);
3154
3155     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3156     if (CCInfo.getNextStackOffset()) {
3157       MachineFunction &MF = DAG.getMachineFunction();
3158       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3159         return false;
3160
3161       // Check if the arguments are already laid out in the right way as
3162       // the caller's fixed stack objects.
3163       MachineFrameInfo *MFI = MF.getFrameInfo();
3164       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3165       const X86InstrInfo *TII =
3166         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3167       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3168         CCValAssign &VA = ArgLocs[i];
3169         SDValue Arg = OutVals[i];
3170         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3171         if (VA.getLocInfo() == CCValAssign::Indirect)
3172           return false;
3173         if (!VA.isRegLoc()) {
3174           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3175                                    MFI, MRI, TII))
3176             return false;
3177         }
3178       }
3179     }
3180
3181     // If the tailcall address may be in a register, then make sure it's
3182     // possible to register allocate for it. In 32-bit, the call address can
3183     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3184     // callee-saved registers are restored. These happen to be the same
3185     // registers used to pass 'inreg' arguments so watch out for those.
3186     if (!Subtarget->is64Bit() &&
3187         ((!isa<GlobalAddressSDNode>(Callee) &&
3188           !isa<ExternalSymbolSDNode>(Callee)) ||
3189          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3190       unsigned NumInRegs = 0;
3191       // In PIC we need an extra register to formulate the address computation
3192       // for the callee.
3193       unsigned MaxInRegs =
3194           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3195
3196       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3197         CCValAssign &VA = ArgLocs[i];
3198         if (!VA.isRegLoc())
3199           continue;
3200         unsigned Reg = VA.getLocReg();
3201         switch (Reg) {
3202         default: break;
3203         case X86::EAX: case X86::EDX: case X86::ECX:
3204           if (++NumInRegs == MaxInRegs)
3205             return false;
3206           break;
3207         }
3208       }
3209     }
3210   }
3211
3212   return true;
3213 }
3214
3215 FastISel *
3216 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3217                                   const TargetLibraryInfo *libInfo) const {
3218   return X86::createFastISel(funcInfo, libInfo);
3219 }
3220
3221 //===----------------------------------------------------------------------===//
3222 //                           Other Lowering Hooks
3223 //===----------------------------------------------------------------------===//
3224
3225 static bool MayFoldLoad(SDValue Op) {
3226   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3227 }
3228
3229 static bool MayFoldIntoStore(SDValue Op) {
3230   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3231 }
3232
3233 static bool isTargetShuffle(unsigned Opcode) {
3234   switch(Opcode) {
3235   default: return false;
3236   case X86ISD::PSHUFD:
3237   case X86ISD::PSHUFHW:
3238   case X86ISD::PSHUFLW:
3239   case X86ISD::SHUFP:
3240   case X86ISD::PALIGNR:
3241   case X86ISD::MOVLHPS:
3242   case X86ISD::MOVLHPD:
3243   case X86ISD::MOVHLPS:
3244   case X86ISD::MOVLPS:
3245   case X86ISD::MOVLPD:
3246   case X86ISD::MOVSHDUP:
3247   case X86ISD::MOVSLDUP:
3248   case X86ISD::MOVDDUP:
3249   case X86ISD::MOVSS:
3250   case X86ISD::MOVSD:
3251   case X86ISD::UNPCKL:
3252   case X86ISD::UNPCKH:
3253   case X86ISD::VPERMILP:
3254   case X86ISD::VPERM2X128:
3255   case X86ISD::VPERMI:
3256     return true;
3257   }
3258 }
3259
3260 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3261                                     SDValue V1, SelectionDAG &DAG) {
3262   switch(Opc) {
3263   default: llvm_unreachable("Unknown x86 shuffle node");
3264   case X86ISD::MOVSHDUP:
3265   case X86ISD::MOVSLDUP:
3266   case X86ISD::MOVDDUP:
3267     return DAG.getNode(Opc, dl, VT, V1);
3268   }
3269 }
3270
3271 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3272                                     SDValue V1, unsigned TargetMask,
3273                                     SelectionDAG &DAG) {
3274   switch(Opc) {
3275   default: llvm_unreachable("Unknown x86 shuffle node");
3276   case X86ISD::PSHUFD:
3277   case X86ISD::PSHUFHW:
3278   case X86ISD::PSHUFLW:
3279   case X86ISD::VPERMILP:
3280   case X86ISD::VPERMI:
3281     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3282   }
3283 }
3284
3285 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3286                                     SDValue V1, SDValue V2, unsigned TargetMask,
3287                                     SelectionDAG &DAG) {
3288   switch(Opc) {
3289   default: llvm_unreachable("Unknown x86 shuffle node");
3290   case X86ISD::PALIGNR:
3291   case X86ISD::SHUFP:
3292   case X86ISD::VPERM2X128:
3293     return DAG.getNode(Opc, dl, VT, V1, V2,
3294                        DAG.getConstant(TargetMask, MVT::i8));
3295   }
3296 }
3297
3298 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3299                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3300   switch(Opc) {
3301   default: llvm_unreachable("Unknown x86 shuffle node");
3302   case X86ISD::MOVLHPS:
3303   case X86ISD::MOVLHPD:
3304   case X86ISD::MOVHLPS:
3305   case X86ISD::MOVLPS:
3306   case X86ISD::MOVLPD:
3307   case X86ISD::MOVSS:
3308   case X86ISD::MOVSD:
3309   case X86ISD::UNPCKL:
3310   case X86ISD::UNPCKH:
3311     return DAG.getNode(Opc, dl, VT, V1, V2);
3312   }
3313 }
3314
3315 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3316   MachineFunction &MF = DAG.getMachineFunction();
3317   const X86RegisterInfo *RegInfo =
3318     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3319   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3320   int ReturnAddrIndex = FuncInfo->getRAIndex();
3321
3322   if (ReturnAddrIndex == 0) {
3323     // Set up a frame object for the return address.
3324     unsigned SlotSize = RegInfo->getSlotSize();
3325     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3326                                                            -(int64_t)SlotSize,
3327                                                            false);
3328     FuncInfo->setRAIndex(ReturnAddrIndex);
3329   }
3330
3331   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3332 }
3333
3334 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3335                                        bool hasSymbolicDisplacement) {
3336   // Offset should fit into 32 bit immediate field.
3337   if (!isInt<32>(Offset))
3338     return false;
3339
3340   // If we don't have a symbolic displacement - we don't have any extra
3341   // restrictions.
3342   if (!hasSymbolicDisplacement)
3343     return true;
3344
3345   // FIXME: Some tweaks might be needed for medium code model.
3346   if (M != CodeModel::Small && M != CodeModel::Kernel)
3347     return false;
3348
3349   // For small code model we assume that latest object is 16MB before end of 31
3350   // bits boundary. We may also accept pretty large negative constants knowing
3351   // that all objects are in the positive half of address space.
3352   if (M == CodeModel::Small && Offset < 16*1024*1024)
3353     return true;
3354
3355   // For kernel code model we know that all object resist in the negative half
3356   // of 32bits address space. We may not accept negative offsets, since they may
3357   // be just off and we may accept pretty large positive ones.
3358   if (M == CodeModel::Kernel && Offset > 0)
3359     return true;
3360
3361   return false;
3362 }
3363
3364 /// isCalleePop - Determines whether the callee is required to pop its
3365 /// own arguments. Callee pop is necessary to support tail calls.
3366 bool X86::isCalleePop(CallingConv::ID CallingConv,
3367                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3368   if (IsVarArg)
3369     return false;
3370
3371   switch (CallingConv) {
3372   default:
3373     return false;
3374   case CallingConv::X86_StdCall:
3375     return !is64Bit;
3376   case CallingConv::X86_FastCall:
3377     return !is64Bit;
3378   case CallingConv::X86_ThisCall:
3379     return !is64Bit;
3380   case CallingConv::Fast:
3381     return TailCallOpt;
3382   case CallingConv::GHC:
3383     return TailCallOpt;
3384   case CallingConv::HiPE:
3385     return TailCallOpt;
3386   }
3387 }
3388
3389 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3390 /// specific condition code, returning the condition code and the LHS/RHS of the
3391 /// comparison to make.
3392 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3393                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3394   if (!isFP) {
3395     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3396       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3397         // X > -1   -> X == 0, jump !sign.
3398         RHS = DAG.getConstant(0, RHS.getValueType());
3399         return X86::COND_NS;
3400       }
3401       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3402         // X < 0   -> X == 0, jump on sign.
3403         return X86::COND_S;
3404       }
3405       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3406         // X < 1   -> X <= 0
3407         RHS = DAG.getConstant(0, RHS.getValueType());
3408         return X86::COND_LE;
3409       }
3410     }
3411
3412     switch (SetCCOpcode) {
3413     default: llvm_unreachable("Invalid integer condition!");
3414     case ISD::SETEQ:  return X86::COND_E;
3415     case ISD::SETGT:  return X86::COND_G;
3416     case ISD::SETGE:  return X86::COND_GE;
3417     case ISD::SETLT:  return X86::COND_L;
3418     case ISD::SETLE:  return X86::COND_LE;
3419     case ISD::SETNE:  return X86::COND_NE;
3420     case ISD::SETULT: return X86::COND_B;
3421     case ISD::SETUGT: return X86::COND_A;
3422     case ISD::SETULE: return X86::COND_BE;
3423     case ISD::SETUGE: return X86::COND_AE;
3424     }
3425   }
3426
3427   // First determine if it is required or is profitable to flip the operands.
3428
3429   // If LHS is a foldable load, but RHS is not, flip the condition.
3430   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3431       !ISD::isNON_EXTLoad(RHS.getNode())) {
3432     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3433     std::swap(LHS, RHS);
3434   }
3435
3436   switch (SetCCOpcode) {
3437   default: break;
3438   case ISD::SETOLT:
3439   case ISD::SETOLE:
3440   case ISD::SETUGT:
3441   case ISD::SETUGE:
3442     std::swap(LHS, RHS);
3443     break;
3444   }
3445
3446   // On a floating point condition, the flags are set as follows:
3447   // ZF  PF  CF   op
3448   //  0 | 0 | 0 | X > Y
3449   //  0 | 0 | 1 | X < Y
3450   //  1 | 0 | 0 | X == Y
3451   //  1 | 1 | 1 | unordered
3452   switch (SetCCOpcode) {
3453   default: llvm_unreachable("Condcode should be pre-legalized away");
3454   case ISD::SETUEQ:
3455   case ISD::SETEQ:   return X86::COND_E;
3456   case ISD::SETOLT:              // flipped
3457   case ISD::SETOGT:
3458   case ISD::SETGT:   return X86::COND_A;
3459   case ISD::SETOLE:              // flipped
3460   case ISD::SETOGE:
3461   case ISD::SETGE:   return X86::COND_AE;
3462   case ISD::SETUGT:              // flipped
3463   case ISD::SETULT:
3464   case ISD::SETLT:   return X86::COND_B;
3465   case ISD::SETUGE:              // flipped
3466   case ISD::SETULE:
3467   case ISD::SETLE:   return X86::COND_BE;
3468   case ISD::SETONE:
3469   case ISD::SETNE:   return X86::COND_NE;
3470   case ISD::SETUO:   return X86::COND_P;
3471   case ISD::SETO:    return X86::COND_NP;
3472   case ISD::SETOEQ:
3473   case ISD::SETUNE:  return X86::COND_INVALID;
3474   }
3475 }
3476
3477 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3478 /// code. Current x86 isa includes the following FP cmov instructions:
3479 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3480 static bool hasFPCMov(unsigned X86CC) {
3481   switch (X86CC) {
3482   default:
3483     return false;
3484   case X86::COND_B:
3485   case X86::COND_BE:
3486   case X86::COND_E:
3487   case X86::COND_P:
3488   case X86::COND_A:
3489   case X86::COND_AE:
3490   case X86::COND_NE:
3491   case X86::COND_NP:
3492     return true;
3493   }
3494 }
3495
3496 /// isFPImmLegal - Returns true if the target can instruction select the
3497 /// specified FP immediate natively. If false, the legalizer will
3498 /// materialize the FP immediate as a load from a constant pool.
3499 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3500   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3501     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3502       return true;
3503   }
3504   return false;
3505 }
3506
3507 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3508 /// the specified range (L, H].
3509 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3510   return (Val < 0) || (Val >= Low && Val < Hi);
3511 }
3512
3513 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3514 /// specified value.
3515 static bool isUndefOrEqual(int Val, int CmpVal) {
3516   return (Val < 0 || Val == CmpVal);
3517 }
3518
3519 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3520 /// from position Pos and ending in Pos+Size, falls within the specified
3521 /// sequential range (L, L+Pos]. or is undef.
3522 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3523                                        unsigned Pos, unsigned Size, int Low) {
3524   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3525     if (!isUndefOrEqual(Mask[i], Low))
3526       return false;
3527   return true;
3528 }
3529
3530 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3531 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3532 /// the second operand.
3533 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3534   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3535     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3536   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3537     return (Mask[0] < 2 && Mask[1] < 2);
3538   return false;
3539 }
3540
3541 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3542 /// is suitable for input to PSHUFHW.
3543 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3544   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3545     return false;
3546
3547   // Lower quadword copied in order or undef.
3548   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3549     return false;
3550
3551   // Upper quadword shuffled.
3552   for (unsigned i = 4; i != 8; ++i)
3553     if (!isUndefOrInRange(Mask[i], 4, 8))
3554       return false;
3555
3556   if (VT == MVT::v16i16) {
3557     // Lower quadword copied in order or undef.
3558     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3559       return false;
3560
3561     // Upper quadword shuffled.
3562     for (unsigned i = 12; i != 16; ++i)
3563       if (!isUndefOrInRange(Mask[i], 12, 16))
3564         return false;
3565   }
3566
3567   return true;
3568 }
3569
3570 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3571 /// is suitable for input to PSHUFLW.
3572 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3573   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3574     return false;
3575
3576   // Upper quadword copied in order.
3577   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3578     return false;
3579
3580   // Lower quadword shuffled.
3581   for (unsigned i = 0; i != 4; ++i)
3582     if (!isUndefOrInRange(Mask[i], 0, 4))
3583       return false;
3584
3585   if (VT == MVT::v16i16) {
3586     // Upper quadword copied in order.
3587     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3588       return false;
3589
3590     // Lower quadword shuffled.
3591     for (unsigned i = 8; i != 12; ++i)
3592       if (!isUndefOrInRange(Mask[i], 8, 12))
3593         return false;
3594   }
3595
3596   return true;
3597 }
3598
3599 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3600 /// is suitable for input to PALIGNR.
3601 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3602                           const X86Subtarget *Subtarget) {
3603   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3604       (VT.is256BitVector() && !Subtarget->hasInt256()))
3605     return false;
3606
3607   unsigned NumElts = VT.getVectorNumElements();
3608   unsigned NumLanes = VT.getSizeInBits()/128;
3609   unsigned NumLaneElts = NumElts/NumLanes;
3610
3611   // Do not handle 64-bit element shuffles with palignr.
3612   if (NumLaneElts == 2)
3613     return false;
3614
3615   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3616     unsigned i;
3617     for (i = 0; i != NumLaneElts; ++i) {
3618       if (Mask[i+l] >= 0)
3619         break;
3620     }
3621
3622     // Lane is all undef, go to next lane
3623     if (i == NumLaneElts)
3624       continue;
3625
3626     int Start = Mask[i+l];
3627
3628     // Make sure its in this lane in one of the sources
3629     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3630         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3631       return false;
3632
3633     // If not lane 0, then we must match lane 0
3634     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3635       return false;
3636
3637     // Correct second source to be contiguous with first source
3638     if (Start >= (int)NumElts)
3639       Start -= NumElts - NumLaneElts;
3640
3641     // Make sure we're shifting in the right direction.
3642     if (Start <= (int)(i+l))
3643       return false;
3644
3645     Start -= i;
3646
3647     // Check the rest of the elements to see if they are consecutive.
3648     for (++i; i != NumLaneElts; ++i) {
3649       int Idx = Mask[i+l];
3650
3651       // Make sure its in this lane
3652       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3653           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3654         return false;
3655
3656       // If not lane 0, then we must match lane 0
3657       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3658         return false;
3659
3660       if (Idx >= (int)NumElts)
3661         Idx -= NumElts - NumLaneElts;
3662
3663       if (!isUndefOrEqual(Idx, Start+i))
3664         return false;
3665
3666     }
3667   }
3668
3669   return true;
3670 }
3671
3672 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3673 /// the two vector operands have swapped position.
3674 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3675                                      unsigned NumElems) {
3676   for (unsigned i = 0; i != NumElems; ++i) {
3677     int idx = Mask[i];
3678     if (idx < 0)
3679       continue;
3680     else if (idx < (int)NumElems)
3681       Mask[i] = idx + NumElems;
3682     else
3683       Mask[i] = idx - NumElems;
3684   }
3685 }
3686
3687 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3688 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3689 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3690 /// reverse of what x86 shuffles want.
3691 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool HasFp256,
3692                         bool Commuted = false) {
3693   if (!HasFp256 && VT.is256BitVector())
3694     return false;
3695
3696   unsigned NumElems = VT.getVectorNumElements();
3697   unsigned NumLanes = VT.getSizeInBits()/128;
3698   unsigned NumLaneElems = NumElems/NumLanes;
3699
3700   if (NumLaneElems != 2 && NumLaneElems != 4)
3701     return false;
3702
3703   // VSHUFPSY divides the resulting vector into 4 chunks.
3704   // The sources are also splitted into 4 chunks, and each destination
3705   // chunk must come from a different source chunk.
3706   //
3707   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3708   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3709   //
3710   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3711   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3712   //
3713   // VSHUFPDY divides the resulting vector into 4 chunks.
3714   // The sources are also splitted into 4 chunks, and each destination
3715   // chunk must come from a different source chunk.
3716   //
3717   //  SRC1 =>      X3       X2       X1       X0
3718   //  SRC2 =>      Y3       Y2       Y1       Y0
3719   //
3720   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3721   //
3722   unsigned HalfLaneElems = NumLaneElems/2;
3723   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3724     for (unsigned i = 0; i != NumLaneElems; ++i) {
3725       int Idx = Mask[i+l];
3726       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3727       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3728         return false;
3729       // For VSHUFPSY, the mask of the second half must be the same as the
3730       // first but with the appropriate offsets. This works in the same way as
3731       // VPERMILPS works with masks.
3732       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3733         continue;
3734       if (!isUndefOrEqual(Idx, Mask[i]+l))
3735         return false;
3736     }
3737   }
3738
3739   return true;
3740 }
3741
3742 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3743 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3744 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3745   if (!VT.is128BitVector())
3746     return false;
3747
3748   unsigned NumElems = VT.getVectorNumElements();
3749
3750   if (NumElems != 4)
3751     return false;
3752
3753   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3754   return isUndefOrEqual(Mask[0], 6) &&
3755          isUndefOrEqual(Mask[1], 7) &&
3756          isUndefOrEqual(Mask[2], 2) &&
3757          isUndefOrEqual(Mask[3], 3);
3758 }
3759
3760 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3761 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3762 /// <2, 3, 2, 3>
3763 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3764   if (!VT.is128BitVector())
3765     return false;
3766
3767   unsigned NumElems = VT.getVectorNumElements();
3768
3769   if (NumElems != 4)
3770     return false;
3771
3772   return isUndefOrEqual(Mask[0], 2) &&
3773          isUndefOrEqual(Mask[1], 3) &&
3774          isUndefOrEqual(Mask[2], 2) &&
3775          isUndefOrEqual(Mask[3], 3);
3776 }
3777
3778 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3779 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3780 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3781   if (!VT.is128BitVector())
3782     return false;
3783
3784   unsigned NumElems = VT.getVectorNumElements();
3785
3786   if (NumElems != 2 && NumElems != 4)
3787     return false;
3788
3789   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3790     if (!isUndefOrEqual(Mask[i], i + NumElems))
3791       return false;
3792
3793   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3794     if (!isUndefOrEqual(Mask[i], i))
3795       return false;
3796
3797   return true;
3798 }
3799
3800 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3801 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3802 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3803   if (!VT.is128BitVector())
3804     return false;
3805
3806   unsigned NumElems = VT.getVectorNumElements();
3807
3808   if (NumElems != 2 && NumElems != 4)
3809     return false;
3810
3811   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3812     if (!isUndefOrEqual(Mask[i], i))
3813       return false;
3814
3815   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3816     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3817       return false;
3818
3819   return true;
3820 }
3821
3822 //
3823 // Some special combinations that can be optimized.
3824 //
3825 static
3826 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3827                                SelectionDAG &DAG) {
3828   MVT VT = SVOp->getSimpleValueType(0);
3829   SDLoc dl(SVOp);
3830
3831   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3832     return SDValue();
3833
3834   ArrayRef<int> Mask = SVOp->getMask();
3835
3836   // These are the special masks that may be optimized.
3837   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3838   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3839   bool MatchEvenMask = true;
3840   bool MatchOddMask  = true;
3841   for (int i=0; i<8; ++i) {
3842     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3843       MatchEvenMask = false;
3844     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3845       MatchOddMask = false;
3846   }
3847
3848   if (!MatchEvenMask && !MatchOddMask)
3849     return SDValue();
3850
3851   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3852
3853   SDValue Op0 = SVOp->getOperand(0);
3854   SDValue Op1 = SVOp->getOperand(1);
3855
3856   if (MatchEvenMask) {
3857     // Shift the second operand right to 32 bits.
3858     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3859     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3860   } else {
3861     // Shift the first operand left to 32 bits.
3862     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3863     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3864   }
3865   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3866   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3867 }
3868
3869 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3870 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3871 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
3872                          bool HasInt256, bool V2IsSplat = false) {
3873
3874   if (VT.is512BitVector())
3875     return false;
3876   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3877          "Unsupported vector type for unpckh");
3878
3879   unsigned NumElts = VT.getVectorNumElements();
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 != NumElts; l += NumLaneElts) {
3890     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3891       int BitI  = Mask[l+i];
3892       int BitI1 = Mask[l+i+1];
3893       if (!isUndefOrEqual(BitI, j))
3894         return false;
3895       if (V2IsSplat) {
3896         if (!isUndefOrEqual(BitI1, NumElts))
3897           return false;
3898       } else {
3899         if (!isUndefOrEqual(BitI1, j + NumElts))
3900           return false;
3901       }
3902     }
3903   }
3904
3905   return true;
3906 }
3907
3908 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3909 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3910 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
3911                          bool HasInt256, bool V2IsSplat = false) {
3912   unsigned NumElts = VT.getVectorNumElements();
3913
3914   if (VT.is512BitVector())
3915     return false;
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 != NumElts; l += NumLaneElts) {
3929     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
3930       int BitI  = Mask[l+i];
3931       int BitI1 = Mask[l+i+1];
3932       if (!isUndefOrEqual(BitI, j))
3933         return false;
3934       if (V2IsSplat) {
3935         if (isUndefOrEqual(BitI1, NumElts))
3936           return false;
3937       } else {
3938         if (!isUndefOrEqual(BitI1, j+NumElts))
3939           return false;
3940       }
3941     }
3942   }
3943   return true;
3944 }
3945
3946 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3947 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3948 /// <0, 0, 1, 1>
3949 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3950   unsigned NumElts = VT.getVectorNumElements();
3951   bool Is256BitVec = VT.is256BitVector();
3952
3953   if (VT.is512BitVector())
3954     return false;
3955   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3956          "Unsupported vector type for unpckh");
3957
3958   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3959       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3960     return false;
3961
3962   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3963   // FIXME: Need a better way to get rid of this, there's no latency difference
3964   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3965   // the former later. We should also remove the "_undef" special mask.
3966   if (NumElts == 4 && Is256BitVec)
3967     return false;
3968
3969   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3970   // independently on 128-bit lanes.
3971   unsigned NumLanes = VT.getSizeInBits()/128;
3972   unsigned NumLaneElts = NumElts/NumLanes;
3973
3974   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3975     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3976       int BitI  = Mask[l+i];
3977       int BitI1 = Mask[l+i+1];
3978
3979       if (!isUndefOrEqual(BitI, j))
3980         return false;
3981       if (!isUndefOrEqual(BitI1, j))
3982         return false;
3983     }
3984   }
3985
3986   return true;
3987 }
3988
3989 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3990 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3991 /// <2, 2, 3, 3>
3992 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3993   unsigned NumElts = VT.getVectorNumElements();
3994
3995   if (VT.is512BitVector())
3996     return false;
3997
3998   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3999          "Unsupported vector type for unpckh");
4000
4001   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4002       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4003     return false;
4004
4005   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4006   // independently on 128-bit lanes.
4007   unsigned NumLanes = VT.getSizeInBits()/128;
4008   unsigned NumLaneElts = NumElts/NumLanes;
4009
4010   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4011     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4012       int BitI  = Mask[l+i];
4013       int BitI1 = Mask[l+i+1];
4014       if (!isUndefOrEqual(BitI, j))
4015         return false;
4016       if (!isUndefOrEqual(BitI1, j))
4017         return false;
4018     }
4019   }
4020   return true;
4021 }
4022
4023 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4024 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4025 /// MOVSD, and MOVD, i.e. setting the lowest element.
4026 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4027   if (VT.getVectorElementType().getSizeInBits() < 32)
4028     return false;
4029   if (!VT.is128BitVector())
4030     return false;
4031
4032   unsigned NumElts = VT.getVectorNumElements();
4033
4034   if (!isUndefOrEqual(Mask[0], NumElts))
4035     return false;
4036
4037   for (unsigned i = 1; i != NumElts; ++i)
4038     if (!isUndefOrEqual(Mask[i], i))
4039       return false;
4040
4041   return true;
4042 }
4043
4044 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4045 /// as permutations between 128-bit chunks or halves. As an example: this
4046 /// shuffle bellow:
4047 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4048 /// The first half comes from the second half of V1 and the second half from the
4049 /// the second half of V2.
4050 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4051   if (!HasFp256 || !VT.is256BitVector())
4052     return false;
4053
4054   // The shuffle result is divided into half A and half B. In total the two
4055   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4056   // B must come from C, D, E or F.
4057   unsigned HalfSize = VT.getVectorNumElements()/2;
4058   bool MatchA = false, MatchB = false;
4059
4060   // Check if A comes from one of C, D, E, F.
4061   for (unsigned Half = 0; Half != 4; ++Half) {
4062     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4063       MatchA = true;
4064       break;
4065     }
4066   }
4067
4068   // Check if B comes from one of C, D, E, F.
4069   for (unsigned Half = 0; Half != 4; ++Half) {
4070     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4071       MatchB = true;
4072       break;
4073     }
4074   }
4075
4076   return MatchA && MatchB;
4077 }
4078
4079 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4080 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4081 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4082   MVT VT = SVOp->getSimpleValueType(0);
4083
4084   unsigned HalfSize = VT.getVectorNumElements()/2;
4085
4086   unsigned FstHalf = 0, SndHalf = 0;
4087   for (unsigned i = 0; i < HalfSize; ++i) {
4088     if (SVOp->getMaskElt(i) > 0) {
4089       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4090       break;
4091     }
4092   }
4093   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4094     if (SVOp->getMaskElt(i) > 0) {
4095       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4096       break;
4097     }
4098   }
4099
4100   return (FstHalf | (SndHalf << 4));
4101 }
4102
4103 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4104 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4105   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4106   if (EltSize < 32)
4107     return false;
4108
4109   unsigned NumElts = VT.getVectorNumElements();
4110   Imm8 = 0;
4111   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4112     for (unsigned i = 0; i != NumElts; ++i) {
4113       if (Mask[i] < 0)
4114         continue;
4115       Imm8 |= Mask[i] << (i*2);
4116     }
4117     return true;
4118   }
4119
4120   unsigned LaneSize = 4;
4121   SmallVector<int, 4> MaskVal(LaneSize, -1);
4122
4123   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4124     for (unsigned i = 0; i != LaneSize; ++i) {
4125       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4126         return false;
4127       if (Mask[i+l] < 0)
4128         continue;
4129       if (MaskVal[i] < 0) {
4130         MaskVal[i] = Mask[i+l] - l;
4131         Imm8 |= MaskVal[i] << (i*2);
4132         continue;
4133       }
4134       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4135         return false;
4136     }
4137   }
4138   return true;
4139 }
4140
4141 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4142 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4143 /// Note that VPERMIL mask matching is different depending whether theunderlying
4144 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4145 /// to the same elements of the low, but to the higher half of the source.
4146 /// In VPERMILPD the two lanes could be shuffled independently of each other
4147 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4148 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4149   if (!HasFp256)
4150     return false;
4151
4152   unsigned NumElts = VT.getVectorNumElements();
4153   // Only match 256-bit with 32/64-bit types
4154   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
4155     return false;
4156
4157   unsigned NumLanes = VT.getSizeInBits()/128;
4158   unsigned LaneSize = NumElts/NumLanes;
4159   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4160     for (unsigned i = 0; i != LaneSize; ++i) {
4161       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4162         return false;
4163       if (NumElts != 8 || l == 0)
4164         continue;
4165       // VPERMILPS handling
4166       if (Mask[i] < 0)
4167         continue;
4168       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
4169         return false;
4170     }
4171   }
4172
4173   return true;
4174 }
4175
4176 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4177 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4178 /// element of vector 2 and the other elements to come from vector 1 in order.
4179 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4180                                bool V2IsSplat = false, bool V2IsUndef = false) {
4181   if (!VT.is128BitVector())
4182     return false;
4183
4184   unsigned NumOps = VT.getVectorNumElements();
4185   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4186     return false;
4187
4188   if (!isUndefOrEqual(Mask[0], 0))
4189     return false;
4190
4191   for (unsigned i = 1; i != NumOps; ++i)
4192     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4193           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4194           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4195       return false;
4196
4197   return true;
4198 }
4199
4200 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4201 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4202 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4203 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4204                            const X86Subtarget *Subtarget) {
4205   if (!Subtarget->hasSSE3())
4206     return false;
4207
4208   unsigned NumElems = VT.getVectorNumElements();
4209
4210   if ((VT.is128BitVector() && NumElems != 4) ||
4211       (VT.is256BitVector() && NumElems != 8) ||
4212       (VT.is512BitVector() && NumElems != 16))
4213     return false;
4214
4215   // "i+1" is the value the indexed mask element must have
4216   for (unsigned i = 0; i != NumElems; i += 2)
4217     if (!isUndefOrEqual(Mask[i], i+1) ||
4218         !isUndefOrEqual(Mask[i+1], i+1))
4219       return false;
4220
4221   return true;
4222 }
4223
4224 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4225 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4226 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4227 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4228                            const X86Subtarget *Subtarget) {
4229   if (!Subtarget->hasSSE3())
4230     return false;
4231
4232   unsigned NumElems = VT.getVectorNumElements();
4233
4234   if ((VT.is128BitVector() && NumElems != 4) ||
4235       (VT.is256BitVector() && NumElems != 8) ||
4236       (VT.is512BitVector() && NumElems != 16))
4237     return false;
4238
4239   // "i" is the value the indexed mask element must have
4240   for (unsigned i = 0; i != NumElems; i += 2)
4241     if (!isUndefOrEqual(Mask[i], i) ||
4242         !isUndefOrEqual(Mask[i+1], i))
4243       return false;
4244
4245   return true;
4246 }
4247
4248 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4249 /// specifies a shuffle of elements that is suitable for input to 256-bit
4250 /// version of MOVDDUP.
4251 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4252   if (!HasFp256 || !VT.is256BitVector())
4253     return false;
4254
4255   unsigned NumElts = VT.getVectorNumElements();
4256   if (NumElts != 4)
4257     return false;
4258
4259   for (unsigned i = 0; i != NumElts/2; ++i)
4260     if (!isUndefOrEqual(Mask[i], 0))
4261       return false;
4262   for (unsigned i = NumElts/2; i != NumElts; ++i)
4263     if (!isUndefOrEqual(Mask[i], NumElts/2))
4264       return false;
4265   return true;
4266 }
4267
4268 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4269 /// specifies a shuffle of elements that is suitable for input to 128-bit
4270 /// version of MOVDDUP.
4271 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4272   if (!VT.is128BitVector())
4273     return false;
4274
4275   unsigned e = VT.getVectorNumElements() / 2;
4276   for (unsigned i = 0; i != e; ++i)
4277     if (!isUndefOrEqual(Mask[i], i))
4278       return false;
4279   for (unsigned i = 0; i != e; ++i)
4280     if (!isUndefOrEqual(Mask[e+i], i))
4281       return false;
4282   return true;
4283 }
4284
4285 /// isVEXTRACTIndex - Return true if the specified
4286 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4287 /// suitable for instruction that extract 128 or 256 bit vectors
4288 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4289   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4290   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4291     return false;
4292
4293   // The index should be aligned on a vecWidth-bit boundary.
4294   uint64_t Index =
4295     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4296
4297   MVT VT = N->getSimpleValueType(0);
4298   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4299   bool Result = (Index * ElSize) % vecWidth == 0;
4300
4301   return Result;
4302 }
4303
4304 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4305 /// operand specifies a subvector insert that is suitable for input to
4306 /// insertion of 128 or 256-bit subvectors
4307 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4308   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4309   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4310     return false;
4311   // The index should be aligned on a vecWidth-bit boundary.
4312   uint64_t Index =
4313     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4314
4315   MVT VT = N->getSimpleValueType(0);
4316   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4317   bool Result = (Index * ElSize) % vecWidth == 0;
4318
4319   return Result;
4320 }
4321
4322 bool X86::isVINSERT128Index(SDNode *N) {
4323   return isVINSERTIndex(N, 128);
4324 }
4325
4326 bool X86::isVINSERT256Index(SDNode *N) {
4327   return isVINSERTIndex(N, 256);
4328 }
4329
4330 bool X86::isVEXTRACT128Index(SDNode *N) {
4331   return isVEXTRACTIndex(N, 128);
4332 }
4333
4334 bool X86::isVEXTRACT256Index(SDNode *N) {
4335   return isVEXTRACTIndex(N, 256);
4336 }
4337
4338 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4339 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4340 /// Handles 128-bit and 256-bit.
4341 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4342   MVT VT = N->getSimpleValueType(0);
4343
4344   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4345          "Unsupported vector type for PSHUF/SHUFP");
4346
4347   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4348   // independently on 128-bit lanes.
4349   unsigned NumElts = VT.getVectorNumElements();
4350   unsigned NumLanes = VT.getSizeInBits()/128;
4351   unsigned NumLaneElts = NumElts/NumLanes;
4352
4353   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4354          "Only supports 2 or 4 elements per lane");
4355
4356   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4357   unsigned Mask = 0;
4358   for (unsigned i = 0; i != NumElts; ++i) {
4359     int Elt = N->getMaskElt(i);
4360     if (Elt < 0) continue;
4361     Elt &= NumLaneElts - 1;
4362     unsigned ShAmt = (i << Shift) % 8;
4363     Mask |= Elt << ShAmt;
4364   }
4365
4366   return Mask;
4367 }
4368
4369 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4370 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4371 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4372   MVT VT = N->getSimpleValueType(0);
4373
4374   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4375          "Unsupported vector type for PSHUFHW");
4376
4377   unsigned NumElts = VT.getVectorNumElements();
4378
4379   unsigned Mask = 0;
4380   for (unsigned l = 0; l != NumElts; l += 8) {
4381     // 8 nodes per lane, but we only care about the last 4.
4382     for (unsigned i = 0; i < 4; ++i) {
4383       int Elt = N->getMaskElt(l+i+4);
4384       if (Elt < 0) continue;
4385       Elt &= 0x3; // only 2-bits.
4386       Mask |= Elt << (i * 2);
4387     }
4388   }
4389
4390   return Mask;
4391 }
4392
4393 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4394 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4395 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4396   MVT VT = N->getSimpleValueType(0);
4397
4398   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4399          "Unsupported vector type for PSHUFHW");
4400
4401   unsigned NumElts = VT.getVectorNumElements();
4402
4403   unsigned Mask = 0;
4404   for (unsigned l = 0; l != NumElts; l += 8) {
4405     // 8 nodes per lane, but we only care about the first 4.
4406     for (unsigned i = 0; i < 4; ++i) {
4407       int Elt = N->getMaskElt(l+i);
4408       if (Elt < 0) continue;
4409       Elt &= 0x3; // only 2-bits
4410       Mask |= Elt << (i * 2);
4411     }
4412   }
4413
4414   return Mask;
4415 }
4416
4417 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4418 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4419 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4420   MVT VT = SVOp->getSimpleValueType(0);
4421   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4422
4423   unsigned NumElts = VT.getVectorNumElements();
4424   unsigned NumLanes = VT.getSizeInBits()/128;
4425   unsigned NumLaneElts = NumElts/NumLanes;
4426
4427   int Val = 0;
4428   unsigned i;
4429   for (i = 0; i != NumElts; ++i) {
4430     Val = SVOp->getMaskElt(i);
4431     if (Val >= 0)
4432       break;
4433   }
4434   if (Val >= (int)NumElts)
4435     Val -= NumElts - NumLaneElts;
4436
4437   assert(Val - i > 0 && "PALIGNR imm should be positive");
4438   return (Val - i) * EltSize;
4439 }
4440
4441 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4442   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4443   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4444     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4445
4446   uint64_t Index =
4447     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4448
4449   MVT VecVT = N->getOperand(0).getSimpleValueType();
4450   MVT ElVT = VecVT.getVectorElementType();
4451
4452   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4453   return Index / NumElemsPerChunk;
4454 }
4455
4456 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4457   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4458   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4459     llvm_unreachable("Illegal insert subvector for VINSERT");
4460
4461   uint64_t Index =
4462     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4463
4464   MVT VecVT = N->getSimpleValueType(0);
4465   MVT ElVT = VecVT.getVectorElementType();
4466
4467   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4468   return Index / NumElemsPerChunk;
4469 }
4470
4471 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4472 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4473 /// and VINSERTI128 instructions.
4474 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4475   return getExtractVEXTRACTImmediate(N, 128);
4476 }
4477
4478 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4479 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4480 /// and VINSERTI64x4 instructions.
4481 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4482   return getExtractVEXTRACTImmediate(N, 256);
4483 }
4484
4485 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4486 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4487 /// and VINSERTI128 instructions.
4488 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4489   return getInsertVINSERTImmediate(N, 128);
4490 }
4491
4492 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4493 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4494 /// and VINSERTI64x4 instructions.
4495 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4496   return getInsertVINSERTImmediate(N, 256);
4497 }
4498
4499 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4500 /// constant +0.0.
4501 bool X86::isZeroNode(SDValue Elt) {
4502   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4503     return CN->isNullValue();
4504   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4505     return CFP->getValueAPF().isPosZero();
4506   return false;
4507 }
4508
4509 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4510 /// their permute mask.
4511 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4512                                     SelectionDAG &DAG) {
4513   MVT VT = SVOp->getSimpleValueType(0);
4514   unsigned NumElems = VT.getVectorNumElements();
4515   SmallVector<int, 8> MaskVec;
4516
4517   for (unsigned i = 0; i != NumElems; ++i) {
4518     int Idx = SVOp->getMaskElt(i);
4519     if (Idx >= 0) {
4520       if (Idx < (int)NumElems)
4521         Idx += NumElems;
4522       else
4523         Idx -= NumElems;
4524     }
4525     MaskVec.push_back(Idx);
4526   }
4527   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4528                               SVOp->getOperand(0), &MaskVec[0]);
4529 }
4530
4531 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4532 /// match movhlps. The lower half elements should come from upper half of
4533 /// V1 (and in order), and the upper half elements should come from the upper
4534 /// half of V2 (and in order).
4535 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4536   if (!VT.is128BitVector())
4537     return false;
4538   if (VT.getVectorNumElements() != 4)
4539     return false;
4540   for (unsigned i = 0, e = 2; i != e; ++i)
4541     if (!isUndefOrEqual(Mask[i], i+2))
4542       return false;
4543   for (unsigned i = 2; i != 4; ++i)
4544     if (!isUndefOrEqual(Mask[i], i+4))
4545       return false;
4546   return true;
4547 }
4548
4549 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4550 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4551 /// required.
4552 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4553   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4554     return false;
4555   N = N->getOperand(0).getNode();
4556   if (!ISD::isNON_EXTLoad(N))
4557     return false;
4558   if (LD)
4559     *LD = cast<LoadSDNode>(N);
4560   return true;
4561 }
4562
4563 // Test whether the given value is a vector value which will be legalized
4564 // into a load.
4565 static bool WillBeConstantPoolLoad(SDNode *N) {
4566   if (N->getOpcode() != ISD::BUILD_VECTOR)
4567     return false;
4568
4569   // Check for any non-constant elements.
4570   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4571     switch (N->getOperand(i).getNode()->getOpcode()) {
4572     case ISD::UNDEF:
4573     case ISD::ConstantFP:
4574     case ISD::Constant:
4575       break;
4576     default:
4577       return false;
4578     }
4579
4580   // Vectors of all-zeros and all-ones are materialized with special
4581   // instructions rather than being loaded.
4582   return !ISD::isBuildVectorAllZeros(N) &&
4583          !ISD::isBuildVectorAllOnes(N);
4584 }
4585
4586 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4587 /// match movlp{s|d}. The lower half elements should come from lower half of
4588 /// V1 (and in order), and the upper half elements should come from the upper
4589 /// half of V2 (and in order). And since V1 will become the source of the
4590 /// MOVLP, it must be either a vector load or a scalar load to vector.
4591 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4592                                ArrayRef<int> Mask, MVT VT) {
4593   if (!VT.is128BitVector())
4594     return false;
4595
4596   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4597     return false;
4598   // Is V2 is a vector load, don't do this transformation. We will try to use
4599   // load folding shufps op.
4600   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4601     return false;
4602
4603   unsigned NumElems = VT.getVectorNumElements();
4604
4605   if (NumElems != 2 && NumElems != 4)
4606     return false;
4607   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4608     if (!isUndefOrEqual(Mask[i], i))
4609       return false;
4610   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4611     if (!isUndefOrEqual(Mask[i], i+NumElems))
4612       return false;
4613   return true;
4614 }
4615
4616 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4617 /// all the same.
4618 static bool isSplatVector(SDNode *N) {
4619   if (N->getOpcode() != ISD::BUILD_VECTOR)
4620     return false;
4621
4622   SDValue SplatValue = N->getOperand(0);
4623   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4624     if (N->getOperand(i) != SplatValue)
4625       return false;
4626   return true;
4627 }
4628
4629 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4630 /// to an zero vector.
4631 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4632 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4633   SDValue V1 = N->getOperand(0);
4634   SDValue V2 = N->getOperand(1);
4635   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4636   for (unsigned i = 0; i != NumElems; ++i) {
4637     int Idx = N->getMaskElt(i);
4638     if (Idx >= (int)NumElems) {
4639       unsigned Opc = V2.getOpcode();
4640       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4641         continue;
4642       if (Opc != ISD::BUILD_VECTOR ||
4643           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4644         return false;
4645     } else if (Idx >= 0) {
4646       unsigned Opc = V1.getOpcode();
4647       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4648         continue;
4649       if (Opc != ISD::BUILD_VECTOR ||
4650           !X86::isZeroNode(V1.getOperand(Idx)))
4651         return false;
4652     }
4653   }
4654   return true;
4655 }
4656
4657 /// getZeroVector - Returns a vector of specified type with all zero elements.
4658 ///
4659 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4660                              SelectionDAG &DAG, SDLoc dl) {
4661   assert(VT.isVector() && "Expected a vector type");
4662
4663   // Always build SSE zero vectors as <4 x i32> bitcasted
4664   // to their dest type. This ensures they get CSE'd.
4665   SDValue Vec;
4666   if (VT.is128BitVector()) {  // SSE
4667     if (Subtarget->hasSSE2()) {  // SSE2
4668       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4669       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4670     } else { // SSE1
4671       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4672       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4673     }
4674   } else if (VT.is256BitVector()) { // AVX
4675     if (Subtarget->hasInt256()) { // AVX2
4676       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4677       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4678       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4679                         array_lengthof(Ops));
4680     } else {
4681       // 256-bit logic and arithmetic instructions in AVX are all
4682       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4683       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4684       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4685       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4686                         array_lengthof(Ops));
4687     }
4688   } else
4689     llvm_unreachable("Unexpected vector type");
4690
4691   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4692 }
4693
4694 /// getOnesVector - Returns a vector of specified type with all bits set.
4695 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4696 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4697 /// Then bitcast to their original type, ensuring they get CSE'd.
4698 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4699                              SDLoc dl) {
4700   assert(VT.isVector() && "Expected a vector type");
4701
4702   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4703   SDValue Vec;
4704   if (VT.is256BitVector()) {
4705     if (HasInt256) { // AVX2
4706       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4707       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4708                         array_lengthof(Ops));
4709     } else { // AVX
4710       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4711       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4712     }
4713   } else if (VT.is128BitVector()) {
4714     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4715   } else
4716     llvm_unreachable("Unexpected vector type");
4717
4718   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4719 }
4720
4721 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4722 /// that point to V2 points to its first element.
4723 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4724   for (unsigned i = 0; i != NumElems; ++i) {
4725     if (Mask[i] > (int)NumElems) {
4726       Mask[i] = NumElems;
4727     }
4728   }
4729 }
4730
4731 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4732 /// operation of specified width.
4733 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4734                        SDValue V2) {
4735   unsigned NumElems = VT.getVectorNumElements();
4736   SmallVector<int, 8> Mask;
4737   Mask.push_back(NumElems);
4738   for (unsigned i = 1; i != NumElems; ++i)
4739     Mask.push_back(i);
4740   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4741 }
4742
4743 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4744 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4745                           SDValue V2) {
4746   unsigned NumElems = VT.getVectorNumElements();
4747   SmallVector<int, 8> Mask;
4748   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4749     Mask.push_back(i);
4750     Mask.push_back(i + NumElems);
4751   }
4752   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4753 }
4754
4755 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4756 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4757                           SDValue V2) {
4758   unsigned NumElems = VT.getVectorNumElements();
4759   SmallVector<int, 8> Mask;
4760   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4761     Mask.push_back(i + Half);
4762     Mask.push_back(i + NumElems + Half);
4763   }
4764   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4765 }
4766
4767 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4768 // a generic shuffle instruction because the target has no such instructions.
4769 // Generate shuffles which repeat i16 and i8 several times until they can be
4770 // represented by v4f32 and then be manipulated by target suported shuffles.
4771 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4772   MVT VT = V.getSimpleValueType();
4773   int NumElems = VT.getVectorNumElements();
4774   SDLoc dl(V);
4775
4776   while (NumElems > 4) {
4777     if (EltNo < NumElems/2) {
4778       V = getUnpackl(DAG, dl, VT, V, V);
4779     } else {
4780       V = getUnpackh(DAG, dl, VT, V, V);
4781       EltNo -= NumElems/2;
4782     }
4783     NumElems >>= 1;
4784   }
4785   return V;
4786 }
4787
4788 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4789 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4790   MVT VT = V.getSimpleValueType();
4791   SDLoc dl(V);
4792
4793   if (VT.is128BitVector()) {
4794     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4795     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4796     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4797                              &SplatMask[0]);
4798   } else if (VT.is256BitVector()) {
4799     // To use VPERMILPS to splat scalars, the second half of indicies must
4800     // refer to the higher part, which is a duplication of the lower one,
4801     // because VPERMILPS can only handle in-lane permutations.
4802     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4803                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4804
4805     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4806     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4807                              &SplatMask[0]);
4808   } else
4809     llvm_unreachable("Vector size not supported");
4810
4811   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4812 }
4813
4814 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4815 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4816   MVT SrcVT = SV->getSimpleValueType(0);
4817   SDValue V1 = SV->getOperand(0);
4818   SDLoc dl(SV);
4819
4820   int EltNo = SV->getSplatIndex();
4821   int NumElems = SrcVT.getVectorNumElements();
4822   bool Is256BitVec = SrcVT.is256BitVector();
4823
4824   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4825          "Unknown how to promote splat for type");
4826
4827   // Extract the 128-bit part containing the splat element and update
4828   // the splat element index when it refers to the higher register.
4829   if (Is256BitVec) {
4830     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4831     if (EltNo >= NumElems/2)
4832       EltNo -= NumElems/2;
4833   }
4834
4835   // All i16 and i8 vector types can't be used directly by a generic shuffle
4836   // instruction because the target has no such instruction. Generate shuffles
4837   // which repeat i16 and i8 several times until they fit in i32, and then can
4838   // be manipulated by target suported shuffles.
4839   MVT EltVT = SrcVT.getVectorElementType();
4840   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4841     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4842
4843   // Recreate the 256-bit vector and place the same 128-bit vector
4844   // into the low and high part. This is necessary because we want
4845   // to use VPERM* to shuffle the vectors
4846   if (Is256BitVec) {
4847     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4848   }
4849
4850   return getLegalSplat(DAG, V1, EltNo);
4851 }
4852
4853 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4854 /// vector of zero or undef vector.  This produces a shuffle where the low
4855 /// element of V2 is swizzled into the zero/undef vector, landing at element
4856 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4857 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4858                                            bool IsZero,
4859                                            const X86Subtarget *Subtarget,
4860                                            SelectionDAG &DAG) {
4861   MVT VT = V2.getSimpleValueType();
4862   SDValue V1 = IsZero
4863     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4864   unsigned NumElems = VT.getVectorNumElements();
4865   SmallVector<int, 16> MaskVec;
4866   for (unsigned i = 0; i != NumElems; ++i)
4867     // If this is the insertion idx, put the low elt of V2 here.
4868     MaskVec.push_back(i == Idx ? NumElems : i);
4869   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4870 }
4871
4872 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4873 /// target specific opcode. Returns true if the Mask could be calculated.
4874 /// Sets IsUnary to true if only uses one source.
4875 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4876                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4877   unsigned NumElems = VT.getVectorNumElements();
4878   SDValue ImmN;
4879
4880   IsUnary = false;
4881   switch(N->getOpcode()) {
4882   case X86ISD::SHUFP:
4883     ImmN = N->getOperand(N->getNumOperands()-1);
4884     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4885     break;
4886   case X86ISD::UNPCKH:
4887     DecodeUNPCKHMask(VT, Mask);
4888     break;
4889   case X86ISD::UNPCKL:
4890     DecodeUNPCKLMask(VT, Mask);
4891     break;
4892   case X86ISD::MOVHLPS:
4893     DecodeMOVHLPSMask(NumElems, Mask);
4894     break;
4895   case X86ISD::MOVLHPS:
4896     DecodeMOVLHPSMask(NumElems, Mask);
4897     break;
4898   case X86ISD::PALIGNR:
4899     ImmN = N->getOperand(N->getNumOperands()-1);
4900     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4901     break;
4902   case X86ISD::PSHUFD:
4903   case X86ISD::VPERMILP:
4904     ImmN = N->getOperand(N->getNumOperands()-1);
4905     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4906     IsUnary = true;
4907     break;
4908   case X86ISD::PSHUFHW:
4909     ImmN = N->getOperand(N->getNumOperands()-1);
4910     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4911     IsUnary = true;
4912     break;
4913   case X86ISD::PSHUFLW:
4914     ImmN = N->getOperand(N->getNumOperands()-1);
4915     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4916     IsUnary = true;
4917     break;
4918   case X86ISD::VPERMI:
4919     ImmN = N->getOperand(N->getNumOperands()-1);
4920     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4921     IsUnary = true;
4922     break;
4923   case X86ISD::MOVSS:
4924   case X86ISD::MOVSD: {
4925     // The index 0 always comes from the first element of the second source,
4926     // this is why MOVSS and MOVSD are used in the first place. The other
4927     // elements come from the other positions of the first source vector
4928     Mask.push_back(NumElems);
4929     for (unsigned i = 1; i != NumElems; ++i) {
4930       Mask.push_back(i);
4931     }
4932     break;
4933   }
4934   case X86ISD::VPERM2X128:
4935     ImmN = N->getOperand(N->getNumOperands()-1);
4936     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4937     if (Mask.empty()) return false;
4938     break;
4939   case X86ISD::MOVDDUP:
4940   case X86ISD::MOVLHPD:
4941   case X86ISD::MOVLPD:
4942   case X86ISD::MOVLPS:
4943   case X86ISD::MOVSHDUP:
4944   case X86ISD::MOVSLDUP:
4945     // Not yet implemented
4946     return false;
4947   default: llvm_unreachable("unknown target shuffle node");
4948   }
4949
4950   return true;
4951 }
4952
4953 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4954 /// element of the result of the vector shuffle.
4955 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4956                                    unsigned Depth) {
4957   if (Depth == 6)
4958     return SDValue();  // Limit search depth.
4959
4960   SDValue V = SDValue(N, 0);
4961   EVT VT = V.getValueType();
4962   unsigned Opcode = V.getOpcode();
4963
4964   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4965   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4966     int Elt = SV->getMaskElt(Index);
4967
4968     if (Elt < 0)
4969       return DAG.getUNDEF(VT.getVectorElementType());
4970
4971     unsigned NumElems = VT.getVectorNumElements();
4972     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4973                                          : SV->getOperand(1);
4974     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4975   }
4976
4977   // Recurse into target specific vector shuffles to find scalars.
4978   if (isTargetShuffle(Opcode)) {
4979     MVT ShufVT = V.getSimpleValueType();
4980     unsigned NumElems = ShufVT.getVectorNumElements();
4981     SmallVector<int, 16> ShuffleMask;
4982     bool IsUnary;
4983
4984     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4985       return SDValue();
4986
4987     int Elt = ShuffleMask[Index];
4988     if (Elt < 0)
4989       return DAG.getUNDEF(ShufVT.getVectorElementType());
4990
4991     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4992                                          : N->getOperand(1);
4993     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4994                                Depth+1);
4995   }
4996
4997   // Actual nodes that may contain scalar elements
4998   if (Opcode == ISD::BITCAST) {
4999     V = V.getOperand(0);
5000     EVT SrcVT = V.getValueType();
5001     unsigned NumElems = VT.getVectorNumElements();
5002
5003     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5004       return SDValue();
5005   }
5006
5007   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5008     return (Index == 0) ? V.getOperand(0)
5009                         : DAG.getUNDEF(VT.getVectorElementType());
5010
5011   if (V.getOpcode() == ISD::BUILD_VECTOR)
5012     return V.getOperand(Index);
5013
5014   return SDValue();
5015 }
5016
5017 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5018 /// shuffle operation which come from a consecutively from a zero. The
5019 /// search can start in two different directions, from left or right.
5020 /// We count undefs as zeros until PreferredNum is reached.
5021 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5022                                          unsigned NumElems, bool ZerosFromLeft,
5023                                          SelectionDAG &DAG,
5024                                          unsigned PreferredNum = -1U) {
5025   unsigned NumZeros = 0;
5026   for (unsigned i = 0; i != NumElems; ++i) {
5027     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5028     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5029     if (!Elt.getNode())
5030       break;
5031
5032     if (X86::isZeroNode(Elt))
5033       ++NumZeros;
5034     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5035       NumZeros = std::min(NumZeros + 1, PreferredNum);
5036     else
5037       break;
5038   }
5039
5040   return NumZeros;
5041 }
5042
5043 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5044 /// correspond consecutively to elements from one of the vector operands,
5045 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5046 static
5047 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5048                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5049                               unsigned NumElems, unsigned &OpNum) {
5050   bool SeenV1 = false;
5051   bool SeenV2 = false;
5052
5053   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5054     int Idx = SVOp->getMaskElt(i);
5055     // Ignore undef indicies
5056     if (Idx < 0)
5057       continue;
5058
5059     if (Idx < (int)NumElems)
5060       SeenV1 = true;
5061     else
5062       SeenV2 = true;
5063
5064     // Only accept consecutive elements from the same vector
5065     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5066       return false;
5067   }
5068
5069   OpNum = SeenV1 ? 0 : 1;
5070   return true;
5071 }
5072
5073 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5074 /// logical left shift of a vector.
5075 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5076                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5077   unsigned NumElems =
5078     SVOp->getSimpleValueType(0).getVectorNumElements();
5079   unsigned NumZeros = getNumOfConsecutiveZeros(
5080       SVOp, NumElems, false /* check zeros from right */, DAG,
5081       SVOp->getMaskElt(0));
5082   unsigned OpSrc;
5083
5084   if (!NumZeros)
5085     return false;
5086
5087   // Considering the elements in the mask that are not consecutive zeros,
5088   // check if they consecutively come from only one of the source vectors.
5089   //
5090   //               V1 = {X, A, B, C}     0
5091   //                         \  \  \    /
5092   //   vector_shuffle V1, V2 <1, 2, 3, X>
5093   //
5094   if (!isShuffleMaskConsecutive(SVOp,
5095             0,                   // Mask Start Index
5096             NumElems-NumZeros,   // Mask End Index(exclusive)
5097             NumZeros,            // Where to start looking in the src vector
5098             NumElems,            // Number of elements in vector
5099             OpSrc))              // Which source operand ?
5100     return false;
5101
5102   isLeft = false;
5103   ShAmt = NumZeros;
5104   ShVal = SVOp->getOperand(OpSrc);
5105   return true;
5106 }
5107
5108 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5109 /// logical left shift of a vector.
5110 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5111                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5112   unsigned NumElems =
5113     SVOp->getSimpleValueType(0).getVectorNumElements();
5114   unsigned NumZeros = getNumOfConsecutiveZeros(
5115       SVOp, NumElems, true /* check zeros from left */, DAG,
5116       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5117   unsigned OpSrc;
5118
5119   if (!NumZeros)
5120     return false;
5121
5122   // Considering the elements in the mask that are not consecutive zeros,
5123   // check if they consecutively come from only one of the source vectors.
5124   //
5125   //                           0    { A, B, X, X } = V2
5126   //                          / \    /  /
5127   //   vector_shuffle V1, V2 <X, X, 4, 5>
5128   //
5129   if (!isShuffleMaskConsecutive(SVOp,
5130             NumZeros,     // Mask Start Index
5131             NumElems,     // Mask End Index(exclusive)
5132             0,            // Where to start looking in the src vector
5133             NumElems,     // Number of elements in vector
5134             OpSrc))       // Which source operand ?
5135     return false;
5136
5137   isLeft = true;
5138   ShAmt = NumZeros;
5139   ShVal = SVOp->getOperand(OpSrc);
5140   return true;
5141 }
5142
5143 /// isVectorShift - Returns true if the shuffle can be implemented as a
5144 /// logical left or right shift of a vector.
5145 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5146                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5147   // Although the logic below support any bitwidth size, there are no
5148   // shift instructions which handle more than 128-bit vectors.
5149   if (!SVOp->getSimpleValueType(0).is128BitVector())
5150     return false;
5151
5152   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5153       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5154     return true;
5155
5156   return false;
5157 }
5158
5159 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5160 ///
5161 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5162                                        unsigned NumNonZero, unsigned NumZero,
5163                                        SelectionDAG &DAG,
5164                                        const X86Subtarget* Subtarget,
5165                                        const TargetLowering &TLI) {
5166   if (NumNonZero > 8)
5167     return SDValue();
5168
5169   SDLoc dl(Op);
5170   SDValue V(0, 0);
5171   bool First = true;
5172   for (unsigned i = 0; i < 16; ++i) {
5173     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5174     if (ThisIsNonZero && First) {
5175       if (NumZero)
5176         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5177       else
5178         V = DAG.getUNDEF(MVT::v8i16);
5179       First = false;
5180     }
5181
5182     if ((i & 1) != 0) {
5183       SDValue ThisElt(0, 0), LastElt(0, 0);
5184       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5185       if (LastIsNonZero) {
5186         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5187                               MVT::i16, Op.getOperand(i-1));
5188       }
5189       if (ThisIsNonZero) {
5190         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5191         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5192                               ThisElt, DAG.getConstant(8, MVT::i8));
5193         if (LastIsNonZero)
5194           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5195       } else
5196         ThisElt = LastElt;
5197
5198       if (ThisElt.getNode())
5199         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5200                         DAG.getIntPtrConstant(i/2));
5201     }
5202   }
5203
5204   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5205 }
5206
5207 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5208 ///
5209 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5210                                      unsigned NumNonZero, unsigned NumZero,
5211                                      SelectionDAG &DAG,
5212                                      const X86Subtarget* Subtarget,
5213                                      const TargetLowering &TLI) {
5214   if (NumNonZero > 4)
5215     return SDValue();
5216
5217   SDLoc dl(Op);
5218   SDValue V(0, 0);
5219   bool First = true;
5220   for (unsigned i = 0; i < 8; ++i) {
5221     bool isNonZero = (NonZeros & (1 << i)) != 0;
5222     if (isNonZero) {
5223       if (First) {
5224         if (NumZero)
5225           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5226         else
5227           V = DAG.getUNDEF(MVT::v8i16);
5228         First = false;
5229       }
5230       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5231                       MVT::v8i16, V, Op.getOperand(i),
5232                       DAG.getIntPtrConstant(i));
5233     }
5234   }
5235
5236   return V;
5237 }
5238
5239 /// getVShift - Return a vector logical shift node.
5240 ///
5241 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5242                          unsigned NumBits, SelectionDAG &DAG,
5243                          const TargetLowering &TLI, SDLoc dl) {
5244   assert(VT.is128BitVector() && "Unknown type for VShift");
5245   EVT ShVT = MVT::v2i64;
5246   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5247   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5248   return DAG.getNode(ISD::BITCAST, dl, VT,
5249                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5250                              DAG.getConstant(NumBits,
5251                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5252 }
5253
5254 static SDValue
5255 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5256
5257   // Check if the scalar load can be widened into a vector load. And if
5258   // the address is "base + cst" see if the cst can be "absorbed" into
5259   // the shuffle mask.
5260   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5261     SDValue Ptr = LD->getBasePtr();
5262     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5263       return SDValue();
5264     EVT PVT = LD->getValueType(0);
5265     if (PVT != MVT::i32 && PVT != MVT::f32)
5266       return SDValue();
5267
5268     int FI = -1;
5269     int64_t Offset = 0;
5270     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5271       FI = FINode->getIndex();
5272       Offset = 0;
5273     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5274                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5275       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5276       Offset = Ptr.getConstantOperandVal(1);
5277       Ptr = Ptr.getOperand(0);
5278     } else {
5279       return SDValue();
5280     }
5281
5282     // FIXME: 256-bit vector instructions don't require a strict alignment,
5283     // improve this code to support it better.
5284     unsigned RequiredAlign = VT.getSizeInBits()/8;
5285     SDValue Chain = LD->getChain();
5286     // Make sure the stack object alignment is at least 16 or 32.
5287     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5288     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5289       if (MFI->isFixedObjectIndex(FI)) {
5290         // Can't change the alignment. FIXME: It's possible to compute
5291         // the exact stack offset and reference FI + adjust offset instead.
5292         // If someone *really* cares about this. That's the way to implement it.
5293         return SDValue();
5294       } else {
5295         MFI->setObjectAlignment(FI, RequiredAlign);
5296       }
5297     }
5298
5299     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5300     // Ptr + (Offset & ~15).
5301     if (Offset < 0)
5302       return SDValue();
5303     if ((Offset % RequiredAlign) & 3)
5304       return SDValue();
5305     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5306     if (StartOffset)
5307       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5308                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5309
5310     int EltNo = (Offset - StartOffset) >> 2;
5311     unsigned NumElems = VT.getVectorNumElements();
5312
5313     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5314     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5315                              LD->getPointerInfo().getWithOffset(StartOffset),
5316                              false, false, false, 0);
5317
5318     SmallVector<int, 8> Mask;
5319     for (unsigned i = 0; i != NumElems; ++i)
5320       Mask.push_back(EltNo);
5321
5322     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5323   }
5324
5325   return SDValue();
5326 }
5327
5328 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5329 /// vector of type 'VT', see if the elements can be replaced by a single large
5330 /// load which has the same value as a build_vector whose operands are 'elts'.
5331 ///
5332 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5333 ///
5334 /// FIXME: we'd also like to handle the case where the last elements are zero
5335 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5336 /// There's even a handy isZeroNode for that purpose.
5337 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5338                                         SDLoc &DL, SelectionDAG &DAG) {
5339   EVT EltVT = VT.getVectorElementType();
5340   unsigned NumElems = Elts.size();
5341
5342   LoadSDNode *LDBase = NULL;
5343   unsigned LastLoadedElt = -1U;
5344
5345   // For each element in the initializer, see if we've found a load or an undef.
5346   // If we don't find an initial load element, or later load elements are
5347   // non-consecutive, bail out.
5348   for (unsigned i = 0; i < NumElems; ++i) {
5349     SDValue Elt = Elts[i];
5350
5351     if (!Elt.getNode() ||
5352         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5353       return SDValue();
5354     if (!LDBase) {
5355       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5356         return SDValue();
5357       LDBase = cast<LoadSDNode>(Elt.getNode());
5358       LastLoadedElt = i;
5359       continue;
5360     }
5361     if (Elt.getOpcode() == ISD::UNDEF)
5362       continue;
5363
5364     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5365     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5366       return SDValue();
5367     LastLoadedElt = i;
5368   }
5369
5370   // If we have found an entire vector of loads and undefs, then return a large
5371   // load of the entire vector width starting at the base pointer.  If we found
5372   // consecutive loads for the low half, generate a vzext_load node.
5373   if (LastLoadedElt == NumElems - 1) {
5374     SDValue NewLd = SDValue();
5375     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5376       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5377                           LDBase->getPointerInfo(),
5378                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5379                           LDBase->isInvariant(), 0);
5380     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5381                         LDBase->getPointerInfo(),
5382                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5383                         LDBase->isInvariant(), LDBase->getAlignment());
5384
5385     if (LDBase->hasAnyUseOfValue(1)) {
5386       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5387                                      SDValue(LDBase, 1),
5388                                      SDValue(NewLd.getNode(), 1));
5389       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5390       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5391                              SDValue(NewLd.getNode(), 1));
5392     }
5393
5394     return NewLd;
5395   }
5396   if (NumElems == 4 && LastLoadedElt == 1 &&
5397       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5398     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5399     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5400     SDValue ResNode =
5401         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5402                                 array_lengthof(Ops), MVT::i64,
5403                                 LDBase->getPointerInfo(),
5404                                 LDBase->getAlignment(),
5405                                 false/*isVolatile*/, true/*ReadMem*/,
5406                                 false/*WriteMem*/);
5407
5408     // Make sure the newly-created LOAD is in the same position as LDBase in
5409     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5410     // update uses of LDBase's output chain to use the TokenFactor.
5411     if (LDBase->hasAnyUseOfValue(1)) {
5412       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5413                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5414       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5415       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5416                              SDValue(ResNode.getNode(), 1));
5417     }
5418
5419     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5420   }
5421   return SDValue();
5422 }
5423
5424 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5425 /// to generate a splat value for the following cases:
5426 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5427 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5428 /// a scalar load, or a constant.
5429 /// The VBROADCAST node is returned when a pattern is found,
5430 /// or SDValue() otherwise.
5431 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5432                                     SelectionDAG &DAG) {
5433   if (!Subtarget->hasFp256())
5434     return SDValue();
5435
5436   MVT VT = Op.getSimpleValueType();
5437   SDLoc dl(Op);
5438
5439   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5440          "Unsupported vector type for broadcast.");
5441
5442   SDValue Ld;
5443   bool ConstSplatVal;
5444
5445   switch (Op.getOpcode()) {
5446     default:
5447       // Unknown pattern found.
5448       return SDValue();
5449
5450     case ISD::BUILD_VECTOR: {
5451       // The BUILD_VECTOR node must be a splat.
5452       if (!isSplatVector(Op.getNode()))
5453         return SDValue();
5454
5455       Ld = Op.getOperand(0);
5456       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5457                      Ld.getOpcode() == ISD::ConstantFP);
5458
5459       // The suspected load node has several users. Make sure that all
5460       // of its users are from the BUILD_VECTOR node.
5461       // Constants may have multiple users.
5462       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5463         return SDValue();
5464       break;
5465     }
5466
5467     case ISD::VECTOR_SHUFFLE: {
5468       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5469
5470       // Shuffles must have a splat mask where the first element is
5471       // broadcasted.
5472       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5473         return SDValue();
5474
5475       SDValue Sc = Op.getOperand(0);
5476       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5477           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5478
5479         if (!Subtarget->hasInt256())
5480           return SDValue();
5481
5482         // Use the register form of the broadcast instruction available on AVX2.
5483         if (VT.getSizeInBits() >= 256)
5484           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5485         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5486       }
5487
5488       Ld = Sc.getOperand(0);
5489       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5490                        Ld.getOpcode() == ISD::ConstantFP);
5491
5492       // The scalar_to_vector node and the suspected
5493       // load node must have exactly one user.
5494       // Constants may have multiple users.
5495
5496       // AVX-512 has register version of the broadcast
5497       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5498         Ld.getValueType().getSizeInBits() >= 32;
5499       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5500           !hasRegVer))
5501         return SDValue();
5502       break;
5503     }
5504   }
5505
5506   bool IsGE256 = (VT.getSizeInBits() >= 256);
5507
5508   // Handle the broadcasting a single constant scalar from the constant pool
5509   // into a vector. On Sandybridge it is still better to load a constant vector
5510   // from the constant pool and not to broadcast it from a scalar.
5511   if (ConstSplatVal && Subtarget->hasInt256()) {
5512     EVT CVT = Ld.getValueType();
5513     assert(!CVT.isVector() && "Must not broadcast a vector type");
5514     unsigned ScalarSize = CVT.getSizeInBits();
5515
5516     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5517       const Constant *C = 0;
5518       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5519         C = CI->getConstantIntValue();
5520       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5521         C = CF->getConstantFPValue();
5522
5523       assert(C && "Invalid constant type");
5524
5525       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5526       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5527       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5528       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5529                        MachinePointerInfo::getConstantPool(),
5530                        false, false, false, Alignment);
5531
5532       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5533     }
5534   }
5535
5536   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5537   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5538
5539   // Handle AVX2 in-register broadcasts.
5540   if (!IsLoad && Subtarget->hasInt256() &&
5541       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5542     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5543
5544   // The scalar source must be a normal load.
5545   if (!IsLoad)
5546     return SDValue();
5547
5548   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5549     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5550
5551   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5552   // double since there is no vbroadcastsd xmm
5553   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5554     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5555       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5556   }
5557
5558   // Unsupported broadcast.
5559   return SDValue();
5560 }
5561
5562 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5563   MVT VT = Op.getSimpleValueType();
5564
5565   // Skip if insert_vec_elt is not supported.
5566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5567   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5568     return SDValue();
5569
5570   SDLoc DL(Op);
5571   unsigned NumElems = Op.getNumOperands();
5572
5573   SDValue VecIn1;
5574   SDValue VecIn2;
5575   SmallVector<unsigned, 4> InsertIndices;
5576   SmallVector<int, 8> Mask(NumElems, -1);
5577
5578   for (unsigned i = 0; i != NumElems; ++i) {
5579     unsigned Opc = Op.getOperand(i).getOpcode();
5580
5581     if (Opc == ISD::UNDEF)
5582       continue;
5583
5584     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5585       // Quit if more than 1 elements need inserting.
5586       if (InsertIndices.size() > 1)
5587         return SDValue();
5588
5589       InsertIndices.push_back(i);
5590       continue;
5591     }
5592
5593     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5594     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5595
5596     // Quit if extracted from vector of different type.
5597     if (ExtractedFromVec.getValueType() != VT)
5598       return SDValue();
5599
5600     // Quit if non-constant index.
5601     if (!isa<ConstantSDNode>(ExtIdx))
5602       return SDValue();
5603
5604     if (VecIn1.getNode() == 0)
5605       VecIn1 = ExtractedFromVec;
5606     else if (VecIn1 != ExtractedFromVec) {
5607       if (VecIn2.getNode() == 0)
5608         VecIn2 = ExtractedFromVec;
5609       else if (VecIn2 != ExtractedFromVec)
5610         // Quit if more than 2 vectors to shuffle
5611         return SDValue();
5612     }
5613
5614     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5615
5616     if (ExtractedFromVec == VecIn1)
5617       Mask[i] = Idx;
5618     else if (ExtractedFromVec == VecIn2)
5619       Mask[i] = Idx + NumElems;
5620   }
5621
5622   if (VecIn1.getNode() == 0)
5623     return SDValue();
5624
5625   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5626   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5627   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5628     unsigned Idx = InsertIndices[i];
5629     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5630                      DAG.getIntPtrConstant(Idx));
5631   }
5632
5633   return NV;
5634 }
5635
5636 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5637 SDValue
5638 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5639
5640   MVT VT = Op.getSimpleValueType();
5641   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5642          "Unexpected type in LowerBUILD_VECTORvXi1!");
5643
5644   SDLoc dl(Op);
5645   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5646     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5647     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5648                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5649     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5650                        Ops, VT.getVectorNumElements());
5651   }
5652
5653   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5654     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5655     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5656                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5657     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5658                        Ops, VT.getVectorNumElements());
5659   }
5660
5661   bool AllContants = true;
5662   uint64_t Immediate = 0;
5663   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5664     SDValue In = Op.getOperand(idx);
5665     if (In.getOpcode() == ISD::UNDEF)
5666       continue;
5667     if (!isa<ConstantSDNode>(In)) {
5668       AllContants = false;
5669       break;
5670     }
5671     if (cast<ConstantSDNode>(In)->getZExtValue())
5672       Immediate |= (1ULL << idx);
5673   }
5674
5675   if (AllContants) {
5676     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5677       DAG.getConstant(Immediate, MVT::i16));
5678     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5679                        DAG.getIntPtrConstant(0));
5680   }
5681
5682   if (!isSplatVector(Op.getNode()))
5683     llvm_unreachable("Unsupported predicate operation");
5684
5685   SDValue In = Op.getOperand(0);
5686   SDValue EFLAGS, X86CC;
5687   if (In.getOpcode() == ISD::SETCC) {
5688     SDValue Op0 = In.getOperand(0);
5689     SDValue Op1 = In.getOperand(1);
5690     ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5691     bool isFP = Op1.getValueType().isFloatingPoint();
5692     unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5693
5694     assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5695
5696     X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5697     EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5698     EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5699   } else if (In.getOpcode() == X86ISD::SETCC) {
5700     X86CC = In.getOperand(0);
5701     EFLAGS = In.getOperand(1);
5702   } else {
5703     // The algorithm:
5704     //   Bit1 = In & 0x1
5705     //   if (Bit1 != 0)
5706     //     ZF = 0
5707     //   else
5708     //     ZF = 1
5709     //   if (ZF == 0)
5710     //     res = allOnes ### CMOVNE -1, %res
5711     //   else
5712     //     res = allZero
5713     MVT InVT = In.getSimpleValueType();
5714     SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5715     EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5716     X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5717   }
5718
5719   if (VT == MVT::v16i1) {
5720     SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5721     SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5722     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5723           Cst0, Cst1, X86CC, EFLAGS);
5724     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5725   }
5726
5727   if (VT == MVT::v8i1) {
5728     SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5729     SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5730     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5731           Cst0, Cst1, X86CC, EFLAGS);
5732     CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5733     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5734   }
5735   llvm_unreachable("Unsupported predicate operation");
5736 }
5737
5738 SDValue
5739 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5740   SDLoc dl(Op);
5741
5742   MVT VT = Op.getSimpleValueType();
5743   MVT ExtVT = VT.getVectorElementType();
5744   unsigned NumElems = Op.getNumOperands();
5745
5746   // Generate vectors for predicate vectors.
5747   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5748     return LowerBUILD_VECTORvXi1(Op, DAG);
5749
5750   // Vectors containing all zeros can be matched by pxor and xorps later
5751   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5752     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5753     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5754     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5755       return Op;
5756
5757     return getZeroVector(VT, Subtarget, DAG, dl);
5758   }
5759
5760   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5761   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5762   // vpcmpeqd on 256-bit vectors.
5763   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5764     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5765       return Op;
5766
5767     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5768   }
5769
5770   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5771   if (Broadcast.getNode())
5772     return Broadcast;
5773
5774   unsigned EVTBits = ExtVT.getSizeInBits();
5775
5776   unsigned NumZero  = 0;
5777   unsigned NumNonZero = 0;
5778   unsigned NonZeros = 0;
5779   bool IsAllConstants = true;
5780   SmallSet<SDValue, 8> Values;
5781   for (unsigned i = 0; i < NumElems; ++i) {
5782     SDValue Elt = Op.getOperand(i);
5783     if (Elt.getOpcode() == ISD::UNDEF)
5784       continue;
5785     Values.insert(Elt);
5786     if (Elt.getOpcode() != ISD::Constant &&
5787         Elt.getOpcode() != ISD::ConstantFP)
5788       IsAllConstants = false;
5789     if (X86::isZeroNode(Elt))
5790       NumZero++;
5791     else {
5792       NonZeros |= (1 << i);
5793       NumNonZero++;
5794     }
5795   }
5796
5797   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5798   if (NumNonZero == 0)
5799     return DAG.getUNDEF(VT);
5800
5801   // Special case for single non-zero, non-undef, element.
5802   if (NumNonZero == 1) {
5803     unsigned Idx = countTrailingZeros(NonZeros);
5804     SDValue Item = Op.getOperand(Idx);
5805
5806     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5807     // the value are obviously zero, truncate the value to i32 and do the
5808     // insertion that way.  Only do this if the value is non-constant or if the
5809     // value is a constant being inserted into element 0.  It is cheaper to do
5810     // a constant pool load than it is to do a movd + shuffle.
5811     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5812         (!IsAllConstants || Idx == 0)) {
5813       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5814         // Handle SSE only.
5815         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5816         EVT VecVT = MVT::v4i32;
5817         unsigned VecElts = 4;
5818
5819         // Truncate the value (which may itself be a constant) to i32, and
5820         // convert it to a vector with movd (S2V+shuffle to zero extend).
5821         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5822         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5823         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5824
5825         // Now we have our 32-bit value zero extended in the low element of
5826         // a vector.  If Idx != 0, swizzle it into place.
5827         if (Idx != 0) {
5828           SmallVector<int, 4> Mask;
5829           Mask.push_back(Idx);
5830           for (unsigned i = 1; i != VecElts; ++i)
5831             Mask.push_back(i);
5832           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5833                                       &Mask[0]);
5834         }
5835         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5836       }
5837     }
5838
5839     // If we have a constant or non-constant insertion into the low element of
5840     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5841     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5842     // depending on what the source datatype is.
5843     if (Idx == 0) {
5844       if (NumZero == 0)
5845         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5846
5847       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5848           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5849         if (VT.is256BitVector()) {
5850           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5851           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5852                              Item, DAG.getIntPtrConstant(0));
5853         }
5854         assert(VT.is128BitVector() && "Expected an SSE value type!");
5855         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5856         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5857         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5858       }
5859
5860       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5861         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5862         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5863         if (VT.is256BitVector()) {
5864           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5865           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5866         } else {
5867           assert(VT.is128BitVector() && "Expected an SSE value type!");
5868           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5869         }
5870         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5871       }
5872     }
5873
5874     // Is it a vector logical left shift?
5875     if (NumElems == 2 && Idx == 1 &&
5876         X86::isZeroNode(Op.getOperand(0)) &&
5877         !X86::isZeroNode(Op.getOperand(1))) {
5878       unsigned NumBits = VT.getSizeInBits();
5879       return getVShift(true, VT,
5880                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5881                                    VT, Op.getOperand(1)),
5882                        NumBits/2, DAG, *this, dl);
5883     }
5884
5885     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5886       return SDValue();
5887
5888     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5889     // is a non-constant being inserted into an element other than the low one,
5890     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5891     // movd/movss) to move this into the low element, then shuffle it into
5892     // place.
5893     if (EVTBits == 32) {
5894       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5895
5896       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5897       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5898       SmallVector<int, 8> MaskVec;
5899       for (unsigned i = 0; i != NumElems; ++i)
5900         MaskVec.push_back(i == Idx ? 0 : 1);
5901       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5902     }
5903   }
5904
5905   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5906   if (Values.size() == 1) {
5907     if (EVTBits == 32) {
5908       // Instead of a shuffle like this:
5909       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5910       // Check if it's possible to issue this instead.
5911       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5912       unsigned Idx = countTrailingZeros(NonZeros);
5913       SDValue Item = Op.getOperand(Idx);
5914       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5915         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5916     }
5917     return SDValue();
5918   }
5919
5920   // A vector full of immediates; various special cases are already
5921   // handled, so this is best done with a single constant-pool load.
5922   if (IsAllConstants)
5923     return SDValue();
5924
5925   // For AVX-length vectors, build the individual 128-bit pieces and use
5926   // shuffles to put them in place.
5927   if (VT.is256BitVector()) {
5928     SmallVector<SDValue, 32> V;
5929     for (unsigned i = 0; i != NumElems; ++i)
5930       V.push_back(Op.getOperand(i));
5931
5932     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5933
5934     // Build both the lower and upper subvector.
5935     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5936     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5937                                 NumElems/2);
5938
5939     // Recreate the wider vector with the lower and upper part.
5940     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5941   }
5942
5943   // Let legalizer expand 2-wide build_vectors.
5944   if (EVTBits == 64) {
5945     if (NumNonZero == 1) {
5946       // One half is zero or undef.
5947       unsigned Idx = countTrailingZeros(NonZeros);
5948       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5949                                  Op.getOperand(Idx));
5950       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5951     }
5952     return SDValue();
5953   }
5954
5955   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5956   if (EVTBits == 8 && NumElems == 16) {
5957     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5958                                         Subtarget, *this);
5959     if (V.getNode()) return V;
5960   }
5961
5962   if (EVTBits == 16 && NumElems == 8) {
5963     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5964                                       Subtarget, *this);
5965     if (V.getNode()) return V;
5966   }
5967
5968   // If element VT is == 32 bits, turn it into a number of shuffles.
5969   SmallVector<SDValue, 8> V(NumElems);
5970   if (NumElems == 4 && NumZero > 0) {
5971     for (unsigned i = 0; i < 4; ++i) {
5972       bool isZero = !(NonZeros & (1 << i));
5973       if (isZero)
5974         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5975       else
5976         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5977     }
5978
5979     for (unsigned i = 0; i < 2; ++i) {
5980       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5981         default: break;
5982         case 0:
5983           V[i] = V[i*2];  // Must be a zero vector.
5984           break;
5985         case 1:
5986           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5987           break;
5988         case 2:
5989           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5990           break;
5991         case 3:
5992           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5993           break;
5994       }
5995     }
5996
5997     bool Reverse1 = (NonZeros & 0x3) == 2;
5998     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5999     int MaskVec[] = {
6000       Reverse1 ? 1 : 0,
6001       Reverse1 ? 0 : 1,
6002       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6003       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6004     };
6005     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6006   }
6007
6008   if (Values.size() > 1 && VT.is128BitVector()) {
6009     // Check for a build vector of consecutive loads.
6010     for (unsigned i = 0; i < NumElems; ++i)
6011       V[i] = Op.getOperand(i);
6012
6013     // Check for elements which are consecutive loads.
6014     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
6015     if (LD.getNode())
6016       return LD;
6017
6018     // Check for a build vector from mostly shuffle plus few inserting.
6019     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6020     if (Sh.getNode())
6021       return Sh;
6022
6023     // For SSE 4.1, use insertps to put the high elements into the low element.
6024     if (getSubtarget()->hasSSE41()) {
6025       SDValue Result;
6026       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6027         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6028       else
6029         Result = DAG.getUNDEF(VT);
6030
6031       for (unsigned i = 1; i < NumElems; ++i) {
6032         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6033         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6034                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6035       }
6036       return Result;
6037     }
6038
6039     // Otherwise, expand into a number of unpckl*, start by extending each of
6040     // our (non-undef) elements to the full vector width with the element in the
6041     // bottom slot of the vector (which generates no code for SSE).
6042     for (unsigned i = 0; i < NumElems; ++i) {
6043       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6044         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6045       else
6046         V[i] = DAG.getUNDEF(VT);
6047     }
6048
6049     // Next, we iteratively mix elements, e.g. for v4f32:
6050     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6051     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6052     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6053     unsigned EltStride = NumElems >> 1;
6054     while (EltStride != 0) {
6055       for (unsigned i = 0; i < EltStride; ++i) {
6056         // If V[i+EltStride] is undef and this is the first round of mixing,
6057         // then it is safe to just drop this shuffle: V[i] is already in the
6058         // right place, the one element (since it's the first round) being
6059         // inserted as undef can be dropped.  This isn't safe for successive
6060         // rounds because they will permute elements within both vectors.
6061         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6062             EltStride == NumElems/2)
6063           continue;
6064
6065         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6066       }
6067       EltStride >>= 1;
6068     }
6069     return V[0];
6070   }
6071   return SDValue();
6072 }
6073
6074 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6075 // to create 256-bit vectors from two other 128-bit ones.
6076 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6077   SDLoc dl(Op);
6078   MVT ResVT = Op.getSimpleValueType();
6079
6080   assert((ResVT.is256BitVector() ||
6081           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6082
6083   SDValue V1 = Op.getOperand(0);
6084   SDValue V2 = Op.getOperand(1);
6085   unsigned NumElems = ResVT.getVectorNumElements();
6086   if(ResVT.is256BitVector())
6087     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6088
6089   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6090 }
6091
6092 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6093   assert(Op.getNumOperands() == 2);
6094
6095   // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors
6096   // from two other 128-bit ones.
6097   return LowerAVXCONCAT_VECTORS(Op, DAG);
6098 }
6099
6100 // Try to lower a shuffle node into a simple blend instruction.
6101 static SDValue
6102 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6103                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6104   SDValue V1 = SVOp->getOperand(0);
6105   SDValue V2 = SVOp->getOperand(1);
6106   SDLoc dl(SVOp);
6107   MVT VT = SVOp->getSimpleValueType(0);
6108   MVT EltVT = VT.getVectorElementType();
6109   unsigned NumElems = VT.getVectorNumElements();
6110
6111   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6112     return SDValue();
6113   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6114     return SDValue();
6115
6116   // Check the mask for BLEND and build the value.
6117   unsigned MaskValue = 0;
6118   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6119   unsigned NumLanes = (NumElems-1)/8 + 1;
6120   unsigned NumElemsInLane = NumElems / NumLanes;
6121
6122   // Blend for v16i16 should be symetric for the both lanes.
6123   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6124
6125     int SndLaneEltIdx = (NumLanes == 2) ?
6126       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6127     int EltIdx = SVOp->getMaskElt(i);
6128
6129     if ((EltIdx < 0 || EltIdx == (int)i) &&
6130         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6131       continue;
6132
6133     if (((unsigned)EltIdx == (i + NumElems)) &&
6134         (SndLaneEltIdx < 0 ||
6135          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6136       MaskValue |= (1<<i);
6137     else
6138       return SDValue();
6139   }
6140
6141   // Convert i32 vectors to floating point if it is not AVX2.
6142   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6143   MVT BlendVT = VT;
6144   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6145     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6146                                NumElems);
6147     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6148     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6149   }
6150
6151   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6152                             DAG.getConstant(MaskValue, MVT::i32));
6153   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6154 }
6155
6156 // v8i16 shuffles - Prefer shuffles in the following order:
6157 // 1. [all]   pshuflw, pshufhw, optional move
6158 // 2. [ssse3] 1 x pshufb
6159 // 3. [ssse3] 2 x pshufb + 1 x por
6160 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6161 static SDValue
6162 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6163                          SelectionDAG &DAG) {
6164   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6165   SDValue V1 = SVOp->getOperand(0);
6166   SDValue V2 = SVOp->getOperand(1);
6167   SDLoc dl(SVOp);
6168   SmallVector<int, 8> MaskVals;
6169
6170   // Determine if more than 1 of the words in each of the low and high quadwords
6171   // of the result come from the same quadword of one of the two inputs.  Undef
6172   // mask values count as coming from any quadword, for better codegen.
6173   unsigned LoQuad[] = { 0, 0, 0, 0 };
6174   unsigned HiQuad[] = { 0, 0, 0, 0 };
6175   std::bitset<4> InputQuads;
6176   for (unsigned i = 0; i < 8; ++i) {
6177     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6178     int EltIdx = SVOp->getMaskElt(i);
6179     MaskVals.push_back(EltIdx);
6180     if (EltIdx < 0) {
6181       ++Quad[0];
6182       ++Quad[1];
6183       ++Quad[2];
6184       ++Quad[3];
6185       continue;
6186     }
6187     ++Quad[EltIdx / 4];
6188     InputQuads.set(EltIdx / 4);
6189   }
6190
6191   int BestLoQuad = -1;
6192   unsigned MaxQuad = 1;
6193   for (unsigned i = 0; i < 4; ++i) {
6194     if (LoQuad[i] > MaxQuad) {
6195       BestLoQuad = i;
6196       MaxQuad = LoQuad[i];
6197     }
6198   }
6199
6200   int BestHiQuad = -1;
6201   MaxQuad = 1;
6202   for (unsigned i = 0; i < 4; ++i) {
6203     if (HiQuad[i] > MaxQuad) {
6204       BestHiQuad = i;
6205       MaxQuad = HiQuad[i];
6206     }
6207   }
6208
6209   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6210   // of the two input vectors, shuffle them into one input vector so only a
6211   // single pshufb instruction is necessary. If There are more than 2 input
6212   // quads, disable the next transformation since it does not help SSSE3.
6213   bool V1Used = InputQuads[0] || InputQuads[1];
6214   bool V2Used = InputQuads[2] || InputQuads[3];
6215   if (Subtarget->hasSSSE3()) {
6216     if (InputQuads.count() == 2 && V1Used && V2Used) {
6217       BestLoQuad = InputQuads[0] ? 0 : 1;
6218       BestHiQuad = InputQuads[2] ? 2 : 3;
6219     }
6220     if (InputQuads.count() > 2) {
6221       BestLoQuad = -1;
6222       BestHiQuad = -1;
6223     }
6224   }
6225
6226   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6227   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6228   // words from all 4 input quadwords.
6229   SDValue NewV;
6230   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6231     int MaskV[] = {
6232       BestLoQuad < 0 ? 0 : BestLoQuad,
6233       BestHiQuad < 0 ? 1 : BestHiQuad
6234     };
6235     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6236                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6237                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6238     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6239
6240     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6241     // source words for the shuffle, to aid later transformations.
6242     bool AllWordsInNewV = true;
6243     bool InOrder[2] = { true, true };
6244     for (unsigned i = 0; i != 8; ++i) {
6245       int idx = MaskVals[i];
6246       if (idx != (int)i)
6247         InOrder[i/4] = false;
6248       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6249         continue;
6250       AllWordsInNewV = false;
6251       break;
6252     }
6253
6254     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6255     if (AllWordsInNewV) {
6256       for (int i = 0; i != 8; ++i) {
6257         int idx = MaskVals[i];
6258         if (idx < 0)
6259           continue;
6260         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6261         if ((idx != i) && idx < 4)
6262           pshufhw = false;
6263         if ((idx != i) && idx > 3)
6264           pshuflw = false;
6265       }
6266       V1 = NewV;
6267       V2Used = false;
6268       BestLoQuad = 0;
6269       BestHiQuad = 1;
6270     }
6271
6272     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6273     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6274     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6275       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6276       unsigned TargetMask = 0;
6277       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6278                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6279       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6280       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6281                              getShufflePSHUFLWImmediate(SVOp);
6282       V1 = NewV.getOperand(0);
6283       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6284     }
6285   }
6286
6287   // Promote splats to a larger type which usually leads to more efficient code.
6288   // FIXME: Is this true if pshufb is available?
6289   if (SVOp->isSplat())
6290     return PromoteSplat(SVOp, DAG);
6291
6292   // If we have SSSE3, and all words of the result are from 1 input vector,
6293   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6294   // is present, fall back to case 4.
6295   if (Subtarget->hasSSSE3()) {
6296     SmallVector<SDValue,16> pshufbMask;
6297
6298     // If we have elements from both input vectors, set the high bit of the
6299     // shuffle mask element to zero out elements that come from V2 in the V1
6300     // mask, and elements that come from V1 in the V2 mask, so that the two
6301     // results can be OR'd together.
6302     bool TwoInputs = V1Used && V2Used;
6303     for (unsigned i = 0; i != 8; ++i) {
6304       int EltIdx = MaskVals[i] * 2;
6305       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6306       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6307       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6308       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6309     }
6310     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6311     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6312                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6313                                  MVT::v16i8, &pshufbMask[0], 16));
6314     if (!TwoInputs)
6315       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6316
6317     // Calculate the shuffle mask for the second input, shuffle it, and
6318     // OR it with the first shuffled input.
6319     pshufbMask.clear();
6320     for (unsigned i = 0; i != 8; ++i) {
6321       int EltIdx = MaskVals[i] * 2;
6322       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6323       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6324       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6325       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6326     }
6327     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6328     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6329                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6330                                  MVT::v16i8, &pshufbMask[0], 16));
6331     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6332     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6333   }
6334
6335   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6336   // and update MaskVals with new element order.
6337   std::bitset<8> InOrder;
6338   if (BestLoQuad >= 0) {
6339     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6340     for (int i = 0; i != 4; ++i) {
6341       int idx = MaskVals[i];
6342       if (idx < 0) {
6343         InOrder.set(i);
6344       } else if ((idx / 4) == BestLoQuad) {
6345         MaskV[i] = idx & 3;
6346         InOrder.set(i);
6347       }
6348     }
6349     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6350                                 &MaskV[0]);
6351
6352     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6353       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6354       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6355                                   NewV.getOperand(0),
6356                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6357     }
6358   }
6359
6360   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6361   // and update MaskVals with the new element order.
6362   if (BestHiQuad >= 0) {
6363     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6364     for (unsigned i = 4; i != 8; ++i) {
6365       int idx = MaskVals[i];
6366       if (idx < 0) {
6367         InOrder.set(i);
6368       } else if ((idx / 4) == BestHiQuad) {
6369         MaskV[i] = (idx & 3) + 4;
6370         InOrder.set(i);
6371       }
6372     }
6373     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6374                                 &MaskV[0]);
6375
6376     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6377       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6378       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6379                                   NewV.getOperand(0),
6380                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6381     }
6382   }
6383
6384   // In case BestHi & BestLo were both -1, which means each quadword has a word
6385   // from each of the four input quadwords, calculate the InOrder bitvector now
6386   // before falling through to the insert/extract cleanup.
6387   if (BestLoQuad == -1 && BestHiQuad == -1) {
6388     NewV = V1;
6389     for (int i = 0; i != 8; ++i)
6390       if (MaskVals[i] < 0 || MaskVals[i] == i)
6391         InOrder.set(i);
6392   }
6393
6394   // The other elements are put in the right place using pextrw and pinsrw.
6395   for (unsigned i = 0; i != 8; ++i) {
6396     if (InOrder[i])
6397       continue;
6398     int EltIdx = MaskVals[i];
6399     if (EltIdx < 0)
6400       continue;
6401     SDValue ExtOp = (EltIdx < 8) ?
6402       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6403                   DAG.getIntPtrConstant(EltIdx)) :
6404       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6405                   DAG.getIntPtrConstant(EltIdx - 8));
6406     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6407                        DAG.getIntPtrConstant(i));
6408   }
6409   return NewV;
6410 }
6411
6412 // v16i8 shuffles - Prefer shuffles in the following order:
6413 // 1. [ssse3] 1 x pshufb
6414 // 2. [ssse3] 2 x pshufb + 1 x por
6415 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6416 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6417                                         const X86Subtarget* Subtarget,
6418                                         SelectionDAG &DAG) {
6419   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6420   SDValue V1 = SVOp->getOperand(0);
6421   SDValue V2 = SVOp->getOperand(1);
6422   SDLoc dl(SVOp);
6423   ArrayRef<int> MaskVals = SVOp->getMask();
6424
6425   // Promote splats to a larger type which usually leads to more efficient code.
6426   // FIXME: Is this true if pshufb is available?
6427   if (SVOp->isSplat())
6428     return PromoteSplat(SVOp, DAG);
6429
6430   // If we have SSSE3, case 1 is generated when all result bytes come from
6431   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6432   // present, fall back to case 3.
6433
6434   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6435   if (Subtarget->hasSSSE3()) {
6436     SmallVector<SDValue,16> pshufbMask;
6437
6438     // If all result elements are from one input vector, then only translate
6439     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6440     //
6441     // Otherwise, we have elements from both input vectors, and must zero out
6442     // elements that come from V2 in the first mask, and V1 in the second mask
6443     // so that we can OR them together.
6444     for (unsigned i = 0; i != 16; ++i) {
6445       int EltIdx = MaskVals[i];
6446       if (EltIdx < 0 || EltIdx >= 16)
6447         EltIdx = 0x80;
6448       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6449     }
6450     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6451                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6452                                  MVT::v16i8, &pshufbMask[0], 16));
6453
6454     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6455     // the 2nd operand if it's undefined or zero.
6456     if (V2.getOpcode() == ISD::UNDEF ||
6457         ISD::isBuildVectorAllZeros(V2.getNode()))
6458       return V1;
6459
6460     // Calculate the shuffle mask for the second input, shuffle it, and
6461     // OR it with the first shuffled input.
6462     pshufbMask.clear();
6463     for (unsigned i = 0; i != 16; ++i) {
6464       int EltIdx = MaskVals[i];
6465       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6466       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6467     }
6468     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6469                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6470                                  MVT::v16i8, &pshufbMask[0], 16));
6471     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6472   }
6473
6474   // No SSSE3 - Calculate in place words and then fix all out of place words
6475   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6476   // the 16 different words that comprise the two doublequadword input vectors.
6477   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6478   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6479   SDValue NewV = V1;
6480   for (int i = 0; i != 8; ++i) {
6481     int Elt0 = MaskVals[i*2];
6482     int Elt1 = MaskVals[i*2+1];
6483
6484     // This word of the result is all undef, skip it.
6485     if (Elt0 < 0 && Elt1 < 0)
6486       continue;
6487
6488     // This word of the result is already in the correct place, skip it.
6489     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6490       continue;
6491
6492     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6493     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6494     SDValue InsElt;
6495
6496     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6497     // using a single extract together, load it and store it.
6498     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6499       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6500                            DAG.getIntPtrConstant(Elt1 / 2));
6501       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6502                         DAG.getIntPtrConstant(i));
6503       continue;
6504     }
6505
6506     // If Elt1 is defined, extract it from the appropriate source.  If the
6507     // source byte is not also odd, shift the extracted word left 8 bits
6508     // otherwise clear the bottom 8 bits if we need to do an or.
6509     if (Elt1 >= 0) {
6510       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6511                            DAG.getIntPtrConstant(Elt1 / 2));
6512       if ((Elt1 & 1) == 0)
6513         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6514                              DAG.getConstant(8,
6515                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6516       else if (Elt0 >= 0)
6517         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6518                              DAG.getConstant(0xFF00, MVT::i16));
6519     }
6520     // If Elt0 is defined, extract it from the appropriate source.  If the
6521     // source byte is not also even, shift the extracted word right 8 bits. If
6522     // Elt1 was also defined, OR the extracted values together before
6523     // inserting them in the result.
6524     if (Elt0 >= 0) {
6525       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6526                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6527       if ((Elt0 & 1) != 0)
6528         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6529                               DAG.getConstant(8,
6530                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6531       else if (Elt1 >= 0)
6532         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6533                              DAG.getConstant(0x00FF, MVT::i16));
6534       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6535                          : InsElt0;
6536     }
6537     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6538                        DAG.getIntPtrConstant(i));
6539   }
6540   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6541 }
6542
6543 // v32i8 shuffles - Translate to VPSHUFB if possible.
6544 static
6545 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6546                                  const X86Subtarget *Subtarget,
6547                                  SelectionDAG &DAG) {
6548   MVT VT = SVOp->getSimpleValueType(0);
6549   SDValue V1 = SVOp->getOperand(0);
6550   SDValue V2 = SVOp->getOperand(1);
6551   SDLoc dl(SVOp);
6552   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6553
6554   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6555   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6556   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6557
6558   // VPSHUFB may be generated if
6559   // (1) one of input vector is undefined or zeroinitializer.
6560   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6561   // And (2) the mask indexes don't cross the 128-bit lane.
6562   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6563       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6564     return SDValue();
6565
6566   if (V1IsAllZero && !V2IsAllZero) {
6567     CommuteVectorShuffleMask(MaskVals, 32);
6568     V1 = V2;
6569   }
6570   SmallVector<SDValue, 32> pshufbMask;
6571   for (unsigned i = 0; i != 32; i++) {
6572     int EltIdx = MaskVals[i];
6573     if (EltIdx < 0 || EltIdx >= 32)
6574       EltIdx = 0x80;
6575     else {
6576       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6577         // Cross lane is not allowed.
6578         return SDValue();
6579       EltIdx &= 0xf;
6580     }
6581     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6582   }
6583   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6584                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6585                                   MVT::v32i8, &pshufbMask[0], 32));
6586 }
6587
6588 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6589 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6590 /// done when every pair / quad of shuffle mask elements point to elements in
6591 /// the right sequence. e.g.
6592 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6593 static
6594 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6595                                  SelectionDAG &DAG) {
6596   MVT VT = SVOp->getSimpleValueType(0);
6597   SDLoc dl(SVOp);
6598   unsigned NumElems = VT.getVectorNumElements();
6599   MVT NewVT;
6600   unsigned Scale;
6601   switch (VT.SimpleTy) {
6602   default: llvm_unreachable("Unexpected!");
6603   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6604   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6605   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6606   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6607   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6608   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6609   }
6610
6611   SmallVector<int, 8> MaskVec;
6612   for (unsigned i = 0; i != NumElems; i += Scale) {
6613     int StartIdx = -1;
6614     for (unsigned j = 0; j != Scale; ++j) {
6615       int EltIdx = SVOp->getMaskElt(i+j);
6616       if (EltIdx < 0)
6617         continue;
6618       if (StartIdx < 0)
6619         StartIdx = (EltIdx / Scale);
6620       if (EltIdx != (int)(StartIdx*Scale + j))
6621         return SDValue();
6622     }
6623     MaskVec.push_back(StartIdx);
6624   }
6625
6626   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6627   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6628   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6629 }
6630
6631 /// getVZextMovL - Return a zero-extending vector move low node.
6632 ///
6633 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6634                             SDValue SrcOp, SelectionDAG &DAG,
6635                             const X86Subtarget *Subtarget, SDLoc dl) {
6636   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6637     LoadSDNode *LD = NULL;
6638     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6639       LD = dyn_cast<LoadSDNode>(SrcOp);
6640     if (!LD) {
6641       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6642       // instead.
6643       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6644       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6645           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6646           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6647           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6648         // PR2108
6649         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6650         return DAG.getNode(ISD::BITCAST, dl, VT,
6651                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6652                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6653                                                    OpVT,
6654                                                    SrcOp.getOperand(0)
6655                                                           .getOperand(0))));
6656       }
6657     }
6658   }
6659
6660   return DAG.getNode(ISD::BITCAST, dl, VT,
6661                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6662                                  DAG.getNode(ISD::BITCAST, dl,
6663                                              OpVT, SrcOp)));
6664 }
6665
6666 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6667 /// which could not be matched by any known target speficic shuffle
6668 static SDValue
6669 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6670
6671   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6672   if (NewOp.getNode())
6673     return NewOp;
6674
6675   MVT VT = SVOp->getSimpleValueType(0);
6676
6677   unsigned NumElems = VT.getVectorNumElements();
6678   unsigned NumLaneElems = NumElems / 2;
6679
6680   SDLoc dl(SVOp);
6681   MVT EltVT = VT.getVectorElementType();
6682   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6683   SDValue Output[2];
6684
6685   SmallVector<int, 16> Mask;
6686   for (unsigned l = 0; l < 2; ++l) {
6687     // Build a shuffle mask for the output, discovering on the fly which
6688     // input vectors to use as shuffle operands (recorded in InputUsed).
6689     // If building a suitable shuffle vector proves too hard, then bail
6690     // out with UseBuildVector set.
6691     bool UseBuildVector = false;
6692     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6693     unsigned LaneStart = l * NumLaneElems;
6694     for (unsigned i = 0; i != NumLaneElems; ++i) {
6695       // The mask element.  This indexes into the input.
6696       int Idx = SVOp->getMaskElt(i+LaneStart);
6697       if (Idx < 0) {
6698         // the mask element does not index into any input vector.
6699         Mask.push_back(-1);
6700         continue;
6701       }
6702
6703       // The input vector this mask element indexes into.
6704       int Input = Idx / NumLaneElems;
6705
6706       // Turn the index into an offset from the start of the input vector.
6707       Idx -= Input * NumLaneElems;
6708
6709       // Find or create a shuffle vector operand to hold this input.
6710       unsigned OpNo;
6711       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6712         if (InputUsed[OpNo] == Input)
6713           // This input vector is already an operand.
6714           break;
6715         if (InputUsed[OpNo] < 0) {
6716           // Create a new operand for this input vector.
6717           InputUsed[OpNo] = Input;
6718           break;
6719         }
6720       }
6721
6722       if (OpNo >= array_lengthof(InputUsed)) {
6723         // More than two input vectors used!  Give up on trying to create a
6724         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6725         UseBuildVector = true;
6726         break;
6727       }
6728
6729       // Add the mask index for the new shuffle vector.
6730       Mask.push_back(Idx + OpNo * NumLaneElems);
6731     }
6732
6733     if (UseBuildVector) {
6734       SmallVector<SDValue, 16> SVOps;
6735       for (unsigned i = 0; i != NumLaneElems; ++i) {
6736         // The mask element.  This indexes into the input.
6737         int Idx = SVOp->getMaskElt(i+LaneStart);
6738         if (Idx < 0) {
6739           SVOps.push_back(DAG.getUNDEF(EltVT));
6740           continue;
6741         }
6742
6743         // The input vector this mask element indexes into.
6744         int Input = Idx / NumElems;
6745
6746         // Turn the index into an offset from the start of the input vector.
6747         Idx -= Input * NumElems;
6748
6749         // Extract the vector element by hand.
6750         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6751                                     SVOp->getOperand(Input),
6752                                     DAG.getIntPtrConstant(Idx)));
6753       }
6754
6755       // Construct the output using a BUILD_VECTOR.
6756       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6757                               SVOps.size());
6758     } else if (InputUsed[0] < 0) {
6759       // No input vectors were used! The result is undefined.
6760       Output[l] = DAG.getUNDEF(NVT);
6761     } else {
6762       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6763                                         (InputUsed[0] % 2) * NumLaneElems,
6764                                         DAG, dl);
6765       // If only one input was used, use an undefined vector for the other.
6766       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6767         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6768                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6769       // At least one input vector was used. Create a new shuffle vector.
6770       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6771     }
6772
6773     Mask.clear();
6774   }
6775
6776   // Concatenate the result back
6777   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6778 }
6779
6780 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6781 /// 4 elements, and match them with several different shuffle types.
6782 static SDValue
6783 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6784   SDValue V1 = SVOp->getOperand(0);
6785   SDValue V2 = SVOp->getOperand(1);
6786   SDLoc dl(SVOp);
6787   MVT VT = SVOp->getSimpleValueType(0);
6788
6789   assert(VT.is128BitVector() && "Unsupported vector size");
6790
6791   std::pair<int, int> Locs[4];
6792   int Mask1[] = { -1, -1, -1, -1 };
6793   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6794
6795   unsigned NumHi = 0;
6796   unsigned NumLo = 0;
6797   for (unsigned i = 0; i != 4; ++i) {
6798     int Idx = PermMask[i];
6799     if (Idx < 0) {
6800       Locs[i] = std::make_pair(-1, -1);
6801     } else {
6802       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6803       if (Idx < 4) {
6804         Locs[i] = std::make_pair(0, NumLo);
6805         Mask1[NumLo] = Idx;
6806         NumLo++;
6807       } else {
6808         Locs[i] = std::make_pair(1, NumHi);
6809         if (2+NumHi < 4)
6810           Mask1[2+NumHi] = Idx;
6811         NumHi++;
6812       }
6813     }
6814   }
6815
6816   if (NumLo <= 2 && NumHi <= 2) {
6817     // If no more than two elements come from either vector. This can be
6818     // implemented with two shuffles. First shuffle gather the elements.
6819     // The second shuffle, which takes the first shuffle as both of its
6820     // vector operands, put the elements into the right order.
6821     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6822
6823     int Mask2[] = { -1, -1, -1, -1 };
6824
6825     for (unsigned i = 0; i != 4; ++i)
6826       if (Locs[i].first != -1) {
6827         unsigned Idx = (i < 2) ? 0 : 4;
6828         Idx += Locs[i].first * 2 + Locs[i].second;
6829         Mask2[i] = Idx;
6830       }
6831
6832     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6833   }
6834
6835   if (NumLo == 3 || NumHi == 3) {
6836     // Otherwise, we must have three elements from one vector, call it X, and
6837     // one element from the other, call it Y.  First, use a shufps to build an
6838     // intermediate vector with the one element from Y and the element from X
6839     // that will be in the same half in the final destination (the indexes don't
6840     // matter). Then, use a shufps to build the final vector, taking the half
6841     // containing the element from Y from the intermediate, and the other half
6842     // from X.
6843     if (NumHi == 3) {
6844       // Normalize it so the 3 elements come from V1.
6845       CommuteVectorShuffleMask(PermMask, 4);
6846       std::swap(V1, V2);
6847     }
6848
6849     // Find the element from V2.
6850     unsigned HiIndex;
6851     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6852       int Val = PermMask[HiIndex];
6853       if (Val < 0)
6854         continue;
6855       if (Val >= 4)
6856         break;
6857     }
6858
6859     Mask1[0] = PermMask[HiIndex];
6860     Mask1[1] = -1;
6861     Mask1[2] = PermMask[HiIndex^1];
6862     Mask1[3] = -1;
6863     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6864
6865     if (HiIndex >= 2) {
6866       Mask1[0] = PermMask[0];
6867       Mask1[1] = PermMask[1];
6868       Mask1[2] = HiIndex & 1 ? 6 : 4;
6869       Mask1[3] = HiIndex & 1 ? 4 : 6;
6870       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6871     }
6872
6873     Mask1[0] = HiIndex & 1 ? 2 : 0;
6874     Mask1[1] = HiIndex & 1 ? 0 : 2;
6875     Mask1[2] = PermMask[2];
6876     Mask1[3] = PermMask[3];
6877     if (Mask1[2] >= 0)
6878       Mask1[2] += 4;
6879     if (Mask1[3] >= 0)
6880       Mask1[3] += 4;
6881     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6882   }
6883
6884   // Break it into (shuffle shuffle_hi, shuffle_lo).
6885   int LoMask[] = { -1, -1, -1, -1 };
6886   int HiMask[] = { -1, -1, -1, -1 };
6887
6888   int *MaskPtr = LoMask;
6889   unsigned MaskIdx = 0;
6890   unsigned LoIdx = 0;
6891   unsigned HiIdx = 2;
6892   for (unsigned i = 0; i != 4; ++i) {
6893     if (i == 2) {
6894       MaskPtr = HiMask;
6895       MaskIdx = 1;
6896       LoIdx = 0;
6897       HiIdx = 2;
6898     }
6899     int Idx = PermMask[i];
6900     if (Idx < 0) {
6901       Locs[i] = std::make_pair(-1, -1);
6902     } else if (Idx < 4) {
6903       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6904       MaskPtr[LoIdx] = Idx;
6905       LoIdx++;
6906     } else {
6907       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6908       MaskPtr[HiIdx] = Idx;
6909       HiIdx++;
6910     }
6911   }
6912
6913   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6914   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6915   int MaskOps[] = { -1, -1, -1, -1 };
6916   for (unsigned i = 0; i != 4; ++i)
6917     if (Locs[i].first != -1)
6918       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6919   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6920 }
6921
6922 static bool MayFoldVectorLoad(SDValue V) {
6923   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6924     V = V.getOperand(0);
6925
6926   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6927     V = V.getOperand(0);
6928   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6929       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6930     // BUILD_VECTOR (load), undef
6931     V = V.getOperand(0);
6932
6933   return MayFoldLoad(V);
6934 }
6935
6936 static
6937 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6938   MVT VT = Op.getSimpleValueType();
6939
6940   // Canonizalize to v2f64.
6941   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6942   return DAG.getNode(ISD::BITCAST, dl, VT,
6943                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6944                                           V1, DAG));
6945 }
6946
6947 static
6948 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6949                         bool HasSSE2) {
6950   SDValue V1 = Op.getOperand(0);
6951   SDValue V2 = Op.getOperand(1);
6952   MVT VT = Op.getSimpleValueType();
6953
6954   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6955
6956   if (HasSSE2 && VT == MVT::v2f64)
6957     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6958
6959   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6960   return DAG.getNode(ISD::BITCAST, dl, VT,
6961                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6962                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6963                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6964 }
6965
6966 static
6967 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6968   SDValue V1 = Op.getOperand(0);
6969   SDValue V2 = Op.getOperand(1);
6970   MVT VT = Op.getSimpleValueType();
6971
6972   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6973          "unsupported shuffle type");
6974
6975   if (V2.getOpcode() == ISD::UNDEF)
6976     V2 = V1;
6977
6978   // v4i32 or v4f32
6979   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6980 }
6981
6982 static
6983 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6984   SDValue V1 = Op.getOperand(0);
6985   SDValue V2 = Op.getOperand(1);
6986   MVT VT = Op.getSimpleValueType();
6987   unsigned NumElems = VT.getVectorNumElements();
6988
6989   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6990   // operand of these instructions is only memory, so check if there's a
6991   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6992   // same masks.
6993   bool CanFoldLoad = false;
6994
6995   // Trivial case, when V2 comes from a load.
6996   if (MayFoldVectorLoad(V2))
6997     CanFoldLoad = true;
6998
6999   // When V1 is a load, it can be folded later into a store in isel, example:
7000   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7001   //    turns into:
7002   //  (MOVLPSmr addr:$src1, VR128:$src2)
7003   // So, recognize this potential and also use MOVLPS or MOVLPD
7004   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7005     CanFoldLoad = true;
7006
7007   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7008   if (CanFoldLoad) {
7009     if (HasSSE2 && NumElems == 2)
7010       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7011
7012     if (NumElems == 4)
7013       // If we don't care about the second element, proceed to use movss.
7014       if (SVOp->getMaskElt(1) != -1)
7015         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7016   }
7017
7018   // movl and movlp will both match v2i64, but v2i64 is never matched by
7019   // movl earlier because we make it strict to avoid messing with the movlp load
7020   // folding logic (see the code above getMOVLP call). Match it here then,
7021   // this is horrible, but will stay like this until we move all shuffle
7022   // matching to x86 specific nodes. Note that for the 1st condition all
7023   // types are matched with movsd.
7024   if (HasSSE2) {
7025     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7026     // as to remove this logic from here, as much as possible
7027     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7028       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7029     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7030   }
7031
7032   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7033
7034   // Invert the operand order and use SHUFPS to match it.
7035   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7036                               getShuffleSHUFImmediate(SVOp), DAG);
7037 }
7038
7039 // Reduce a vector shuffle to zext.
7040 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7041                                     SelectionDAG &DAG) {
7042   // PMOVZX is only available from SSE41.
7043   if (!Subtarget->hasSSE41())
7044     return SDValue();
7045
7046   MVT VT = Op.getSimpleValueType();
7047
7048   // Only AVX2 support 256-bit vector integer extending.
7049   if (!Subtarget->hasInt256() && VT.is256BitVector())
7050     return SDValue();
7051
7052   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7053   SDLoc DL(Op);
7054   SDValue V1 = Op.getOperand(0);
7055   SDValue V2 = Op.getOperand(1);
7056   unsigned NumElems = VT.getVectorNumElements();
7057
7058   // Extending is an unary operation and the element type of the source vector
7059   // won't be equal to or larger than i64.
7060   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7061       VT.getVectorElementType() == MVT::i64)
7062     return SDValue();
7063
7064   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7065   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7066   while ((1U << Shift) < NumElems) {
7067     if (SVOp->getMaskElt(1U << Shift) == 1)
7068       break;
7069     Shift += 1;
7070     // The maximal ratio is 8, i.e. from i8 to i64.
7071     if (Shift > 3)
7072       return SDValue();
7073   }
7074
7075   // Check the shuffle mask.
7076   unsigned Mask = (1U << Shift) - 1;
7077   for (unsigned i = 0; i != NumElems; ++i) {
7078     int EltIdx = SVOp->getMaskElt(i);
7079     if ((i & Mask) != 0 && EltIdx != -1)
7080       return SDValue();
7081     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7082       return SDValue();
7083   }
7084
7085   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7086   MVT NeVT = MVT::getIntegerVT(NBits);
7087   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7088
7089   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7090     return SDValue();
7091
7092   // Simplify the operand as it's prepared to be fed into shuffle.
7093   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7094   if (V1.getOpcode() == ISD::BITCAST &&
7095       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7096       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7097       V1.getOperand(0).getOperand(0)
7098         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7099     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7100     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7101     ConstantSDNode *CIdx =
7102       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7103     // If it's foldable, i.e. normal load with single use, we will let code
7104     // selection to fold it. Otherwise, we will short the conversion sequence.
7105     if (CIdx && CIdx->getZExtValue() == 0 &&
7106         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7107       MVT FullVT = V.getSimpleValueType();
7108       MVT V1VT = V1.getSimpleValueType();
7109       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7110         // The "ext_vec_elt" node is wider than the result node.
7111         // In this case we should extract subvector from V.
7112         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7113         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7114         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7115                                         FullVT.getVectorNumElements()/Ratio);
7116         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7117                         DAG.getIntPtrConstant(0));
7118       }
7119       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7120     }
7121   }
7122
7123   return DAG.getNode(ISD::BITCAST, DL, VT,
7124                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7125 }
7126
7127 static SDValue
7128 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7129                        SelectionDAG &DAG) {
7130   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7131   MVT VT = Op.getSimpleValueType();
7132   SDLoc dl(Op);
7133   SDValue V1 = Op.getOperand(0);
7134   SDValue V2 = Op.getOperand(1);
7135
7136   if (isZeroShuffle(SVOp))
7137     return getZeroVector(VT, Subtarget, DAG, dl);
7138
7139   // Handle splat operations
7140   if (SVOp->isSplat()) {
7141     // Use vbroadcast whenever the splat comes from a foldable load
7142     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7143     if (Broadcast.getNode())
7144       return Broadcast;
7145   }
7146
7147   // Check integer expanding shuffles.
7148   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7149   if (NewOp.getNode())
7150     return NewOp;
7151
7152   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7153   // do it!
7154   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7155       VT == MVT::v16i16 || VT == MVT::v32i8) {
7156     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7157     if (NewOp.getNode())
7158       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7159   } else if ((VT == MVT::v4i32 ||
7160              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7161     // FIXME: Figure out a cleaner way to do this.
7162     // Try to make use of movq to zero out the top part.
7163     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7164       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7165       if (NewOp.getNode()) {
7166         MVT NewVT = NewOp.getSimpleValueType();
7167         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7168                                NewVT, true, false))
7169           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7170                               DAG, Subtarget, dl);
7171       }
7172     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7173       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7174       if (NewOp.getNode()) {
7175         MVT NewVT = NewOp.getSimpleValueType();
7176         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7177           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7178                               DAG, Subtarget, dl);
7179       }
7180     }
7181   }
7182   return SDValue();
7183 }
7184
7185 SDValue
7186 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7187   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7188   SDValue V1 = Op.getOperand(0);
7189   SDValue V2 = Op.getOperand(1);
7190   MVT VT = Op.getSimpleValueType();
7191   SDLoc dl(Op);
7192   unsigned NumElems = VT.getVectorNumElements();
7193   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7194   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7195   bool V1IsSplat = false;
7196   bool V2IsSplat = false;
7197   bool HasSSE2 = Subtarget->hasSSE2();
7198   bool HasFp256    = Subtarget->hasFp256();
7199   bool HasInt256   = Subtarget->hasInt256();
7200   MachineFunction &MF = DAG.getMachineFunction();
7201   bool OptForSize = MF.getFunction()->getAttributes().
7202     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7203
7204   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7205
7206   if (V1IsUndef && V2IsUndef)
7207     return DAG.getUNDEF(VT);
7208
7209   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7210
7211   // Vector shuffle lowering takes 3 steps:
7212   //
7213   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7214   //    narrowing and commutation of operands should be handled.
7215   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7216   //    shuffle nodes.
7217   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7218   //    so the shuffle can be broken into other shuffles and the legalizer can
7219   //    try the lowering again.
7220   //
7221   // The general idea is that no vector_shuffle operation should be left to
7222   // be matched during isel, all of them must be converted to a target specific
7223   // node here.
7224
7225   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7226   // narrowing and commutation of operands should be handled. The actual code
7227   // doesn't include all of those, work in progress...
7228   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7229   if (NewOp.getNode())
7230     return NewOp;
7231
7232   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7233
7234   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7235   // unpckh_undef). Only use pshufd if speed is more important than size.
7236   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7237     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7238   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7239     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7240
7241   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7242       V2IsUndef && MayFoldVectorLoad(V1))
7243     return getMOVDDup(Op, dl, V1, DAG);
7244
7245   if (isMOVHLPS_v_undef_Mask(M, VT))
7246     return getMOVHighToLow(Op, dl, DAG);
7247
7248   // Use to match splats
7249   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7250       (VT == MVT::v2f64 || VT == MVT::v2i64))
7251     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7252
7253   if (isPSHUFDMask(M, VT)) {
7254     // The actual implementation will match the mask in the if above and then
7255     // during isel it can match several different instructions, not only pshufd
7256     // as its name says, sad but true, emulate the behavior for now...
7257     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7258       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7259
7260     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7261
7262     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7263       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7264
7265     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7266       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7267                                   DAG);
7268
7269     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7270                                 TargetMask, DAG);
7271   }
7272
7273   if (isPALIGNRMask(M, VT, Subtarget))
7274     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7275                                 getShufflePALIGNRImmediate(SVOp),
7276                                 DAG);
7277
7278   // Check if this can be converted into a logical shift.
7279   bool isLeft = false;
7280   unsigned ShAmt = 0;
7281   SDValue ShVal;
7282   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7283   if (isShift && ShVal.hasOneUse()) {
7284     // If the shifted value has multiple uses, it may be cheaper to use
7285     // v_set0 + movlhps or movhlps, etc.
7286     MVT EltVT = VT.getVectorElementType();
7287     ShAmt *= EltVT.getSizeInBits();
7288     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7289   }
7290
7291   if (isMOVLMask(M, VT)) {
7292     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7293       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7294     if (!isMOVLPMask(M, VT)) {
7295       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7296         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7297
7298       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7299         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7300     }
7301   }
7302
7303   // FIXME: fold these into legal mask.
7304   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7305     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7306
7307   if (isMOVHLPSMask(M, VT))
7308     return getMOVHighToLow(Op, dl, DAG);
7309
7310   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7311     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7312
7313   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7314     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7315
7316   if (isMOVLPMask(M, VT))
7317     return getMOVLP(Op, dl, DAG, HasSSE2);
7318
7319   if (ShouldXformToMOVHLPS(M, VT) ||
7320       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7321     return CommuteVectorShuffle(SVOp, DAG);
7322
7323   if (isShift) {
7324     // No better options. Use a vshldq / vsrldq.
7325     MVT EltVT = VT.getVectorElementType();
7326     ShAmt *= EltVT.getSizeInBits();
7327     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7328   }
7329
7330   bool Commuted = false;
7331   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7332   // 1,1,1,1 -> v8i16 though.
7333   V1IsSplat = isSplatVector(V1.getNode());
7334   V2IsSplat = isSplatVector(V2.getNode());
7335
7336   // Canonicalize the splat or undef, if present, to be on the RHS.
7337   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7338     CommuteVectorShuffleMask(M, NumElems);
7339     std::swap(V1, V2);
7340     std::swap(V1IsSplat, V2IsSplat);
7341     Commuted = true;
7342   }
7343
7344   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7345     // Shuffling low element of v1 into undef, just return v1.
7346     if (V2IsUndef)
7347       return V1;
7348     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7349     // the instruction selector will not match, so get a canonical MOVL with
7350     // swapped operands to undo the commute.
7351     return getMOVL(DAG, dl, VT, V2, V1);
7352   }
7353
7354   if (isUNPCKLMask(M, VT, HasInt256))
7355     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7356
7357   if (isUNPCKHMask(M, VT, HasInt256))
7358     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7359
7360   if (V2IsSplat) {
7361     // Normalize mask so all entries that point to V2 points to its first
7362     // element then try to match unpck{h|l} again. If match, return a
7363     // new vector_shuffle with the corrected mask.p
7364     SmallVector<int, 8> NewMask(M.begin(), M.end());
7365     NormalizeMask(NewMask, NumElems);
7366     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7367       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7368     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7369       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7370   }
7371
7372   if (Commuted) {
7373     // Commute is back and try unpck* again.
7374     // FIXME: this seems wrong.
7375     CommuteVectorShuffleMask(M, NumElems);
7376     std::swap(V1, V2);
7377     std::swap(V1IsSplat, V2IsSplat);
7378     Commuted = false;
7379
7380     if (isUNPCKLMask(M, VT, HasInt256))
7381       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7382
7383     if (isUNPCKHMask(M, VT, HasInt256))
7384       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7385   }
7386
7387   // Normalize the node to match x86 shuffle ops if needed
7388   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7389     return CommuteVectorShuffle(SVOp, DAG);
7390
7391   // The checks below are all present in isShuffleMaskLegal, but they are
7392   // inlined here right now to enable us to directly emit target specific
7393   // nodes, and remove one by one until they don't return Op anymore.
7394
7395   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7396       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7397     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7398       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7399   }
7400
7401   if (isPSHUFHWMask(M, VT, HasInt256))
7402     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7403                                 getShufflePSHUFHWImmediate(SVOp),
7404                                 DAG);
7405
7406   if (isPSHUFLWMask(M, VT, HasInt256))
7407     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7408                                 getShufflePSHUFLWImmediate(SVOp),
7409                                 DAG);
7410
7411   if (isSHUFPMask(M, VT, HasFp256))
7412     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7413                                 getShuffleSHUFImmediate(SVOp), DAG);
7414
7415   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7416     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7417   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7418     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7419
7420   //===--------------------------------------------------------------------===//
7421   // Generate target specific nodes for 128 or 256-bit shuffles only
7422   // supported in the AVX instruction set.
7423   //
7424
7425   // Handle VMOVDDUPY permutations
7426   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7427     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7428
7429   // Handle VPERMILPS/D* permutations
7430   if (isVPERMILPMask(M, VT, HasFp256)) {
7431     if (HasInt256 && VT == MVT::v8i32)
7432       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7433                                   getShuffleSHUFImmediate(SVOp), DAG);
7434     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7435                                 getShuffleSHUFImmediate(SVOp), DAG);
7436   }
7437
7438   // Handle VPERM2F128/VPERM2I128 permutations
7439   if (isVPERM2X128Mask(M, VT, HasFp256))
7440     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7441                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7442
7443   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7444   if (BlendOp.getNode())
7445     return BlendOp;
7446
7447   unsigned Imm8;
7448   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7449     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7450
7451   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7452       VT.is512BitVector()) {
7453     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7454     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7455     SmallVector<SDValue, 16> permclMask;
7456     for (unsigned i = 0; i != NumElems; ++i) {
7457       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7458     }
7459
7460     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT,
7461                                 &permclMask[0], NumElems);
7462     if (V2IsUndef)
7463       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7464       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7465                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7466     return DAG.getNode(X86ISD::VPERMV3, dl, VT,
7467                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1, V2);
7468   }
7469
7470   //===--------------------------------------------------------------------===//
7471   // Since no target specific shuffle was selected for this generic one,
7472   // lower it into other known shuffles. FIXME: this isn't true yet, but
7473   // this is the plan.
7474   //
7475
7476   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7477   if (VT == MVT::v8i16) {
7478     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7479     if (NewOp.getNode())
7480       return NewOp;
7481   }
7482
7483   if (VT == MVT::v16i8) {
7484     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7485     if (NewOp.getNode())
7486       return NewOp;
7487   }
7488
7489   if (VT == MVT::v32i8) {
7490     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7491     if (NewOp.getNode())
7492       return NewOp;
7493   }
7494
7495   // Handle all 128-bit wide vectors with 4 elements, and match them with
7496   // several different shuffle types.
7497   if (NumElems == 4 && VT.is128BitVector())
7498     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7499
7500   // Handle general 256-bit shuffles
7501   if (VT.is256BitVector())
7502     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7503
7504   return SDValue();
7505 }
7506
7507 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7508   MVT VT = Op.getSimpleValueType();
7509   SDLoc dl(Op);
7510
7511   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7512     return SDValue();
7513
7514   if (VT.getSizeInBits() == 8) {
7515     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7516                                   Op.getOperand(0), Op.getOperand(1));
7517     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7518                                   DAG.getValueType(VT));
7519     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7520   }
7521
7522   if (VT.getSizeInBits() == 16) {
7523     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7524     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7525     if (Idx == 0)
7526       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7527                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7528                                      DAG.getNode(ISD::BITCAST, dl,
7529                                                  MVT::v4i32,
7530                                                  Op.getOperand(0)),
7531                                      Op.getOperand(1)));
7532     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7533                                   Op.getOperand(0), Op.getOperand(1));
7534     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7535                                   DAG.getValueType(VT));
7536     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7537   }
7538
7539   if (VT == MVT::f32) {
7540     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7541     // the result back to FR32 register. It's only worth matching if the
7542     // result has a single use which is a store or a bitcast to i32.  And in
7543     // the case of a store, it's not worth it if the index is a constant 0,
7544     // because a MOVSSmr can be used instead, which is smaller and faster.
7545     if (!Op.hasOneUse())
7546       return SDValue();
7547     SDNode *User = *Op.getNode()->use_begin();
7548     if ((User->getOpcode() != ISD::STORE ||
7549          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7550           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7551         (User->getOpcode() != ISD::BITCAST ||
7552          User->getValueType(0) != MVT::i32))
7553       return SDValue();
7554     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7555                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7556                                               Op.getOperand(0)),
7557                                               Op.getOperand(1));
7558     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7559   }
7560
7561   if (VT == MVT::i32 || VT == MVT::i64) {
7562     // ExtractPS/pextrq works with constant index.
7563     if (isa<ConstantSDNode>(Op.getOperand(1)))
7564       return Op;
7565   }
7566   return SDValue();
7567 }
7568
7569 SDValue
7570 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7571                                            SelectionDAG &DAG) const {
7572   SDLoc dl(Op);
7573   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7574     return SDValue();
7575
7576   SDValue Vec = Op.getOperand(0);
7577   MVT VecVT = Vec.getSimpleValueType();
7578
7579   // If this is a 256-bit vector result, first extract the 128-bit vector and
7580   // then extract the element from the 128-bit vector.
7581   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7582     SDValue Idx = Op.getOperand(1);
7583     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7584
7585     // Get the 128-bit vector.
7586     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7587     MVT EltVT = VecVT.getVectorElementType();
7588
7589     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7590
7591     //if (IdxVal >= NumElems/2)
7592     //  IdxVal -= NumElems/2;
7593     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7594     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7595                        DAG.getConstant(IdxVal, MVT::i32));
7596   }
7597
7598   assert(VecVT.is128BitVector() && "Unexpected vector length");
7599
7600   if (Subtarget->hasSSE41()) {
7601     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7602     if (Res.getNode())
7603       return Res;
7604   }
7605
7606   MVT VT = Op.getSimpleValueType();
7607   // TODO: handle v16i8.
7608   if (VT.getSizeInBits() == 16) {
7609     SDValue Vec = Op.getOperand(0);
7610     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7611     if (Idx == 0)
7612       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7613                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7614                                      DAG.getNode(ISD::BITCAST, dl,
7615                                                  MVT::v4i32, Vec),
7616                                      Op.getOperand(1)));
7617     // Transform it so it match pextrw which produces a 32-bit result.
7618     MVT EltVT = MVT::i32;
7619     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7620                                   Op.getOperand(0), Op.getOperand(1));
7621     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7622                                   DAG.getValueType(VT));
7623     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7624   }
7625
7626   if (VT.getSizeInBits() == 32) {
7627     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7628     if (Idx == 0)
7629       return Op;
7630
7631     // SHUFPS the element to the lowest double word, then movss.
7632     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7633     MVT VVT = Op.getOperand(0).getSimpleValueType();
7634     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7635                                        DAG.getUNDEF(VVT), Mask);
7636     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7637                        DAG.getIntPtrConstant(0));
7638   }
7639
7640   if (VT.getSizeInBits() == 64) {
7641     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7642     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7643     //        to match extract_elt for f64.
7644     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7645     if (Idx == 0)
7646       return Op;
7647
7648     // UNPCKHPD the element to the lowest double word, then movsd.
7649     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7650     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7651     int Mask[2] = { 1, -1 };
7652     MVT VVT = Op.getOperand(0).getSimpleValueType();
7653     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7654                                        DAG.getUNDEF(VVT), Mask);
7655     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7656                        DAG.getIntPtrConstant(0));
7657   }
7658
7659   return SDValue();
7660 }
7661
7662 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7663   MVT VT = Op.getSimpleValueType();
7664   MVT EltVT = VT.getVectorElementType();
7665   SDLoc dl(Op);
7666
7667   SDValue N0 = Op.getOperand(0);
7668   SDValue N1 = Op.getOperand(1);
7669   SDValue N2 = Op.getOperand(2);
7670
7671   if (!VT.is128BitVector())
7672     return SDValue();
7673
7674   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7675       isa<ConstantSDNode>(N2)) {
7676     unsigned Opc;
7677     if (VT == MVT::v8i16)
7678       Opc = X86ISD::PINSRW;
7679     else if (VT == MVT::v16i8)
7680       Opc = X86ISD::PINSRB;
7681     else
7682       Opc = X86ISD::PINSRB;
7683
7684     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7685     // argument.
7686     if (N1.getValueType() != MVT::i32)
7687       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7688     if (N2.getValueType() != MVT::i32)
7689       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7690     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7691   }
7692
7693   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7694     // Bits [7:6] of the constant are the source select.  This will always be
7695     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7696     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7697     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7698     // Bits [5:4] of the constant are the destination select.  This is the
7699     //  value of the incoming immediate.
7700     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7701     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7702     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7703     // Create this as a scalar to vector..
7704     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7705     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7706   }
7707
7708   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7709     // PINSR* works with constant index.
7710     return Op;
7711   }
7712   return SDValue();
7713 }
7714
7715 SDValue
7716 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7717   MVT VT = Op.getSimpleValueType();
7718   MVT EltVT = VT.getVectorElementType();
7719
7720   SDLoc dl(Op);
7721   SDValue N0 = Op.getOperand(0);
7722   SDValue N1 = Op.getOperand(1);
7723   SDValue N2 = Op.getOperand(2);
7724
7725   // If this is a 256-bit vector result, first extract the 128-bit vector,
7726   // insert the element into the extracted half and then place it back.
7727   if (VT.is256BitVector() || VT.is512BitVector()) {
7728     if (!isa<ConstantSDNode>(N2))
7729       return SDValue();
7730
7731     // Get the desired 128-bit vector half.
7732     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7733     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7734
7735     // Insert the element into the desired half.
7736     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7737     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7738
7739     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7740                     DAG.getConstant(IdxIn128, MVT::i32));
7741
7742     // Insert the changed part back to the 256-bit vector
7743     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7744   }
7745
7746   if (Subtarget->hasSSE41())
7747     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7748
7749   if (EltVT == MVT::i8)
7750     return SDValue();
7751
7752   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7753     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7754     // as its second argument.
7755     if (N1.getValueType() != MVT::i32)
7756       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7757     if (N2.getValueType() != MVT::i32)
7758       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7759     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7760   }
7761   return SDValue();
7762 }
7763
7764 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7765   SDLoc dl(Op);
7766   MVT OpVT = Op.getSimpleValueType();
7767
7768   // If this is a 256-bit vector result, first insert into a 128-bit
7769   // vector and then insert into the 256-bit vector.
7770   if (!OpVT.is128BitVector()) {
7771     // Insert into a 128-bit vector.
7772     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7773     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
7774                                  OpVT.getVectorNumElements() / SizeFactor);
7775
7776     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7777
7778     // Insert the 128-bit vector.
7779     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7780   }
7781
7782   if (OpVT == MVT::v1i64 &&
7783       Op.getOperand(0).getValueType() == MVT::i64)
7784     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7785
7786   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7787   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7788   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7789                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7790 }
7791
7792 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7793 // a simple subregister reference or explicit instructions to grab
7794 // upper bits of a vector.
7795 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7796                                       SelectionDAG &DAG) {
7797   SDLoc dl(Op);
7798   SDValue In =  Op.getOperand(0);
7799   SDValue Idx = Op.getOperand(1);
7800   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7801   MVT ResVT   = Op.getSimpleValueType();
7802   MVT InVT    = In.getSimpleValueType();
7803
7804   if (Subtarget->hasFp256()) {
7805     if (ResVT.is128BitVector() &&
7806         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7807         isa<ConstantSDNode>(Idx)) {
7808       return Extract128BitVector(In, IdxVal, DAG, dl);
7809     }
7810     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7811         isa<ConstantSDNode>(Idx)) {
7812       return Extract256BitVector(In, IdxVal, DAG, dl);
7813     }
7814   }
7815   return SDValue();
7816 }
7817
7818 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7819 // simple superregister reference or explicit instructions to insert
7820 // the upper bits of a vector.
7821 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7822                                      SelectionDAG &DAG) {
7823   if (Subtarget->hasFp256()) {
7824     SDLoc dl(Op.getNode());
7825     SDValue Vec = Op.getNode()->getOperand(0);
7826     SDValue SubVec = Op.getNode()->getOperand(1);
7827     SDValue Idx = Op.getNode()->getOperand(2);
7828
7829     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
7830          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
7831         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
7832         isa<ConstantSDNode>(Idx)) {
7833       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7834       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7835     }
7836
7837     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
7838         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
7839         isa<ConstantSDNode>(Idx)) {
7840       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7841       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7842     }
7843   }
7844   return SDValue();
7845 }
7846
7847 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7848 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7849 // one of the above mentioned nodes. It has to be wrapped because otherwise
7850 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7851 // be used to form addressing mode. These wrapped nodes will be selected
7852 // into MOV32ri.
7853 SDValue
7854 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7855   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7856
7857   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7858   // global base reg.
7859   unsigned char OpFlag = 0;
7860   unsigned WrapperKind = X86ISD::Wrapper;
7861   CodeModel::Model M = getTargetMachine().getCodeModel();
7862
7863   if (Subtarget->isPICStyleRIPRel() &&
7864       (M == CodeModel::Small || M == CodeModel::Kernel))
7865     WrapperKind = X86ISD::WrapperRIP;
7866   else if (Subtarget->isPICStyleGOT())
7867     OpFlag = X86II::MO_GOTOFF;
7868   else if (Subtarget->isPICStyleStubPIC())
7869     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7870
7871   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7872                                              CP->getAlignment(),
7873                                              CP->getOffset(), OpFlag);
7874   SDLoc DL(CP);
7875   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7876   // With PIC, the address is actually $g + Offset.
7877   if (OpFlag) {
7878     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7879                          DAG.getNode(X86ISD::GlobalBaseReg,
7880                                      SDLoc(), getPointerTy()),
7881                          Result);
7882   }
7883
7884   return Result;
7885 }
7886
7887 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7888   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7889
7890   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7891   // global base reg.
7892   unsigned char OpFlag = 0;
7893   unsigned WrapperKind = X86ISD::Wrapper;
7894   CodeModel::Model M = getTargetMachine().getCodeModel();
7895
7896   if (Subtarget->isPICStyleRIPRel() &&
7897       (M == CodeModel::Small || M == CodeModel::Kernel))
7898     WrapperKind = X86ISD::WrapperRIP;
7899   else if (Subtarget->isPICStyleGOT())
7900     OpFlag = X86II::MO_GOTOFF;
7901   else if (Subtarget->isPICStyleStubPIC())
7902     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7903
7904   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7905                                           OpFlag);
7906   SDLoc DL(JT);
7907   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7908
7909   // With PIC, the address is actually $g + Offset.
7910   if (OpFlag)
7911     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7912                          DAG.getNode(X86ISD::GlobalBaseReg,
7913                                      SDLoc(), getPointerTy()),
7914                          Result);
7915
7916   return Result;
7917 }
7918
7919 SDValue
7920 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7921   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7922
7923   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7924   // global base reg.
7925   unsigned char OpFlag = 0;
7926   unsigned WrapperKind = X86ISD::Wrapper;
7927   CodeModel::Model M = getTargetMachine().getCodeModel();
7928
7929   if (Subtarget->isPICStyleRIPRel() &&
7930       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7931     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7932       OpFlag = X86II::MO_GOTPCREL;
7933     WrapperKind = X86ISD::WrapperRIP;
7934   } else if (Subtarget->isPICStyleGOT()) {
7935     OpFlag = X86II::MO_GOT;
7936   } else if (Subtarget->isPICStyleStubPIC()) {
7937     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7938   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7939     OpFlag = X86II::MO_DARWIN_NONLAZY;
7940   }
7941
7942   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7943
7944   SDLoc DL(Op);
7945   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7946
7947   // With PIC, the address is actually $g + Offset.
7948   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7949       !Subtarget->is64Bit()) {
7950     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7951                          DAG.getNode(X86ISD::GlobalBaseReg,
7952                                      SDLoc(), getPointerTy()),
7953                          Result);
7954   }
7955
7956   // For symbols that require a load from a stub to get the address, emit the
7957   // load.
7958   if (isGlobalStubReference(OpFlag))
7959     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7960                          MachinePointerInfo::getGOT(), false, false, false, 0);
7961
7962   return Result;
7963 }
7964
7965 SDValue
7966 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7967   // Create the TargetBlockAddressAddress node.
7968   unsigned char OpFlags =
7969     Subtarget->ClassifyBlockAddressReference();
7970   CodeModel::Model M = getTargetMachine().getCodeModel();
7971   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7972   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7973   SDLoc dl(Op);
7974   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7975                                              OpFlags);
7976
7977   if (Subtarget->isPICStyleRIPRel() &&
7978       (M == CodeModel::Small || M == CodeModel::Kernel))
7979     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7980   else
7981     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7982
7983   // With PIC, the address is actually $g + Offset.
7984   if (isGlobalRelativeToPICBase(OpFlags)) {
7985     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7986                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7987                          Result);
7988   }
7989
7990   return Result;
7991 }
7992
7993 SDValue
7994 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7995                                       int64_t Offset, SelectionDAG &DAG) const {
7996   // Create the TargetGlobalAddress node, folding in the constant
7997   // offset if it is legal.
7998   unsigned char OpFlags =
7999     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8000   CodeModel::Model M = getTargetMachine().getCodeModel();
8001   SDValue Result;
8002   if (OpFlags == X86II::MO_NO_FLAG &&
8003       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8004     // A direct static reference to a global.
8005     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8006     Offset = 0;
8007   } else {
8008     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8009   }
8010
8011   if (Subtarget->isPICStyleRIPRel() &&
8012       (M == CodeModel::Small || M == CodeModel::Kernel))
8013     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8014   else
8015     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8016
8017   // With PIC, the address is actually $g + Offset.
8018   if (isGlobalRelativeToPICBase(OpFlags)) {
8019     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8020                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8021                          Result);
8022   }
8023
8024   // For globals that require a load from a stub to get the address, emit the
8025   // load.
8026   if (isGlobalStubReference(OpFlags))
8027     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8028                          MachinePointerInfo::getGOT(), false, false, false, 0);
8029
8030   // If there was a non-zero offset that we didn't fold, create an explicit
8031   // addition for it.
8032   if (Offset != 0)
8033     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8034                          DAG.getConstant(Offset, getPointerTy()));
8035
8036   return Result;
8037 }
8038
8039 SDValue
8040 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8041   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8042   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8043   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8044 }
8045
8046 static SDValue
8047 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8048            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8049            unsigned char OperandFlags, bool LocalDynamic = false) {
8050   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8051   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8052   SDLoc dl(GA);
8053   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8054                                            GA->getValueType(0),
8055                                            GA->getOffset(),
8056                                            OperandFlags);
8057
8058   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8059                                            : X86ISD::TLSADDR;
8060
8061   if (InFlag) {
8062     SDValue Ops[] = { Chain,  TGA, *InFlag };
8063     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8064   } else {
8065     SDValue Ops[]  = { Chain, TGA };
8066     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8067   }
8068
8069   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8070   MFI->setAdjustsStack(true);
8071
8072   SDValue Flag = Chain.getValue(1);
8073   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8074 }
8075
8076 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8077 static SDValue
8078 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8079                                 const EVT PtrVT) {
8080   SDValue InFlag;
8081   SDLoc dl(GA);  // ? function entry point might be better
8082   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8083                                    DAG.getNode(X86ISD::GlobalBaseReg,
8084                                                SDLoc(), PtrVT), InFlag);
8085   InFlag = Chain.getValue(1);
8086
8087   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8088 }
8089
8090 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8091 static SDValue
8092 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8093                                 const EVT PtrVT) {
8094   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8095                     X86::RAX, X86II::MO_TLSGD);
8096 }
8097
8098 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8099                                            SelectionDAG &DAG,
8100                                            const EVT PtrVT,
8101                                            bool is64Bit) {
8102   SDLoc dl(GA);
8103
8104   // Get the start address of the TLS block for this module.
8105   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8106       .getInfo<X86MachineFunctionInfo>();
8107   MFI->incNumLocalDynamicTLSAccesses();
8108
8109   SDValue Base;
8110   if (is64Bit) {
8111     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8112                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8113   } else {
8114     SDValue InFlag;
8115     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8116         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8117     InFlag = Chain.getValue(1);
8118     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8119                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8120   }
8121
8122   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8123   // of Base.
8124
8125   // Build x@dtpoff.
8126   unsigned char OperandFlags = X86II::MO_DTPOFF;
8127   unsigned WrapperKind = X86ISD::Wrapper;
8128   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8129                                            GA->getValueType(0),
8130                                            GA->getOffset(), OperandFlags);
8131   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8132
8133   // Add x@dtpoff with the base.
8134   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8135 }
8136
8137 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8138 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8139                                    const EVT PtrVT, TLSModel::Model model,
8140                                    bool is64Bit, bool isPIC) {
8141   SDLoc dl(GA);
8142
8143   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8144   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8145                                                          is64Bit ? 257 : 256));
8146
8147   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
8148                                       DAG.getIntPtrConstant(0),
8149                                       MachinePointerInfo(Ptr),
8150                                       false, false, false, 0);
8151
8152   unsigned char OperandFlags = 0;
8153   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8154   // initialexec.
8155   unsigned WrapperKind = X86ISD::Wrapper;
8156   if (model == TLSModel::LocalExec) {
8157     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8158   } else if (model == TLSModel::InitialExec) {
8159     if (is64Bit) {
8160       OperandFlags = X86II::MO_GOTTPOFF;
8161       WrapperKind = X86ISD::WrapperRIP;
8162     } else {
8163       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8164     }
8165   } else {
8166     llvm_unreachable("Unexpected model");
8167   }
8168
8169   // emit "addl x@ntpoff,%eax" (local exec)
8170   // or "addl x@indntpoff,%eax" (initial exec)
8171   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8172   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8173                                            GA->getValueType(0),
8174                                            GA->getOffset(), OperandFlags);
8175   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8176
8177   if (model == TLSModel::InitialExec) {
8178     if (isPIC && !is64Bit) {
8179       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8180                           DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8181                            Offset);
8182     }
8183
8184     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8185                          MachinePointerInfo::getGOT(), false, false, false,
8186                          0);
8187   }
8188
8189   // The address of the thread local variable is the add of the thread
8190   // pointer with the offset of the variable.
8191   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8192 }
8193
8194 SDValue
8195 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8196
8197   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8198   const GlobalValue *GV = GA->getGlobal();
8199
8200   if (Subtarget->isTargetELF()) {
8201     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8202
8203     switch (model) {
8204       case TLSModel::GeneralDynamic:
8205         if (Subtarget->is64Bit())
8206           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8207         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8208       case TLSModel::LocalDynamic:
8209         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8210                                            Subtarget->is64Bit());
8211       case TLSModel::InitialExec:
8212       case TLSModel::LocalExec:
8213         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8214                                    Subtarget->is64Bit(),
8215                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8216     }
8217     llvm_unreachable("Unknown TLS model.");
8218   }
8219
8220   if (Subtarget->isTargetDarwin()) {
8221     // Darwin only has one model of TLS.  Lower to that.
8222     unsigned char OpFlag = 0;
8223     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8224                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8225
8226     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8227     // global base reg.
8228     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8229                   !Subtarget->is64Bit();
8230     if (PIC32)
8231       OpFlag = X86II::MO_TLVP_PIC_BASE;
8232     else
8233       OpFlag = X86II::MO_TLVP;
8234     SDLoc DL(Op);
8235     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8236                                                 GA->getValueType(0),
8237                                                 GA->getOffset(), OpFlag);
8238     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8239
8240     // With PIC32, the address is actually $g + Offset.
8241     if (PIC32)
8242       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8243                            DAG.getNode(X86ISD::GlobalBaseReg,
8244                                        SDLoc(), getPointerTy()),
8245                            Offset);
8246
8247     // Lowering the machine isd will make sure everything is in the right
8248     // location.
8249     SDValue Chain = DAG.getEntryNode();
8250     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8251     SDValue Args[] = { Chain, Offset };
8252     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8253
8254     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8255     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8256     MFI->setAdjustsStack(true);
8257
8258     // And our return value (tls address) is in the standard call return value
8259     // location.
8260     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8261     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8262                               Chain.getValue(1));
8263   }
8264
8265   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8266     // Just use the implicit TLS architecture
8267     // Need to generate someting similar to:
8268     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8269     //                                  ; from TEB
8270     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8271     //   mov     rcx, qword [rdx+rcx*8]
8272     //   mov     eax, .tls$:tlsvar
8273     //   [rax+rcx] contains the address
8274     // Windows 64bit: gs:0x58
8275     // Windows 32bit: fs:__tls_array
8276
8277     // If GV is an alias then use the aliasee for determining
8278     // thread-localness.
8279     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8280       GV = GA->resolveAliasedGlobal(false);
8281     SDLoc dl(GA);
8282     SDValue Chain = DAG.getEntryNode();
8283
8284     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8285     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8286     // use its literal value of 0x2C.
8287     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8288                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8289                                                              256)
8290                                         : Type::getInt32PtrTy(*DAG.getContext(),
8291                                                               257));
8292
8293     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8294       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8295         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8296
8297     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8298                                         MachinePointerInfo(Ptr),
8299                                         false, false, false, 0);
8300
8301     // Load the _tls_index variable
8302     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8303     if (Subtarget->is64Bit())
8304       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8305                            IDX, MachinePointerInfo(), MVT::i32,
8306                            false, false, 0);
8307     else
8308       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8309                         false, false, false, 0);
8310
8311     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8312                                     getPointerTy());
8313     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8314
8315     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8316     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8317                       false, false, false, 0);
8318
8319     // Get the offset of start of .tls section
8320     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8321                                              GA->getValueType(0),
8322                                              GA->getOffset(), X86II::MO_SECREL);
8323     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8324
8325     // The address of the thread local variable is the add of the thread
8326     // pointer with the offset of the variable.
8327     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8328   }
8329
8330   llvm_unreachable("TLS not implemented for this target.");
8331 }
8332
8333 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8334 /// and take a 2 x i32 value to shift plus a shift amount.
8335 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8336   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8337   EVT VT = Op.getValueType();
8338   unsigned VTBits = VT.getSizeInBits();
8339   SDLoc dl(Op);
8340   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8341   SDValue ShOpLo = Op.getOperand(0);
8342   SDValue ShOpHi = Op.getOperand(1);
8343   SDValue ShAmt  = Op.getOperand(2);
8344   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8345                                      DAG.getConstant(VTBits - 1, MVT::i8))
8346                        : DAG.getConstant(0, VT);
8347
8348   SDValue Tmp2, Tmp3;
8349   if (Op.getOpcode() == ISD::SHL_PARTS) {
8350     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8351     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8352   } else {
8353     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8354     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8355   }
8356
8357   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8358                                 DAG.getConstant(VTBits, MVT::i8));
8359   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8360                              AndNode, DAG.getConstant(0, MVT::i8));
8361
8362   SDValue Hi, Lo;
8363   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8364   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8365   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8366
8367   if (Op.getOpcode() == ISD::SHL_PARTS) {
8368     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8369     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8370   } else {
8371     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8372     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8373   }
8374
8375   SDValue Ops[2] = { Lo, Hi };
8376   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8377 }
8378
8379 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8380                                            SelectionDAG &DAG) const {
8381   EVT SrcVT = Op.getOperand(0).getValueType();
8382
8383   if (SrcVT.isVector())
8384     return SDValue();
8385
8386   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8387          "Unknown SINT_TO_FP to lower!");
8388
8389   // These are really Legal; return the operand so the caller accepts it as
8390   // Legal.
8391   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8392     return Op;
8393   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8394       Subtarget->is64Bit()) {
8395     return Op;
8396   }
8397
8398   SDLoc dl(Op);
8399   unsigned Size = SrcVT.getSizeInBits()/8;
8400   MachineFunction &MF = DAG.getMachineFunction();
8401   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8402   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8403   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8404                                StackSlot,
8405                                MachinePointerInfo::getFixedStack(SSFI),
8406                                false, false, 0);
8407   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8408 }
8409
8410 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8411                                      SDValue StackSlot,
8412                                      SelectionDAG &DAG) const {
8413   // Build the FILD
8414   SDLoc DL(Op);
8415   SDVTList Tys;
8416   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8417   if (useSSE)
8418     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8419   else
8420     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8421
8422   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8423
8424   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8425   MachineMemOperand *MMO;
8426   if (FI) {
8427     int SSFI = FI->getIndex();
8428     MMO =
8429       DAG.getMachineFunction()
8430       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8431                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8432   } else {
8433     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8434     StackSlot = StackSlot.getOperand(1);
8435   }
8436   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8437   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8438                                            X86ISD::FILD, DL,
8439                                            Tys, Ops, array_lengthof(Ops),
8440                                            SrcVT, MMO);
8441
8442   if (useSSE) {
8443     Chain = Result.getValue(1);
8444     SDValue InFlag = Result.getValue(2);
8445
8446     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8447     // shouldn't be necessary except that RFP cannot be live across
8448     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8449     MachineFunction &MF = DAG.getMachineFunction();
8450     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8451     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8452     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8453     Tys = DAG.getVTList(MVT::Other);
8454     SDValue Ops[] = {
8455       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8456     };
8457     MachineMemOperand *MMO =
8458       DAG.getMachineFunction()
8459       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8460                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8461
8462     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8463                                     Ops, array_lengthof(Ops),
8464                                     Op.getValueType(), MMO);
8465     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8466                          MachinePointerInfo::getFixedStack(SSFI),
8467                          false, false, false, 0);
8468   }
8469
8470   return Result;
8471 }
8472
8473 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8474 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8475                                                SelectionDAG &DAG) const {
8476   // This algorithm is not obvious. Here it is what we're trying to output:
8477   /*
8478      movq       %rax,  %xmm0
8479      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8480      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8481      #ifdef __SSE3__
8482        haddpd   %xmm0, %xmm0
8483      #else
8484        pshufd   $0x4e, %xmm0, %xmm1
8485        addpd    %xmm1, %xmm0
8486      #endif
8487   */
8488
8489   SDLoc dl(Op);
8490   LLVMContext *Context = DAG.getContext();
8491
8492   // Build some magic constants.
8493   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8494   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8495   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8496
8497   SmallVector<Constant*,2> CV1;
8498   CV1.push_back(
8499     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8500                                       APInt(64, 0x4330000000000000ULL))));
8501   CV1.push_back(
8502     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8503                                       APInt(64, 0x4530000000000000ULL))));
8504   Constant *C1 = ConstantVector::get(CV1);
8505   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8506
8507   // Load the 64-bit value into an XMM register.
8508   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8509                             Op.getOperand(0));
8510   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8511                               MachinePointerInfo::getConstantPool(),
8512                               false, false, false, 16);
8513   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8514                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8515                               CLod0);
8516
8517   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8518                               MachinePointerInfo::getConstantPool(),
8519                               false, false, false, 16);
8520   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8521   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8522   SDValue Result;
8523
8524   if (Subtarget->hasSSE3()) {
8525     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8526     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8527   } else {
8528     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8529     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8530                                            S2F, 0x4E, DAG);
8531     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8532                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8533                          Sub);
8534   }
8535
8536   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8537                      DAG.getIntPtrConstant(0));
8538 }
8539
8540 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8541 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8542                                                SelectionDAG &DAG) const {
8543   SDLoc dl(Op);
8544   // FP constant to bias correct the final result.
8545   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8546                                    MVT::f64);
8547
8548   // Load the 32-bit value into an XMM register.
8549   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8550                              Op.getOperand(0));
8551
8552   // Zero out the upper parts of the register.
8553   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8554
8555   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8556                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8557                      DAG.getIntPtrConstant(0));
8558
8559   // Or the load with the bias.
8560   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8561                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8562                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8563                                                    MVT::v2f64, Load)),
8564                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8565                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8566                                                    MVT::v2f64, Bias)));
8567   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8568                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8569                    DAG.getIntPtrConstant(0));
8570
8571   // Subtract the bias.
8572   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8573
8574   // Handle final rounding.
8575   EVT DestVT = Op.getValueType();
8576
8577   if (DestVT.bitsLT(MVT::f64))
8578     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8579                        DAG.getIntPtrConstant(0));
8580   if (DestVT.bitsGT(MVT::f64))
8581     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8582
8583   // Handle final rounding.
8584   return Sub;
8585 }
8586
8587 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8588                                                SelectionDAG &DAG) const {
8589   SDValue N0 = Op.getOperand(0);
8590   EVT SVT = N0.getValueType();
8591   SDLoc dl(Op);
8592
8593   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8594           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8595          "Custom UINT_TO_FP is not supported!");
8596
8597   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8598                              SVT.getVectorNumElements());
8599   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8600                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8601 }
8602
8603 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8604                                            SelectionDAG &DAG) const {
8605   SDValue N0 = Op.getOperand(0);
8606   SDLoc dl(Op);
8607
8608   if (Op.getValueType().isVector())
8609     return lowerUINT_TO_FP_vec(Op, DAG);
8610
8611   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8612   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8613   // the optimization here.
8614   if (DAG.SignBitIsZero(N0))
8615     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8616
8617   EVT SrcVT = N0.getValueType();
8618   EVT DstVT = Op.getValueType();
8619   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8620     return LowerUINT_TO_FP_i64(Op, DAG);
8621   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8622     return LowerUINT_TO_FP_i32(Op, DAG);
8623   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8624     return SDValue();
8625
8626   // Make a 64-bit buffer, and use it to build an FILD.
8627   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8628   if (SrcVT == MVT::i32) {
8629     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8630     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8631                                      getPointerTy(), StackSlot, WordOff);
8632     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8633                                   StackSlot, MachinePointerInfo(),
8634                                   false, false, 0);
8635     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8636                                   OffsetSlot, MachinePointerInfo(),
8637                                   false, false, 0);
8638     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8639     return Fild;
8640   }
8641
8642   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8643   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8644                                StackSlot, MachinePointerInfo(),
8645                                false, false, 0);
8646   // For i64 source, we need to add the appropriate power of 2 if the input
8647   // was negative.  This is the same as the optimization in
8648   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8649   // we must be careful to do the computation in x87 extended precision, not
8650   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8651   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8652   MachineMemOperand *MMO =
8653     DAG.getMachineFunction()
8654     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8655                           MachineMemOperand::MOLoad, 8, 8);
8656
8657   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8658   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8659   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8660                                          array_lengthof(Ops), MVT::i64, MMO);
8661
8662   APInt FF(32, 0x5F800000ULL);
8663
8664   // Check whether the sign bit is set.
8665   SDValue SignSet = DAG.getSetCC(dl,
8666                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8667                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8668                                  ISD::SETLT);
8669
8670   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8671   SDValue FudgePtr = DAG.getConstantPool(
8672                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8673                                          getPointerTy());
8674
8675   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8676   SDValue Zero = DAG.getIntPtrConstant(0);
8677   SDValue Four = DAG.getIntPtrConstant(4);
8678   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8679                                Zero, Four);
8680   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8681
8682   // Load the value out, extending it from f32 to f80.
8683   // FIXME: Avoid the extend by constructing the right constant pool?
8684   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8685                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8686                                  MVT::f32, false, false, 4);
8687   // Extend everything to 80 bits to force it to be done on x87.
8688   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8689   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8690 }
8691
8692 std::pair<SDValue,SDValue>
8693 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8694                                     bool IsSigned, bool IsReplace) const {
8695   SDLoc DL(Op);
8696
8697   EVT DstTy = Op.getValueType();
8698
8699   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8700     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8701     DstTy = MVT::i64;
8702   }
8703
8704   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8705          DstTy.getSimpleVT() >= MVT::i16 &&
8706          "Unknown FP_TO_INT to lower!");
8707
8708   // These are really Legal.
8709   if (DstTy == MVT::i32 &&
8710       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8711     return std::make_pair(SDValue(), SDValue());
8712   if (Subtarget->is64Bit() &&
8713       DstTy == MVT::i64 &&
8714       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8715     return std::make_pair(SDValue(), SDValue());
8716
8717   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8718   // stack slot, or into the FTOL runtime function.
8719   MachineFunction &MF = DAG.getMachineFunction();
8720   unsigned MemSize = DstTy.getSizeInBits()/8;
8721   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8722   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8723
8724   unsigned Opc;
8725   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8726     Opc = X86ISD::WIN_FTOL;
8727   else
8728     switch (DstTy.getSimpleVT().SimpleTy) {
8729     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8730     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8731     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8732     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8733     }
8734
8735   SDValue Chain = DAG.getEntryNode();
8736   SDValue Value = Op.getOperand(0);
8737   EVT TheVT = Op.getOperand(0).getValueType();
8738   // FIXME This causes a redundant load/store if the SSE-class value is already
8739   // in memory, such as if it is on the callstack.
8740   if (isScalarFPTypeInSSEReg(TheVT)) {
8741     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8742     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8743                          MachinePointerInfo::getFixedStack(SSFI),
8744                          false, false, 0);
8745     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8746     SDValue Ops[] = {
8747       Chain, StackSlot, DAG.getValueType(TheVT)
8748     };
8749
8750     MachineMemOperand *MMO =
8751       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8752                               MachineMemOperand::MOLoad, MemSize, MemSize);
8753     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8754                                     array_lengthof(Ops), DstTy, MMO);
8755     Chain = Value.getValue(1);
8756     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8757     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8758   }
8759
8760   MachineMemOperand *MMO =
8761     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8762                             MachineMemOperand::MOStore, MemSize, MemSize);
8763
8764   if (Opc != X86ISD::WIN_FTOL) {
8765     // Build the FP_TO_INT*_IN_MEM
8766     SDValue Ops[] = { Chain, Value, StackSlot };
8767     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8768                                            Ops, array_lengthof(Ops), DstTy,
8769                                            MMO);
8770     return std::make_pair(FIST, StackSlot);
8771   } else {
8772     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8773       DAG.getVTList(MVT::Other, MVT::Glue),
8774       Chain, Value);
8775     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8776       MVT::i32, ftol.getValue(1));
8777     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8778       MVT::i32, eax.getValue(2));
8779     SDValue Ops[] = { eax, edx };
8780     SDValue pair = IsReplace
8781       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8782       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8783     return std::make_pair(pair, SDValue());
8784   }
8785 }
8786
8787 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8788                               const X86Subtarget *Subtarget) {
8789   MVT VT = Op->getSimpleValueType(0);
8790   SDValue In = Op->getOperand(0);
8791   MVT InVT = In.getSimpleValueType();
8792   SDLoc dl(Op);
8793
8794   // Optimize vectors in AVX mode:
8795   //
8796   //   v8i16 -> v8i32
8797   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8798   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8799   //   Concat upper and lower parts.
8800   //
8801   //   v4i32 -> v4i64
8802   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8803   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8804   //   Concat upper and lower parts.
8805   //
8806
8807   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8808       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8809     return SDValue();
8810
8811   if (Subtarget->hasInt256())
8812     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8813
8814   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8815   SDValue Undef = DAG.getUNDEF(InVT);
8816   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8817   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8818   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8819
8820   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8821                              VT.getVectorNumElements()/2);
8822
8823   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8824   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8825
8826   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8827 }
8828
8829 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
8830                                SelectionDAG &DAG) {
8831   if (Subtarget->hasFp256()) {
8832     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8833     if (Res.getNode())
8834       return Res;
8835   }
8836
8837   return SDValue();
8838 }
8839
8840 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
8841                                 SelectionDAG &DAG) {
8842   SDLoc DL(Op);
8843   MVT VT = Op.getSimpleValueType();
8844   SDValue In = Op.getOperand(0);
8845   MVT SVT = In.getSimpleValueType();
8846
8847   if (Subtarget->hasFp256()) {
8848     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8849     if (Res.getNode())
8850       return Res;
8851   }
8852
8853   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8854       VT.getVectorNumElements() != SVT.getVectorNumElements())
8855     return SDValue();
8856
8857   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8858
8859   // AVX2 has better support of integer extending.
8860   if (Subtarget->hasInt256())
8861     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8862
8863   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8864   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8865   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8866                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8867                                                 DAG.getUNDEF(MVT::v8i16),
8868                                                 &Mask[0]));
8869
8870   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8871 }
8872
8873 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8874   SDLoc DL(Op);
8875   MVT VT = Op.getSimpleValueType();
8876   SDValue In = Op.getOperand(0);
8877   MVT SVT = In.getSimpleValueType();
8878
8879   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8880     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8881     if (Subtarget->hasInt256()) {
8882       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8883       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8884       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8885                                 ShufMask);
8886       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8887                          DAG.getIntPtrConstant(0));
8888     }
8889
8890     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8891     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8892                                DAG.getIntPtrConstant(0));
8893     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8894                                DAG.getIntPtrConstant(2));
8895
8896     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8897     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8898
8899     // The PSHUFD mask:
8900     static const int ShufMask1[] = {0, 2, 0, 0};
8901     SDValue Undef = DAG.getUNDEF(VT);
8902     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8903     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8904
8905     // The MOVLHPS mask:
8906     static const int ShufMask2[] = {0, 1, 4, 5};
8907     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8908   }
8909
8910   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8911     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8912     if (Subtarget->hasInt256()) {
8913       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8914
8915       SmallVector<SDValue,32> pshufbMask;
8916       for (unsigned i = 0; i < 2; ++i) {
8917         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8918         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8919         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8920         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8921         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8922         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8923         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8924         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8925         for (unsigned j = 0; j < 8; ++j)
8926           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8927       }
8928       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8929                                &pshufbMask[0], 32);
8930       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8931       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8932
8933       static const int ShufMask[] = {0,  2,  -1,  -1};
8934       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8935                                 &ShufMask[0]);
8936       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8937                        DAG.getIntPtrConstant(0));
8938       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8939     }
8940
8941     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8942                                DAG.getIntPtrConstant(0));
8943
8944     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8945                                DAG.getIntPtrConstant(4));
8946
8947     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8948     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8949
8950     // The PSHUFB mask:
8951     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8952                                    -1, -1, -1, -1, -1, -1, -1, -1};
8953
8954     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8955     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8956     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8957
8958     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8959     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8960
8961     // The MOVLHPS Mask:
8962     static const int ShufMask2[] = {0, 1, 4, 5};
8963     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8964     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8965   }
8966
8967   // Handle truncation of V256 to V128 using shuffles.
8968   if (!VT.is128BitVector() || !SVT.is256BitVector())
8969     return SDValue();
8970
8971   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8972          "Invalid op");
8973   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8974
8975   unsigned NumElems = VT.getVectorNumElements();
8976   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8977                              NumElems * 2);
8978
8979   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8980   // Prepare truncation shuffle mask
8981   for (unsigned i = 0; i != NumElems; ++i)
8982     MaskVec[i] = i * 2;
8983   SDValue V = DAG.getVectorShuffle(NVT, DL,
8984                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8985                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8986   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8987                      DAG.getIntPtrConstant(0));
8988 }
8989
8990 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8991                                            SelectionDAG &DAG) const {
8992   MVT VT = Op.getSimpleValueType();
8993   if (VT.isVector()) {
8994     if (VT == MVT::v8i16)
8995       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8996                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8997                                      MVT::v8i32, Op.getOperand(0)));
8998     return SDValue();
8999   }
9000
9001   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9002     /*IsSigned=*/ true, /*IsReplace=*/ false);
9003   SDValue FIST = Vals.first, StackSlot = Vals.second;
9004   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9005   if (FIST.getNode() == 0) return Op;
9006
9007   if (StackSlot.getNode())
9008     // Load the result.
9009     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9010                        FIST, StackSlot, MachinePointerInfo(),
9011                        false, false, false, 0);
9012
9013   // The node is the result.
9014   return FIST;
9015 }
9016
9017 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9018                                            SelectionDAG &DAG) const {
9019   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9020     /*IsSigned=*/ false, /*IsReplace=*/ false);
9021   SDValue FIST = Vals.first, StackSlot = Vals.second;
9022   assert(FIST.getNode() && "Unexpected failure");
9023
9024   if (StackSlot.getNode())
9025     // Load the result.
9026     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9027                        FIST, StackSlot, MachinePointerInfo(),
9028                        false, false, false, 0);
9029
9030   // The node is the result.
9031   return FIST;
9032 }
9033
9034 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9035   SDLoc DL(Op);
9036   MVT VT = Op.getSimpleValueType();
9037   SDValue In = Op.getOperand(0);
9038   MVT SVT = In.getSimpleValueType();
9039
9040   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9041
9042   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9043                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9044                                  In, DAG.getUNDEF(SVT)));
9045 }
9046
9047 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
9048   LLVMContext *Context = DAG.getContext();
9049   SDLoc dl(Op);
9050   MVT VT = Op.getSimpleValueType();
9051   MVT EltVT = VT;
9052   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9053   if (VT.isVector()) {
9054     EltVT = VT.getVectorElementType();
9055     NumElts = VT.getVectorNumElements();
9056   }
9057   Constant *C;
9058   if (EltVT == MVT::f64)
9059     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9060                                           APInt(64, ~(1ULL << 63))));
9061   else
9062     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9063                                           APInt(32, ~(1U << 31))));
9064   C = ConstantVector::getSplat(NumElts, C);
9065   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9066   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9067   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9068                              MachinePointerInfo::getConstantPool(),
9069                              false, false, false, Alignment);
9070   if (VT.isVector()) {
9071     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9072     return DAG.getNode(ISD::BITCAST, dl, VT,
9073                        DAG.getNode(ISD::AND, dl, ANDVT,
9074                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9075                                                Op.getOperand(0)),
9076                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9077   }
9078   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9079 }
9080
9081 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
9082   LLVMContext *Context = DAG.getContext();
9083   SDLoc dl(Op);
9084   MVT VT = Op.getSimpleValueType();
9085   MVT EltVT = VT;
9086   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9087   if (VT.isVector()) {
9088     EltVT = VT.getVectorElementType();
9089     NumElts = VT.getVectorNumElements();
9090   }
9091   Constant *C;
9092   if (EltVT == MVT::f64)
9093     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9094                                           APInt(64, 1ULL << 63)));
9095   else
9096     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9097                                           APInt(32, 1U << 31)));
9098   C = ConstantVector::getSplat(NumElts, C);
9099   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9100   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9101   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9102                              MachinePointerInfo::getConstantPool(),
9103                              false, false, false, Alignment);
9104   if (VT.isVector()) {
9105     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9106     return DAG.getNode(ISD::BITCAST, dl, VT,
9107                        DAG.getNode(ISD::XOR, dl, XORVT,
9108                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9109                                                Op.getOperand(0)),
9110                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9111   }
9112
9113   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9114 }
9115
9116 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9117   LLVMContext *Context = DAG.getContext();
9118   SDValue Op0 = Op.getOperand(0);
9119   SDValue Op1 = Op.getOperand(1);
9120   SDLoc dl(Op);
9121   MVT VT = Op.getSimpleValueType();
9122   MVT SrcVT = Op1.getSimpleValueType();
9123
9124   // If second operand is smaller, extend it first.
9125   if (SrcVT.bitsLT(VT)) {
9126     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9127     SrcVT = VT;
9128   }
9129   // And if it is bigger, shrink it first.
9130   if (SrcVT.bitsGT(VT)) {
9131     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9132     SrcVT = VT;
9133   }
9134
9135   // At this point the operands and the result should have the same
9136   // type, and that won't be f80 since that is not custom lowered.
9137
9138   // First get the sign bit of second operand.
9139   SmallVector<Constant*,4> CV;
9140   if (SrcVT == MVT::f64) {
9141     const fltSemantics &Sem = APFloat::IEEEdouble;
9142     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9143     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9144   } else {
9145     const fltSemantics &Sem = APFloat::IEEEsingle;
9146     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9147     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9148     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9149     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9150   }
9151   Constant *C = ConstantVector::get(CV);
9152   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9153   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9154                               MachinePointerInfo::getConstantPool(),
9155                               false, false, false, 16);
9156   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9157
9158   // Shift sign bit right or left if the two operands have different types.
9159   if (SrcVT.bitsGT(VT)) {
9160     // Op0 is MVT::f32, Op1 is MVT::f64.
9161     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9162     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9163                           DAG.getConstant(32, MVT::i32));
9164     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9165     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9166                           DAG.getIntPtrConstant(0));
9167   }
9168
9169   // Clear first operand sign bit.
9170   CV.clear();
9171   if (VT == MVT::f64) {
9172     const fltSemantics &Sem = APFloat::IEEEdouble;
9173     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9174                                                    APInt(64, ~(1ULL << 63)))));
9175     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9176   } else {
9177     const fltSemantics &Sem = APFloat::IEEEsingle;
9178     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9179                                                    APInt(32, ~(1U << 31)))));
9180     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9181     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9182     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9183   }
9184   C = ConstantVector::get(CV);
9185   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9186   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9187                               MachinePointerInfo::getConstantPool(),
9188                               false, false, false, 16);
9189   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9190
9191   // Or the value with the sign bit.
9192   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9193 }
9194
9195 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9196   SDValue N0 = Op.getOperand(0);
9197   SDLoc dl(Op);
9198   MVT VT = Op.getSimpleValueType();
9199
9200   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9201   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9202                                   DAG.getConstant(1, VT));
9203   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9204 }
9205
9206 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9207 //
9208 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9209                                       SelectionDAG &DAG) {
9210   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9211
9212   if (!Subtarget->hasSSE41())
9213     return SDValue();
9214
9215   if (!Op->hasOneUse())
9216     return SDValue();
9217
9218   SDNode *N = Op.getNode();
9219   SDLoc DL(N);
9220
9221   SmallVector<SDValue, 8> Opnds;
9222   DenseMap<SDValue, unsigned> VecInMap;
9223   EVT VT = MVT::Other;
9224
9225   // Recognize a special case where a vector is casted into wide integer to
9226   // test all 0s.
9227   Opnds.push_back(N->getOperand(0));
9228   Opnds.push_back(N->getOperand(1));
9229
9230   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9231     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9232     // BFS traverse all OR'd operands.
9233     if (I->getOpcode() == ISD::OR) {
9234       Opnds.push_back(I->getOperand(0));
9235       Opnds.push_back(I->getOperand(1));
9236       // Re-evaluate the number of nodes to be traversed.
9237       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9238       continue;
9239     }
9240
9241     // Quit if a non-EXTRACT_VECTOR_ELT
9242     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9243       return SDValue();
9244
9245     // Quit if without a constant index.
9246     SDValue Idx = I->getOperand(1);
9247     if (!isa<ConstantSDNode>(Idx))
9248       return SDValue();
9249
9250     SDValue ExtractedFromVec = I->getOperand(0);
9251     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9252     if (M == VecInMap.end()) {
9253       VT = ExtractedFromVec.getValueType();
9254       // Quit if not 128/256-bit vector.
9255       if (!VT.is128BitVector() && !VT.is256BitVector())
9256         return SDValue();
9257       // Quit if not the same type.
9258       if (VecInMap.begin() != VecInMap.end() &&
9259           VT != VecInMap.begin()->first.getValueType())
9260         return SDValue();
9261       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9262     }
9263     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9264   }
9265
9266   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9267          "Not extracted from 128-/256-bit vector.");
9268
9269   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9270   SmallVector<SDValue, 8> VecIns;
9271
9272   for (DenseMap<SDValue, unsigned>::const_iterator
9273         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9274     // Quit if not all elements are used.
9275     if (I->second != FullMask)
9276       return SDValue();
9277     VecIns.push_back(I->first);
9278   }
9279
9280   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9281
9282   // Cast all vectors into TestVT for PTEST.
9283   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9284     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9285
9286   // If more than one full vectors are evaluated, OR them first before PTEST.
9287   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9288     // Each iteration will OR 2 nodes and append the result until there is only
9289     // 1 node left, i.e. the final OR'd value of all vectors.
9290     SDValue LHS = VecIns[Slot];
9291     SDValue RHS = VecIns[Slot + 1];
9292     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9293   }
9294
9295   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9296                      VecIns.back(), VecIns.back());
9297 }
9298
9299 /// Emit nodes that will be selected as "test Op0,Op0", or something
9300 /// equivalent.
9301 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9302                                     SelectionDAG &DAG) const {
9303   SDLoc dl(Op);
9304
9305   // CF and OF aren't always set the way we want. Determine which
9306   // of these we need.
9307   bool NeedCF = false;
9308   bool NeedOF = false;
9309   switch (X86CC) {
9310   default: break;
9311   case X86::COND_A: case X86::COND_AE:
9312   case X86::COND_B: case X86::COND_BE:
9313     NeedCF = true;
9314     break;
9315   case X86::COND_G: case X86::COND_GE:
9316   case X86::COND_L: case X86::COND_LE:
9317   case X86::COND_O: case X86::COND_NO:
9318     NeedOF = true;
9319     break;
9320   }
9321
9322   // See if we can use the EFLAGS value from the operand instead of
9323   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9324   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9325   if (Op.getResNo() != 0 || NeedOF || NeedCF)
9326     // Emit a CMP with 0, which is the TEST pattern.
9327     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9328                        DAG.getConstant(0, Op.getValueType()));
9329
9330   unsigned Opcode = 0;
9331   unsigned NumOperands = 0;
9332
9333   // Truncate operations may prevent the merge of the SETCC instruction
9334   // and the arithmetic intruction before it. Attempt to truncate the operands
9335   // of the arithmetic instruction and use a reduced bit-width instruction.
9336   bool NeedTruncation = false;
9337   SDValue ArithOp = Op;
9338   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9339     SDValue Arith = Op->getOperand(0);
9340     // Both the trunc and the arithmetic op need to have one user each.
9341     if (Arith->hasOneUse())
9342       switch (Arith.getOpcode()) {
9343         default: break;
9344         case ISD::ADD:
9345         case ISD::SUB:
9346         case ISD::AND:
9347         case ISD::OR:
9348         case ISD::XOR: {
9349           NeedTruncation = true;
9350           ArithOp = Arith;
9351         }
9352       }
9353   }
9354
9355   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9356   // which may be the result of a CAST.  We use the variable 'Op', which is the
9357   // non-casted variable when we check for possible users.
9358   switch (ArithOp.getOpcode()) {
9359   case ISD::ADD:
9360     // Due to an isel shortcoming, be conservative if this add is likely to be
9361     // selected as part of a load-modify-store instruction. When the root node
9362     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9363     // uses of other nodes in the match, such as the ADD in this case. This
9364     // leads to the ADD being left around and reselected, with the result being
9365     // two adds in the output.  Alas, even if none our users are stores, that
9366     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9367     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9368     // climbing the DAG back to the root, and it doesn't seem to be worth the
9369     // effort.
9370     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9371          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9372       if (UI->getOpcode() != ISD::CopyToReg &&
9373           UI->getOpcode() != ISD::SETCC &&
9374           UI->getOpcode() != ISD::STORE)
9375         goto default_case;
9376
9377     if (ConstantSDNode *C =
9378         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9379       // An add of one will be selected as an INC.
9380       if (C->getAPIntValue() == 1) {
9381         Opcode = X86ISD::INC;
9382         NumOperands = 1;
9383         break;
9384       }
9385
9386       // An add of negative one (subtract of one) will be selected as a DEC.
9387       if (C->getAPIntValue().isAllOnesValue()) {
9388         Opcode = X86ISD::DEC;
9389         NumOperands = 1;
9390         break;
9391       }
9392     }
9393
9394     // Otherwise use a regular EFLAGS-setting add.
9395     Opcode = X86ISD::ADD;
9396     NumOperands = 2;
9397     break;
9398   case ISD::AND: {
9399     // If the primary and result isn't used, don't bother using X86ISD::AND,
9400     // because a TEST instruction will be better.
9401     bool NonFlagUse = false;
9402     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9403            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9404       SDNode *User = *UI;
9405       unsigned UOpNo = UI.getOperandNo();
9406       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9407         // Look pass truncate.
9408         UOpNo = User->use_begin().getOperandNo();
9409         User = *User->use_begin();
9410       }
9411
9412       if (User->getOpcode() != ISD::BRCOND &&
9413           User->getOpcode() != ISD::SETCC &&
9414           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9415         NonFlagUse = true;
9416         break;
9417       }
9418     }
9419
9420     if (!NonFlagUse)
9421       break;
9422   }
9423     // FALL THROUGH
9424   case ISD::SUB:
9425   case ISD::OR:
9426   case ISD::XOR:
9427     // Due to the ISEL shortcoming noted above, be conservative if this op is
9428     // likely to be selected as part of a load-modify-store instruction.
9429     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9430            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9431       if (UI->getOpcode() == ISD::STORE)
9432         goto default_case;
9433
9434     // Otherwise use a regular EFLAGS-setting instruction.
9435     switch (ArithOp.getOpcode()) {
9436     default: llvm_unreachable("unexpected operator!");
9437     case ISD::SUB: Opcode = X86ISD::SUB; break;
9438     case ISD::XOR: Opcode = X86ISD::XOR; break;
9439     case ISD::AND: Opcode = X86ISD::AND; break;
9440     case ISD::OR: {
9441       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9442         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9443         if (EFLAGS.getNode())
9444           return EFLAGS;
9445       }
9446       Opcode = X86ISD::OR;
9447       break;
9448     }
9449     }
9450
9451     NumOperands = 2;
9452     break;
9453   case X86ISD::ADD:
9454   case X86ISD::SUB:
9455   case X86ISD::INC:
9456   case X86ISD::DEC:
9457   case X86ISD::OR:
9458   case X86ISD::XOR:
9459   case X86ISD::AND:
9460     return SDValue(Op.getNode(), 1);
9461   default:
9462   default_case:
9463     break;
9464   }
9465
9466   // If we found that truncation is beneficial, perform the truncation and
9467   // update 'Op'.
9468   if (NeedTruncation) {
9469     EVT VT = Op.getValueType();
9470     SDValue WideVal = Op->getOperand(0);
9471     EVT WideVT = WideVal.getValueType();
9472     unsigned ConvertedOp = 0;
9473     // Use a target machine opcode to prevent further DAGCombine
9474     // optimizations that may separate the arithmetic operations
9475     // from the setcc node.
9476     switch (WideVal.getOpcode()) {
9477       default: break;
9478       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9479       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9480       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9481       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9482       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9483     }
9484
9485     if (ConvertedOp) {
9486       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9487       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9488         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9489         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9490         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9491       }
9492     }
9493   }
9494
9495   if (Opcode == 0)
9496     // Emit a CMP with 0, which is the TEST pattern.
9497     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9498                        DAG.getConstant(0, Op.getValueType()));
9499
9500   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9501   SmallVector<SDValue, 4> Ops;
9502   for (unsigned i = 0; i != NumOperands; ++i)
9503     Ops.push_back(Op.getOperand(i));
9504
9505   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9506   DAG.ReplaceAllUsesWith(Op, New);
9507   return SDValue(New.getNode(), 1);
9508 }
9509
9510 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9511 /// equivalent.
9512 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9513                                    SelectionDAG &DAG) const {
9514   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9515     if (C->getAPIntValue() == 0)
9516       return EmitTest(Op0, X86CC, DAG);
9517
9518   SDLoc dl(Op0);
9519   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9520        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9521     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9522     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9523     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9524                               Op0, Op1);
9525     return SDValue(Sub.getNode(), 1);
9526   }
9527   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9528 }
9529
9530 /// Convert a comparison if required by the subtarget.
9531 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9532                                                  SelectionDAG &DAG) const {
9533   // If the subtarget does not support the FUCOMI instruction, floating-point
9534   // comparisons have to be converted.
9535   if (Subtarget->hasCMov() ||
9536       Cmp.getOpcode() != X86ISD::CMP ||
9537       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9538       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9539     return Cmp;
9540
9541   // The instruction selector will select an FUCOM instruction instead of
9542   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9543   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9544   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9545   SDLoc dl(Cmp);
9546   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9547   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9548   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9549                             DAG.getConstant(8, MVT::i8));
9550   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9551   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9552 }
9553
9554 static bool isAllOnes(SDValue V) {
9555   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9556   return C && C->isAllOnesValue();
9557 }
9558
9559 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9560 /// if it's possible.
9561 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9562                                      SDLoc dl, SelectionDAG &DAG) const {
9563   SDValue Op0 = And.getOperand(0);
9564   SDValue Op1 = And.getOperand(1);
9565   if (Op0.getOpcode() == ISD::TRUNCATE)
9566     Op0 = Op0.getOperand(0);
9567   if (Op1.getOpcode() == ISD::TRUNCATE)
9568     Op1 = Op1.getOperand(0);
9569
9570   SDValue LHS, RHS;
9571   if (Op1.getOpcode() == ISD::SHL)
9572     std::swap(Op0, Op1);
9573   if (Op0.getOpcode() == ISD::SHL) {
9574     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9575       if (And00C->getZExtValue() == 1) {
9576         // If we looked past a truncate, check that it's only truncating away
9577         // known zeros.
9578         unsigned BitWidth = Op0.getValueSizeInBits();
9579         unsigned AndBitWidth = And.getValueSizeInBits();
9580         if (BitWidth > AndBitWidth) {
9581           APInt Zeros, Ones;
9582           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9583           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9584             return SDValue();
9585         }
9586         LHS = Op1;
9587         RHS = Op0.getOperand(1);
9588       }
9589   } else if (Op1.getOpcode() == ISD::Constant) {
9590     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9591     uint64_t AndRHSVal = AndRHS->getZExtValue();
9592     SDValue AndLHS = Op0;
9593
9594     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9595       LHS = AndLHS.getOperand(0);
9596       RHS = AndLHS.getOperand(1);
9597     }
9598
9599     // Use BT if the immediate can't be encoded in a TEST instruction.
9600     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9601       LHS = AndLHS;
9602       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9603     }
9604   }
9605
9606   if (LHS.getNode()) {
9607     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9608     // instruction.  Since the shift amount is in-range-or-undefined, we know
9609     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9610     // the encoding for the i16 version is larger than the i32 version.
9611     // Also promote i16 to i32 for performance / code size reason.
9612     if (LHS.getValueType() == MVT::i8 ||
9613         LHS.getValueType() == MVT::i16)
9614       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9615
9616     // If the operand types disagree, extend the shift amount to match.  Since
9617     // BT ignores high bits (like shifts) we can use anyextend.
9618     if (LHS.getValueType() != RHS.getValueType())
9619       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9620
9621     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9622     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9623     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9624                        DAG.getConstant(Cond, MVT::i8), BT);
9625   }
9626
9627   return SDValue();
9628 }
9629
9630 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9631 /// mask CMPs.
9632 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9633                               SDValue &Op1) {
9634   unsigned SSECC;
9635   bool Swap = false;
9636
9637   // SSE Condition code mapping:
9638   //  0 - EQ
9639   //  1 - LT
9640   //  2 - LE
9641   //  3 - UNORD
9642   //  4 - NEQ
9643   //  5 - NLT
9644   //  6 - NLE
9645   //  7 - ORD
9646   switch (SetCCOpcode) {
9647   default: llvm_unreachable("Unexpected SETCC condition");
9648   case ISD::SETOEQ:
9649   case ISD::SETEQ:  SSECC = 0; break;
9650   case ISD::SETOGT:
9651   case ISD::SETGT:  Swap = true; // Fallthrough
9652   case ISD::SETLT:
9653   case ISD::SETOLT: SSECC = 1; break;
9654   case ISD::SETOGE:
9655   case ISD::SETGE:  Swap = true; // Fallthrough
9656   case ISD::SETLE:
9657   case ISD::SETOLE: SSECC = 2; break;
9658   case ISD::SETUO:  SSECC = 3; break;
9659   case ISD::SETUNE:
9660   case ISD::SETNE:  SSECC = 4; break;
9661   case ISD::SETULE: Swap = true; // Fallthrough
9662   case ISD::SETUGE: SSECC = 5; break;
9663   case ISD::SETULT: Swap = true; // Fallthrough
9664   case ISD::SETUGT: SSECC = 6; break;
9665   case ISD::SETO:   SSECC = 7; break;
9666   case ISD::SETUEQ:
9667   case ISD::SETONE: SSECC = 8; break;
9668   }
9669   if (Swap)
9670     std::swap(Op0, Op1);
9671
9672   return SSECC;
9673 }
9674
9675 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9676 // ones, and then concatenate the result back.
9677 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9678   MVT VT = Op.getSimpleValueType();
9679
9680   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9681          "Unsupported value type for operation");
9682
9683   unsigned NumElems = VT.getVectorNumElements();
9684   SDLoc dl(Op);
9685   SDValue CC = Op.getOperand(2);
9686
9687   // Extract the LHS vectors
9688   SDValue LHS = Op.getOperand(0);
9689   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9690   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9691
9692   // Extract the RHS vectors
9693   SDValue RHS = Op.getOperand(1);
9694   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9695   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9696
9697   // Issue the operation on the smaller types and concatenate the result back
9698   MVT EltVT = VT.getVectorElementType();
9699   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9700   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9701                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9702                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9703 }
9704
9705 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
9706   SDValue Cond;
9707   SDValue Op0 = Op.getOperand(0);
9708   SDValue Op1 = Op.getOperand(1);
9709   SDValue CC = Op.getOperand(2);
9710   MVT VT = Op.getSimpleValueType();
9711
9712   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
9713          Op.getValueType().getScalarType() == MVT::i1 &&
9714          "Cannot set masked compare for this operation");
9715
9716   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9717   SDLoc dl(Op);
9718
9719   bool Unsigned = false;
9720   unsigned SSECC;
9721   switch (SetCCOpcode) {
9722   default: llvm_unreachable("Unexpected SETCC condition");
9723   case ISD::SETNE:  SSECC = 4; break;
9724   case ISD::SETEQ:  SSECC = 0; break;
9725   case ISD::SETUGT: Unsigned = true;
9726   case ISD::SETGT:  SSECC = 6; break; // NLE
9727   case ISD::SETULT: Unsigned = true;
9728   case ISD::SETLT:  SSECC = 1; break;
9729   case ISD::SETUGE: Unsigned = true;
9730   case ISD::SETGE:  SSECC = 5; break; // NLT
9731   case ISD::SETULE: Unsigned = true;
9732   case ISD::SETLE:  SSECC = 2; break;
9733   }
9734   unsigned  Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
9735   return DAG.getNode(Opc, dl, VT, Op0, Op1,
9736                      DAG.getConstant(SSECC, MVT::i8));
9737
9738 }
9739
9740 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9741                            SelectionDAG &DAG) {
9742   SDValue Cond;
9743   SDValue Op0 = Op.getOperand(0);
9744   SDValue Op1 = Op.getOperand(1);
9745   SDValue CC = Op.getOperand(2);
9746   MVT VT = Op.getSimpleValueType();
9747   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9748   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
9749   SDLoc dl(Op);
9750
9751   if (isFP) {
9752 #ifndef NDEBUG
9753     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
9754     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9755 #endif
9756
9757     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
9758     unsigned Opc = X86ISD::CMPP;
9759     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
9760       assert(VT.getVectorNumElements() <= 16);
9761       Opc = X86ISD::CMPM;
9762     }
9763     // In the two special cases we can't handle, emit two comparisons.
9764     if (SSECC == 8) {
9765       unsigned CC0, CC1;
9766       unsigned CombineOpc;
9767       if (SetCCOpcode == ISD::SETUEQ) {
9768         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9769       } else {
9770         assert(SetCCOpcode == ISD::SETONE);
9771         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9772       }
9773
9774       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
9775                                  DAG.getConstant(CC0, MVT::i8));
9776       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
9777                                  DAG.getConstant(CC1, MVT::i8));
9778       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9779     }
9780     // Handle all other FP comparisons here.
9781     return DAG.getNode(Opc, dl, VT, Op0, Op1,
9782                        DAG.getConstant(SSECC, MVT::i8));
9783   }
9784
9785   // Break 256-bit integer vector compare into smaller ones.
9786   if (VT.is256BitVector() && !Subtarget->hasInt256())
9787     return Lower256IntVSETCC(Op, DAG);
9788
9789   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
9790   EVT OpVT = Op1.getValueType();
9791   if (Subtarget->hasAVX512()) {
9792     if (Op1.getValueType().is512BitVector() ||
9793         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
9794       return LowerIntVSETCC_AVX512(Op, DAG);
9795
9796     // In AVX-512 architecture setcc returns mask with i1 elements,
9797     // But there is no compare instruction for i8 and i16 elements.
9798     // We are not talking about 512-bit operands in this case, these
9799     // types are illegal.
9800     if (MaskResult &&
9801         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
9802          OpVT.getVectorElementType().getSizeInBits() >= 8))
9803       return DAG.getNode(ISD::TRUNCATE, dl, VT,
9804                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
9805   }
9806
9807   // We are handling one of the integer comparisons here.  Since SSE only has
9808   // GT and EQ comparisons for integer, swapping operands and multiple
9809   // operations may be required for some comparisons.
9810   unsigned Opc;
9811   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9812   
9813   switch (SetCCOpcode) {
9814   default: llvm_unreachable("Unexpected SETCC condition");
9815   case ISD::SETNE:  Invert = true;
9816   case ISD::SETEQ:  Opc = MaskResult? X86ISD::PCMPEQM: X86ISD::PCMPEQ; break;
9817   case ISD::SETLT:  Swap = true;
9818   case ISD::SETGT:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT; break;
9819   case ISD::SETGE:  Swap = true;
9820   case ISD::SETLE:  Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9821                     Invert = true; break;
9822   case ISD::SETULT: Swap = true;
9823   case ISD::SETUGT: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9824                     FlipSigns = true; break;
9825   case ISD::SETUGE: Swap = true;
9826   case ISD::SETULE: Opc = MaskResult? X86ISD::PCMPGTM: X86ISD::PCMPGT;
9827                     FlipSigns = true; Invert = true; break;
9828   }
9829   
9830   // Special case: Use min/max operations for SETULE/SETUGE
9831   MVT VET = VT.getVectorElementType();
9832   bool hasMinMax =
9833        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
9834     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
9835   
9836   if (hasMinMax) {
9837     switch (SetCCOpcode) {
9838     default: break;
9839     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
9840     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
9841     }
9842     
9843     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
9844   }
9845   
9846   if (Swap)
9847     std::swap(Op0, Op1);
9848
9849   // Check that the operation in question is available (most are plain SSE2,
9850   // but PCMPGTQ and PCMPEQQ have different requirements).
9851   if (VT == MVT::v2i64) {
9852     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9853       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9854
9855       // First cast everything to the right type.
9856       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9857       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9858
9859       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9860       // bits of the inputs before performing those operations. The lower
9861       // compare is always unsigned.
9862       SDValue SB;
9863       if (FlipSigns) {
9864         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9865       } else {
9866         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9867         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9868         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9869                          Sign, Zero, Sign, Zero);
9870       }
9871       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9872       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9873
9874       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9875       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9876       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9877
9878       // Create masks for only the low parts/high parts of the 64 bit integers.
9879       static const int MaskHi[] = { 1, 1, 3, 3 };
9880       static const int MaskLo[] = { 0, 0, 2, 2 };
9881       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9882       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9883       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9884
9885       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9886       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9887
9888       if (Invert)
9889         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9890
9891       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9892     }
9893
9894     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9895       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9896       // pcmpeqd + pshufd + pand.
9897       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9898
9899       // First cast everything to the right type.
9900       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9901       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9902
9903       // Do the compare.
9904       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9905
9906       // Make sure the lower and upper halves are both all-ones.
9907       static const int Mask[] = { 1, 0, 3, 2 };
9908       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9909       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9910
9911       if (Invert)
9912         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9913
9914       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9915     }
9916   }
9917
9918   // Since SSE has no unsigned integer comparisons, we need to flip the sign
9919   // bits of the inputs before performing those operations.
9920   if (FlipSigns) {
9921     EVT EltVT = VT.getVectorElementType();
9922     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9923     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9924     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9925   }
9926
9927   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9928
9929   // If the logical-not of the result is required, perform that now.
9930   if (Invert)
9931     Result = DAG.getNOT(dl, Result, VT);
9932   
9933   if (MinMax)
9934     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
9935
9936   return Result;
9937 }
9938
9939 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9940
9941   MVT VT = Op.getSimpleValueType();
9942
9943   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9944
9945   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9946   SDValue Op0 = Op.getOperand(0);
9947   SDValue Op1 = Op.getOperand(1);
9948   SDLoc dl(Op);
9949   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9950
9951   // Optimize to BT if possible.
9952   // Lower (X & (1 << N)) == 0 to BT(X, N).
9953   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9954   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9955   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9956       Op1.getOpcode() == ISD::Constant &&
9957       cast<ConstantSDNode>(Op1)->isNullValue() &&
9958       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9959     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9960     if (NewSetCC.getNode())
9961       return NewSetCC;
9962   }
9963
9964   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9965   // these.
9966   if (Op1.getOpcode() == ISD::Constant &&
9967       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9968        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9969       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9970
9971     // If the input is a setcc, then reuse the input setcc or use a new one with
9972     // the inverted condition.
9973     if (Op0.getOpcode() == X86ISD::SETCC) {
9974       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9975       bool Invert = (CC == ISD::SETNE) ^
9976         cast<ConstantSDNode>(Op1)->isNullValue();
9977       if (!Invert) return Op0;
9978
9979       CCode = X86::GetOppositeBranchCondition(CCode);
9980       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9981                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9982     }
9983   }
9984
9985   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
9986   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9987   if (X86CC == X86::COND_INVALID)
9988     return SDValue();
9989
9990   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9991   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9992   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9993                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9994 }
9995
9996 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9997 static bool isX86LogicalCmp(SDValue Op) {
9998   unsigned Opc = Op.getNode()->getOpcode();
9999   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10000       Opc == X86ISD::SAHF)
10001     return true;
10002   if (Op.getResNo() == 1 &&
10003       (Opc == X86ISD::ADD ||
10004        Opc == X86ISD::SUB ||
10005        Opc == X86ISD::ADC ||
10006        Opc == X86ISD::SBB ||
10007        Opc == X86ISD::SMUL ||
10008        Opc == X86ISD::UMUL ||
10009        Opc == X86ISD::INC ||
10010        Opc == X86ISD::DEC ||
10011        Opc == X86ISD::OR ||
10012        Opc == X86ISD::XOR ||
10013        Opc == X86ISD::AND))
10014     return true;
10015
10016   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10017     return true;
10018
10019   return false;
10020 }
10021
10022 static bool isZero(SDValue V) {
10023   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10024   return C && C->isNullValue();
10025 }
10026
10027 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10028   if (V.getOpcode() != ISD::TRUNCATE)
10029     return false;
10030
10031   SDValue VOp0 = V.getOperand(0);
10032   unsigned InBits = VOp0.getValueSizeInBits();
10033   unsigned Bits = V.getValueSizeInBits();
10034   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10035 }
10036
10037 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10038   bool addTest = true;
10039   SDValue Cond  = Op.getOperand(0);
10040   SDValue Op1 = Op.getOperand(1);
10041   SDValue Op2 = Op.getOperand(2);
10042   SDLoc DL(Op);
10043   EVT VT = Op1.getValueType();
10044   SDValue CC;
10045
10046   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10047   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10048   // sequence later on.
10049   if (Cond.getOpcode() == ISD::SETCC &&
10050       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10051        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10052       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10053     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10054     int SSECC = translateX86FSETCC(
10055         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10056
10057     if (SSECC != 8) {
10058       unsigned Opcode = VT == MVT::f32 ? X86ISD::FSETCCss : X86ISD::FSETCCsd;
10059       SDValue Cmp = DAG.getNode(Opcode, DL, VT, CondOp0, CondOp1,
10060                                 DAG.getConstant(SSECC, MVT::i8));
10061       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10062       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10063       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10064     }
10065   }
10066
10067   if (Cond.getOpcode() == ISD::SETCC) {
10068     SDValue NewCond = LowerSETCC(Cond, DAG);
10069     if (NewCond.getNode())
10070       Cond = NewCond;
10071   }
10072
10073   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10074   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10075   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10076   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10077   if (Cond.getOpcode() == X86ISD::SETCC &&
10078       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10079       isZero(Cond.getOperand(1).getOperand(1))) {
10080     SDValue Cmp = Cond.getOperand(1);
10081
10082     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10083
10084     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10085         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10086       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10087
10088       SDValue CmpOp0 = Cmp.getOperand(0);
10089       // Apply further optimizations for special cases
10090       // (select (x != 0), -1, 0) -> neg & sbb
10091       // (select (x == 0), 0, -1) -> neg & sbb
10092       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10093         if (YC->isNullValue() &&
10094             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10095           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10096           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10097                                     DAG.getConstant(0, CmpOp0.getValueType()),
10098                                     CmpOp0);
10099           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10100                                     DAG.getConstant(X86::COND_B, MVT::i8),
10101                                     SDValue(Neg.getNode(), 1));
10102           return Res;
10103         }
10104
10105       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10106                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10107       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10108
10109       SDValue Res =   // Res = 0 or -1.
10110         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10111                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10112
10113       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10114         Res = DAG.getNOT(DL, Res, Res.getValueType());
10115
10116       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10117       if (N2C == 0 || !N2C->isNullValue())
10118         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10119       return Res;
10120     }
10121   }
10122
10123   // Look past (and (setcc_carry (cmp ...)), 1).
10124   if (Cond.getOpcode() == ISD::AND &&
10125       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10126     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10127     if (C && C->getAPIntValue() == 1)
10128       Cond = Cond.getOperand(0);
10129   }
10130
10131   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10132   // setting operand in place of the X86ISD::SETCC.
10133   unsigned CondOpcode = Cond.getOpcode();
10134   if (CondOpcode == X86ISD::SETCC ||
10135       CondOpcode == X86ISD::SETCC_CARRY) {
10136     CC = Cond.getOperand(0);
10137
10138     SDValue Cmp = Cond.getOperand(1);
10139     unsigned Opc = Cmp.getOpcode();
10140     MVT VT = Op.getSimpleValueType();
10141
10142     bool IllegalFPCMov = false;
10143     if (VT.isFloatingPoint() && !VT.isVector() &&
10144         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10145       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10146
10147     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10148         Opc == X86ISD::BT) { // FIXME
10149       Cond = Cmp;
10150       addTest = false;
10151     }
10152   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10153              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10154              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10155               Cond.getOperand(0).getValueType() != MVT::i8)) {
10156     SDValue LHS = Cond.getOperand(0);
10157     SDValue RHS = Cond.getOperand(1);
10158     unsigned X86Opcode;
10159     unsigned X86Cond;
10160     SDVTList VTs;
10161     switch (CondOpcode) {
10162     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10163     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10164     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10165     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10166     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10167     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10168     default: llvm_unreachable("unexpected overflowing operator");
10169     }
10170     if (CondOpcode == ISD::UMULO)
10171       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10172                           MVT::i32);
10173     else
10174       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10175
10176     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10177
10178     if (CondOpcode == ISD::UMULO)
10179       Cond = X86Op.getValue(2);
10180     else
10181       Cond = X86Op.getValue(1);
10182
10183     CC = DAG.getConstant(X86Cond, MVT::i8);
10184     addTest = false;
10185   }
10186
10187   if (addTest) {
10188     // Look pass the truncate if the high bits are known zero.
10189     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10190         Cond = Cond.getOperand(0);
10191
10192     // We know the result of AND is compared against zero. Try to match
10193     // it to BT.
10194     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10195       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10196       if (NewSetCC.getNode()) {
10197         CC = NewSetCC.getOperand(0);
10198         Cond = NewSetCC.getOperand(1);
10199         addTest = false;
10200       }
10201     }
10202   }
10203
10204   if (addTest) {
10205     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10206     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10207   }
10208
10209   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10210   // a <  b ?  0 : -1 -> RES = setcc_carry
10211   // a >= b ? -1 :  0 -> RES = setcc_carry
10212   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10213   if (Cond.getOpcode() == X86ISD::SUB) {
10214     Cond = ConvertCmpIfNecessary(Cond, DAG);
10215     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10216
10217     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10218         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10219       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10220                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10221       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10222         return DAG.getNOT(DL, Res, Res.getValueType());
10223       return Res;
10224     }
10225   }
10226
10227   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10228   // widen the cmov and push the truncate through. This avoids introducing a new
10229   // branch during isel and doesn't add any extensions.
10230   if (Op.getValueType() == MVT::i8 &&
10231       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10232     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10233     if (T1.getValueType() == T2.getValueType() &&
10234         // Blacklist CopyFromReg to avoid partial register stalls.
10235         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10236       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10237       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10238       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10239     }
10240   }
10241
10242   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10243   // condition is true.
10244   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10245   SDValue Ops[] = { Op2, Op1, CC, Cond };
10246   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10247 }
10248
10249 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10250   MVT VT = Op->getSimpleValueType(0);
10251   SDValue In = Op->getOperand(0);
10252   MVT InVT = In.getSimpleValueType();
10253   SDLoc dl(Op);
10254
10255   if (InVT.getVectorElementType().getSizeInBits() >=8 &&
10256       VT.getVectorElementType().getSizeInBits() >= 32)
10257     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10258
10259   if (InVT.getVectorElementType() == MVT::i1) {
10260     unsigned int NumElts = InVT.getVectorNumElements();
10261     assert ((NumElts == 8 || NumElts == 16) &&
10262       "Unsupported SIGN_EXTEND operation");
10263     if (VT.getVectorElementType().getSizeInBits() >= 32) {
10264       Constant *C =
10265        ConstantInt::get(*DAG.getContext(),
10266                         (NumElts == 8)? APInt(64, ~0ULL): APInt(32, ~0U));
10267       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10268       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10269       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10270       SDValue Ld = DAG.getLoad(VT.getScalarType(), dl, DAG.getEntryNode(), CP,
10271                              MachinePointerInfo::getConstantPool(),
10272                              false, false, false, Alignment);
10273       return DAG.getNode(X86ISD::VBROADCASTM, dl, VT, In, Ld);
10274     }
10275   }
10276   return SDValue();
10277 }
10278
10279 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10280                                 SelectionDAG &DAG) {
10281   MVT VT = Op->getSimpleValueType(0);
10282   SDValue In = Op->getOperand(0);
10283   MVT InVT = In.getSimpleValueType();
10284   SDLoc dl(Op);
10285
10286   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10287     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10288
10289   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10290       (VT != MVT::v8i32 || InVT != MVT::v8i16))
10291     return SDValue();
10292
10293   if (Subtarget->hasInt256())
10294     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10295
10296   // Optimize vectors in AVX mode
10297   // Sign extend  v8i16 to v8i32 and
10298   //              v4i32 to v4i64
10299   //
10300   // Divide input vector into two parts
10301   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10302   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10303   // concat the vectors to original VT
10304
10305   unsigned NumElems = InVT.getVectorNumElements();
10306   SDValue Undef = DAG.getUNDEF(InVT);
10307
10308   SmallVector<int,8> ShufMask1(NumElems, -1);
10309   for (unsigned i = 0; i != NumElems/2; ++i)
10310     ShufMask1[i] = i;
10311
10312   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10313
10314   SmallVector<int,8> ShufMask2(NumElems, -1);
10315   for (unsigned i = 0; i != NumElems/2; ++i)
10316     ShufMask2[i] = i + NumElems/2;
10317
10318   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10319
10320   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10321                                 VT.getVectorNumElements()/2);
10322
10323   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10324   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10325
10326   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10327 }
10328
10329 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10330 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10331 // from the AND / OR.
10332 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10333   Opc = Op.getOpcode();
10334   if (Opc != ISD::OR && Opc != ISD::AND)
10335     return false;
10336   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10337           Op.getOperand(0).hasOneUse() &&
10338           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10339           Op.getOperand(1).hasOneUse());
10340 }
10341
10342 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10343 // 1 and that the SETCC node has a single use.
10344 static bool isXor1OfSetCC(SDValue Op) {
10345   if (Op.getOpcode() != ISD::XOR)
10346     return false;
10347   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10348   if (N1C && N1C->getAPIntValue() == 1) {
10349     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10350       Op.getOperand(0).hasOneUse();
10351   }
10352   return false;
10353 }
10354
10355 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10356   bool addTest = true;
10357   SDValue Chain = Op.getOperand(0);
10358   SDValue Cond  = Op.getOperand(1);
10359   SDValue Dest  = Op.getOperand(2);
10360   SDLoc dl(Op);
10361   SDValue CC;
10362   bool Inverted = false;
10363
10364   if (Cond.getOpcode() == ISD::SETCC) {
10365     // Check for setcc([su]{add,sub,mul}o == 0).
10366     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10367         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10368         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10369         Cond.getOperand(0).getResNo() == 1 &&
10370         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10371          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10372          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10373          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10374          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10375          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10376       Inverted = true;
10377       Cond = Cond.getOperand(0);
10378     } else {
10379       SDValue NewCond = LowerSETCC(Cond, DAG);
10380       if (NewCond.getNode())
10381         Cond = NewCond;
10382     }
10383   }
10384 #if 0
10385   // FIXME: LowerXALUO doesn't handle these!!
10386   else if (Cond.getOpcode() == X86ISD::ADD  ||
10387            Cond.getOpcode() == X86ISD::SUB  ||
10388            Cond.getOpcode() == X86ISD::SMUL ||
10389            Cond.getOpcode() == X86ISD::UMUL)
10390     Cond = LowerXALUO(Cond, DAG);
10391 #endif
10392
10393   // Look pass (and (setcc_carry (cmp ...)), 1).
10394   if (Cond.getOpcode() == ISD::AND &&
10395       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10396     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10397     if (C && C->getAPIntValue() == 1)
10398       Cond = Cond.getOperand(0);
10399   }
10400
10401   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10402   // setting operand in place of the X86ISD::SETCC.
10403   unsigned CondOpcode = Cond.getOpcode();
10404   if (CondOpcode == X86ISD::SETCC ||
10405       CondOpcode == X86ISD::SETCC_CARRY) {
10406     CC = Cond.getOperand(0);
10407
10408     SDValue Cmp = Cond.getOperand(1);
10409     unsigned Opc = Cmp.getOpcode();
10410     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10411     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10412       Cond = Cmp;
10413       addTest = false;
10414     } else {
10415       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10416       default: break;
10417       case X86::COND_O:
10418       case X86::COND_B:
10419         // These can only come from an arithmetic instruction with overflow,
10420         // e.g. SADDO, UADDO.
10421         Cond = Cond.getNode()->getOperand(1);
10422         addTest = false;
10423         break;
10424       }
10425     }
10426   }
10427   CondOpcode = Cond.getOpcode();
10428   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10429       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10430       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10431        Cond.getOperand(0).getValueType() != MVT::i8)) {
10432     SDValue LHS = Cond.getOperand(0);
10433     SDValue RHS = Cond.getOperand(1);
10434     unsigned X86Opcode;
10435     unsigned X86Cond;
10436     SDVTList VTs;
10437     switch (CondOpcode) {
10438     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10439     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10440     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10441     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10442     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10443     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10444     default: llvm_unreachable("unexpected overflowing operator");
10445     }
10446     if (Inverted)
10447       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10448     if (CondOpcode == ISD::UMULO)
10449       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10450                           MVT::i32);
10451     else
10452       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10453
10454     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10455
10456     if (CondOpcode == ISD::UMULO)
10457       Cond = X86Op.getValue(2);
10458     else
10459       Cond = X86Op.getValue(1);
10460
10461     CC = DAG.getConstant(X86Cond, MVT::i8);
10462     addTest = false;
10463   } else {
10464     unsigned CondOpc;
10465     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10466       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10467       if (CondOpc == ISD::OR) {
10468         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10469         // two branches instead of an explicit OR instruction with a
10470         // separate test.
10471         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10472             isX86LogicalCmp(Cmp)) {
10473           CC = Cond.getOperand(0).getOperand(0);
10474           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10475                               Chain, Dest, CC, Cmp);
10476           CC = Cond.getOperand(1).getOperand(0);
10477           Cond = Cmp;
10478           addTest = false;
10479         }
10480       } else { // ISD::AND
10481         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10482         // two branches instead of an explicit AND instruction with a
10483         // separate test. However, we only do this if this block doesn't
10484         // have a fall-through edge, because this requires an explicit
10485         // jmp when the condition is false.
10486         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10487             isX86LogicalCmp(Cmp) &&
10488             Op.getNode()->hasOneUse()) {
10489           X86::CondCode CCode =
10490             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10491           CCode = X86::GetOppositeBranchCondition(CCode);
10492           CC = DAG.getConstant(CCode, MVT::i8);
10493           SDNode *User = *Op.getNode()->use_begin();
10494           // Look for an unconditional branch following this conditional branch.
10495           // We need this because we need to reverse the successors in order
10496           // to implement FCMP_OEQ.
10497           if (User->getOpcode() == ISD::BR) {
10498             SDValue FalseBB = User->getOperand(1);
10499             SDNode *NewBR =
10500               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10501             assert(NewBR == User);
10502             (void)NewBR;
10503             Dest = FalseBB;
10504
10505             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10506                                 Chain, Dest, CC, Cmp);
10507             X86::CondCode CCode =
10508               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10509             CCode = X86::GetOppositeBranchCondition(CCode);
10510             CC = DAG.getConstant(CCode, MVT::i8);
10511             Cond = Cmp;
10512             addTest = false;
10513           }
10514         }
10515       }
10516     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10517       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10518       // It should be transformed during dag combiner except when the condition
10519       // is set by a arithmetics with overflow node.
10520       X86::CondCode CCode =
10521         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10522       CCode = X86::GetOppositeBranchCondition(CCode);
10523       CC = DAG.getConstant(CCode, MVT::i8);
10524       Cond = Cond.getOperand(0).getOperand(1);
10525       addTest = false;
10526     } else if (Cond.getOpcode() == ISD::SETCC &&
10527                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10528       // For FCMP_OEQ, we can emit
10529       // two branches instead of an explicit AND instruction with a
10530       // separate test. However, we only do this if this block doesn't
10531       // have a fall-through edge, because this requires an explicit
10532       // jmp when the condition is false.
10533       if (Op.getNode()->hasOneUse()) {
10534         SDNode *User = *Op.getNode()->use_begin();
10535         // Look for an unconditional branch following this conditional branch.
10536         // We need this because we need to reverse the successors in order
10537         // to implement FCMP_OEQ.
10538         if (User->getOpcode() == ISD::BR) {
10539           SDValue FalseBB = User->getOperand(1);
10540           SDNode *NewBR =
10541             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10542           assert(NewBR == User);
10543           (void)NewBR;
10544           Dest = FalseBB;
10545
10546           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10547                                     Cond.getOperand(0), Cond.getOperand(1));
10548           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10549           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10550           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10551                               Chain, Dest, CC, Cmp);
10552           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10553           Cond = Cmp;
10554           addTest = false;
10555         }
10556       }
10557     } else if (Cond.getOpcode() == ISD::SETCC &&
10558                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10559       // For FCMP_UNE, we can emit
10560       // two branches instead of an explicit AND instruction with a
10561       // separate test. However, we only do this if this block doesn't
10562       // have a fall-through edge, because this requires an explicit
10563       // jmp when the condition is false.
10564       if (Op.getNode()->hasOneUse()) {
10565         SDNode *User = *Op.getNode()->use_begin();
10566         // Look for an unconditional branch following this conditional branch.
10567         // We need this because we need to reverse the successors in order
10568         // to implement FCMP_UNE.
10569         if (User->getOpcode() == ISD::BR) {
10570           SDValue FalseBB = User->getOperand(1);
10571           SDNode *NewBR =
10572             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10573           assert(NewBR == User);
10574           (void)NewBR;
10575
10576           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10577                                     Cond.getOperand(0), Cond.getOperand(1));
10578           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10579           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10580           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10581                               Chain, Dest, CC, Cmp);
10582           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10583           Cond = Cmp;
10584           addTest = false;
10585           Dest = FalseBB;
10586         }
10587       }
10588     }
10589   }
10590
10591   if (addTest) {
10592     // Look pass the truncate if the high bits are known zero.
10593     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10594         Cond = Cond.getOperand(0);
10595
10596     // We know the result of AND is compared against zero. Try to match
10597     // it to BT.
10598     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10599       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10600       if (NewSetCC.getNode()) {
10601         CC = NewSetCC.getOperand(0);
10602         Cond = NewSetCC.getOperand(1);
10603         addTest = false;
10604       }
10605     }
10606   }
10607
10608   if (addTest) {
10609     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10610     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10611   }
10612   Cond = ConvertCmpIfNecessary(Cond, DAG);
10613   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10614                      Chain, Dest, CC, Cond);
10615 }
10616
10617 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10618 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10619 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10620 // that the guard pages used by the OS virtual memory manager are allocated in
10621 // correct sequence.
10622 SDValue
10623 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10624                                            SelectionDAG &DAG) const {
10625   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10626           getTargetMachine().Options.EnableSegmentedStacks) &&
10627          "This should be used only on Windows targets or when segmented stacks "
10628          "are being used");
10629   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10630   SDLoc dl(Op);
10631
10632   // Get the inputs.
10633   SDValue Chain = Op.getOperand(0);
10634   SDValue Size  = Op.getOperand(1);
10635   // FIXME: Ensure alignment here
10636
10637   bool Is64Bit = Subtarget->is64Bit();
10638   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10639
10640   if (getTargetMachine().Options.EnableSegmentedStacks) {
10641     MachineFunction &MF = DAG.getMachineFunction();
10642     MachineRegisterInfo &MRI = MF.getRegInfo();
10643
10644     if (Is64Bit) {
10645       // The 64 bit implementation of segmented stacks needs to clobber both r10
10646       // r11. This makes it impossible to use it along with nested parameters.
10647       const Function *F = MF.getFunction();
10648
10649       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10650            I != E; ++I)
10651         if (I->hasNestAttr())
10652           report_fatal_error("Cannot use segmented stacks with functions that "
10653                              "have nested arguments.");
10654     }
10655
10656     const TargetRegisterClass *AddrRegClass =
10657       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10658     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10659     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10660     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10661                                 DAG.getRegister(Vreg, SPTy));
10662     SDValue Ops1[2] = { Value, Chain };
10663     return DAG.getMergeValues(Ops1, 2, dl);
10664   } else {
10665     SDValue Flag;
10666     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10667
10668     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10669     Flag = Chain.getValue(1);
10670     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10671
10672     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10673     Flag = Chain.getValue(1);
10674
10675     const X86RegisterInfo *RegInfo =
10676       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10677     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10678                                SPTy).getValue(1);
10679
10680     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10681     return DAG.getMergeValues(Ops1, 2, dl);
10682   }
10683 }
10684
10685 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10686   MachineFunction &MF = DAG.getMachineFunction();
10687   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10688
10689   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10690   SDLoc DL(Op);
10691
10692   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10693     // vastart just stores the address of the VarArgsFrameIndex slot into the
10694     // memory location argument.
10695     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10696                                    getPointerTy());
10697     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10698                         MachinePointerInfo(SV), false, false, 0);
10699   }
10700
10701   // __va_list_tag:
10702   //   gp_offset         (0 - 6 * 8)
10703   //   fp_offset         (48 - 48 + 8 * 16)
10704   //   overflow_arg_area (point to parameters coming in memory).
10705   //   reg_save_area
10706   SmallVector<SDValue, 8> MemOps;
10707   SDValue FIN = Op.getOperand(1);
10708   // Store gp_offset
10709   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10710                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10711                                                MVT::i32),
10712                                FIN, MachinePointerInfo(SV), false, false, 0);
10713   MemOps.push_back(Store);
10714
10715   // Store fp_offset
10716   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10717                     FIN, DAG.getIntPtrConstant(4));
10718   Store = DAG.getStore(Op.getOperand(0), DL,
10719                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10720                                        MVT::i32),
10721                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10722   MemOps.push_back(Store);
10723
10724   // Store ptr to overflow_arg_area
10725   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10726                     FIN, DAG.getIntPtrConstant(4));
10727   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10728                                     getPointerTy());
10729   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10730                        MachinePointerInfo(SV, 8),
10731                        false, false, 0);
10732   MemOps.push_back(Store);
10733
10734   // Store ptr to reg_save_area.
10735   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10736                     FIN, DAG.getIntPtrConstant(8));
10737   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10738                                     getPointerTy());
10739   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10740                        MachinePointerInfo(SV, 16), false, false, 0);
10741   MemOps.push_back(Store);
10742   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10743                      &MemOps[0], MemOps.size());
10744 }
10745
10746 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10747   assert(Subtarget->is64Bit() &&
10748          "LowerVAARG only handles 64-bit va_arg!");
10749   assert((Subtarget->isTargetLinux() ||
10750           Subtarget->isTargetDarwin()) &&
10751           "Unhandled target in LowerVAARG");
10752   assert(Op.getNode()->getNumOperands() == 4);
10753   SDValue Chain = Op.getOperand(0);
10754   SDValue SrcPtr = Op.getOperand(1);
10755   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10756   unsigned Align = Op.getConstantOperandVal(3);
10757   SDLoc dl(Op);
10758
10759   EVT ArgVT = Op.getNode()->getValueType(0);
10760   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10761   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10762   uint8_t ArgMode;
10763
10764   // Decide which area this value should be read from.
10765   // TODO: Implement the AMD64 ABI in its entirety. This simple
10766   // selection mechanism works only for the basic types.
10767   if (ArgVT == MVT::f80) {
10768     llvm_unreachable("va_arg for f80 not yet implemented");
10769   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10770     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10771   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10772     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10773   } else {
10774     llvm_unreachable("Unhandled argument type in LowerVAARG");
10775   }
10776
10777   if (ArgMode == 2) {
10778     // Sanity Check: Make sure using fp_offset makes sense.
10779     assert(!getTargetMachine().Options.UseSoftFloat &&
10780            !(DAG.getMachineFunction()
10781                 .getFunction()->getAttributes()
10782                 .hasAttribute(AttributeSet::FunctionIndex,
10783                               Attribute::NoImplicitFloat)) &&
10784            Subtarget->hasSSE1());
10785   }
10786
10787   // Insert VAARG_64 node into the DAG
10788   // VAARG_64 returns two values: Variable Argument Address, Chain
10789   SmallVector<SDValue, 11> InstOps;
10790   InstOps.push_back(Chain);
10791   InstOps.push_back(SrcPtr);
10792   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10793   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10794   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10795   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10796   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10797                                           VTs, &InstOps[0], InstOps.size(),
10798                                           MVT::i64,
10799                                           MachinePointerInfo(SV),
10800                                           /*Align=*/0,
10801                                           /*Volatile=*/false,
10802                                           /*ReadMem=*/true,
10803                                           /*WriteMem=*/true);
10804   Chain = VAARG.getValue(1);
10805
10806   // Load the next argument and return it
10807   return DAG.getLoad(ArgVT, dl,
10808                      Chain,
10809                      VAARG,
10810                      MachinePointerInfo(),
10811                      false, false, false, 0);
10812 }
10813
10814 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10815                            SelectionDAG &DAG) {
10816   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10817   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10818   SDValue Chain = Op.getOperand(0);
10819   SDValue DstPtr = Op.getOperand(1);
10820   SDValue SrcPtr = Op.getOperand(2);
10821   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10822   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10823   SDLoc DL(Op);
10824
10825   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10826                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10827                        false,
10828                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10829 }
10830
10831 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10832 // may or may not be a constant. Takes immediate version of shift as input.
10833 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10834                                    SDValue SrcOp, SDValue ShAmt,
10835                                    SelectionDAG &DAG) {
10836   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10837
10838   if (isa<ConstantSDNode>(ShAmt)) {
10839     // Constant may be a TargetConstant. Use a regular constant.
10840     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10841     switch (Opc) {
10842       default: llvm_unreachable("Unknown target vector shift node");
10843       case X86ISD::VSHLI:
10844       case X86ISD::VSRLI:
10845       case X86ISD::VSRAI:
10846         return DAG.getNode(Opc, dl, VT, SrcOp,
10847                            DAG.getConstant(ShiftAmt, MVT::i32));
10848     }
10849   }
10850
10851   // Change opcode to non-immediate version
10852   switch (Opc) {
10853     default: llvm_unreachable("Unknown target vector shift node");
10854     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10855     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10856     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10857   }
10858
10859   // Need to build a vector containing shift amount
10860   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10861   SDValue ShOps[4];
10862   ShOps[0] = ShAmt;
10863   ShOps[1] = DAG.getConstant(0, MVT::i32);
10864   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10865   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10866
10867   // The return type has to be a 128-bit type with the same element
10868   // type as the input type.
10869   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10870   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10871
10872   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10873   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10874 }
10875
10876 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10877   SDLoc dl(Op);
10878   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10879   switch (IntNo) {
10880   default: return SDValue();    // Don't custom lower most intrinsics.
10881   // Comparison intrinsics.
10882   case Intrinsic::x86_sse_comieq_ss:
10883   case Intrinsic::x86_sse_comilt_ss:
10884   case Intrinsic::x86_sse_comile_ss:
10885   case Intrinsic::x86_sse_comigt_ss:
10886   case Intrinsic::x86_sse_comige_ss:
10887   case Intrinsic::x86_sse_comineq_ss:
10888   case Intrinsic::x86_sse_ucomieq_ss:
10889   case Intrinsic::x86_sse_ucomilt_ss:
10890   case Intrinsic::x86_sse_ucomile_ss:
10891   case Intrinsic::x86_sse_ucomigt_ss:
10892   case Intrinsic::x86_sse_ucomige_ss:
10893   case Intrinsic::x86_sse_ucomineq_ss:
10894   case Intrinsic::x86_sse2_comieq_sd:
10895   case Intrinsic::x86_sse2_comilt_sd:
10896   case Intrinsic::x86_sse2_comile_sd:
10897   case Intrinsic::x86_sse2_comigt_sd:
10898   case Intrinsic::x86_sse2_comige_sd:
10899   case Intrinsic::x86_sse2_comineq_sd:
10900   case Intrinsic::x86_sse2_ucomieq_sd:
10901   case Intrinsic::x86_sse2_ucomilt_sd:
10902   case Intrinsic::x86_sse2_ucomile_sd:
10903   case Intrinsic::x86_sse2_ucomigt_sd:
10904   case Intrinsic::x86_sse2_ucomige_sd:
10905   case Intrinsic::x86_sse2_ucomineq_sd: {
10906     unsigned Opc;
10907     ISD::CondCode CC;
10908     switch (IntNo) {
10909     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10910     case Intrinsic::x86_sse_comieq_ss:
10911     case Intrinsic::x86_sse2_comieq_sd:
10912       Opc = X86ISD::COMI;
10913       CC = ISD::SETEQ;
10914       break;
10915     case Intrinsic::x86_sse_comilt_ss:
10916     case Intrinsic::x86_sse2_comilt_sd:
10917       Opc = X86ISD::COMI;
10918       CC = ISD::SETLT;
10919       break;
10920     case Intrinsic::x86_sse_comile_ss:
10921     case Intrinsic::x86_sse2_comile_sd:
10922       Opc = X86ISD::COMI;
10923       CC = ISD::SETLE;
10924       break;
10925     case Intrinsic::x86_sse_comigt_ss:
10926     case Intrinsic::x86_sse2_comigt_sd:
10927       Opc = X86ISD::COMI;
10928       CC = ISD::SETGT;
10929       break;
10930     case Intrinsic::x86_sse_comige_ss:
10931     case Intrinsic::x86_sse2_comige_sd:
10932       Opc = X86ISD::COMI;
10933       CC = ISD::SETGE;
10934       break;
10935     case Intrinsic::x86_sse_comineq_ss:
10936     case Intrinsic::x86_sse2_comineq_sd:
10937       Opc = X86ISD::COMI;
10938       CC = ISD::SETNE;
10939       break;
10940     case Intrinsic::x86_sse_ucomieq_ss:
10941     case Intrinsic::x86_sse2_ucomieq_sd:
10942       Opc = X86ISD::UCOMI;
10943       CC = ISD::SETEQ;
10944       break;
10945     case Intrinsic::x86_sse_ucomilt_ss:
10946     case Intrinsic::x86_sse2_ucomilt_sd:
10947       Opc = X86ISD::UCOMI;
10948       CC = ISD::SETLT;
10949       break;
10950     case Intrinsic::x86_sse_ucomile_ss:
10951     case Intrinsic::x86_sse2_ucomile_sd:
10952       Opc = X86ISD::UCOMI;
10953       CC = ISD::SETLE;
10954       break;
10955     case Intrinsic::x86_sse_ucomigt_ss:
10956     case Intrinsic::x86_sse2_ucomigt_sd:
10957       Opc = X86ISD::UCOMI;
10958       CC = ISD::SETGT;
10959       break;
10960     case Intrinsic::x86_sse_ucomige_ss:
10961     case Intrinsic::x86_sse2_ucomige_sd:
10962       Opc = X86ISD::UCOMI;
10963       CC = ISD::SETGE;
10964       break;
10965     case Intrinsic::x86_sse_ucomineq_ss:
10966     case Intrinsic::x86_sse2_ucomineq_sd:
10967       Opc = X86ISD::UCOMI;
10968       CC = ISD::SETNE;
10969       break;
10970     }
10971
10972     SDValue LHS = Op.getOperand(1);
10973     SDValue RHS = Op.getOperand(2);
10974     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10975     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10976     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10977     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10978                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10979     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10980   }
10981
10982   // Arithmetic intrinsics.
10983   case Intrinsic::x86_sse2_pmulu_dq:
10984   case Intrinsic::x86_avx2_pmulu_dq:
10985     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10986                        Op.getOperand(1), Op.getOperand(2));
10987
10988   // SSE2/AVX2 sub with unsigned saturation intrinsics
10989   case Intrinsic::x86_sse2_psubus_b:
10990   case Intrinsic::x86_sse2_psubus_w:
10991   case Intrinsic::x86_avx2_psubus_b:
10992   case Intrinsic::x86_avx2_psubus_w:
10993     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10994                        Op.getOperand(1), Op.getOperand(2));
10995
10996   // SSE3/AVX horizontal add/sub intrinsics
10997   case Intrinsic::x86_sse3_hadd_ps:
10998   case Intrinsic::x86_sse3_hadd_pd:
10999   case Intrinsic::x86_avx_hadd_ps_256:
11000   case Intrinsic::x86_avx_hadd_pd_256:
11001   case Intrinsic::x86_sse3_hsub_ps:
11002   case Intrinsic::x86_sse3_hsub_pd:
11003   case Intrinsic::x86_avx_hsub_ps_256:
11004   case Intrinsic::x86_avx_hsub_pd_256:
11005   case Intrinsic::x86_ssse3_phadd_w_128:
11006   case Intrinsic::x86_ssse3_phadd_d_128:
11007   case Intrinsic::x86_avx2_phadd_w:
11008   case Intrinsic::x86_avx2_phadd_d:
11009   case Intrinsic::x86_ssse3_phsub_w_128:
11010   case Intrinsic::x86_ssse3_phsub_d_128:
11011   case Intrinsic::x86_avx2_phsub_w:
11012   case Intrinsic::x86_avx2_phsub_d: {
11013     unsigned Opcode;
11014     switch (IntNo) {
11015     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11016     case Intrinsic::x86_sse3_hadd_ps:
11017     case Intrinsic::x86_sse3_hadd_pd:
11018     case Intrinsic::x86_avx_hadd_ps_256:
11019     case Intrinsic::x86_avx_hadd_pd_256:
11020       Opcode = X86ISD::FHADD;
11021       break;
11022     case Intrinsic::x86_sse3_hsub_ps:
11023     case Intrinsic::x86_sse3_hsub_pd:
11024     case Intrinsic::x86_avx_hsub_ps_256:
11025     case Intrinsic::x86_avx_hsub_pd_256:
11026       Opcode = X86ISD::FHSUB;
11027       break;
11028     case Intrinsic::x86_ssse3_phadd_w_128:
11029     case Intrinsic::x86_ssse3_phadd_d_128:
11030     case Intrinsic::x86_avx2_phadd_w:
11031     case Intrinsic::x86_avx2_phadd_d:
11032       Opcode = X86ISD::HADD;
11033       break;
11034     case Intrinsic::x86_ssse3_phsub_w_128:
11035     case Intrinsic::x86_ssse3_phsub_d_128:
11036     case Intrinsic::x86_avx2_phsub_w:
11037     case Intrinsic::x86_avx2_phsub_d:
11038       Opcode = X86ISD::HSUB;
11039       break;
11040     }
11041     return DAG.getNode(Opcode, dl, Op.getValueType(),
11042                        Op.getOperand(1), Op.getOperand(2));
11043   }
11044
11045   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11046   case Intrinsic::x86_sse2_pmaxu_b:
11047   case Intrinsic::x86_sse41_pmaxuw:
11048   case Intrinsic::x86_sse41_pmaxud:
11049   case Intrinsic::x86_avx2_pmaxu_b:
11050   case Intrinsic::x86_avx2_pmaxu_w:
11051   case Intrinsic::x86_avx2_pmaxu_d:
11052   case Intrinsic::x86_sse2_pminu_b:
11053   case Intrinsic::x86_sse41_pminuw:
11054   case Intrinsic::x86_sse41_pminud:
11055   case Intrinsic::x86_avx2_pminu_b:
11056   case Intrinsic::x86_avx2_pminu_w:
11057   case Intrinsic::x86_avx2_pminu_d:
11058   case Intrinsic::x86_sse41_pmaxsb:
11059   case Intrinsic::x86_sse2_pmaxs_w:
11060   case Intrinsic::x86_sse41_pmaxsd:
11061   case Intrinsic::x86_avx2_pmaxs_b:
11062   case Intrinsic::x86_avx2_pmaxs_w:
11063   case Intrinsic::x86_avx2_pmaxs_d:
11064   case Intrinsic::x86_sse41_pminsb:
11065   case Intrinsic::x86_sse2_pmins_w:
11066   case Intrinsic::x86_sse41_pminsd:
11067   case Intrinsic::x86_avx2_pmins_b:
11068   case Intrinsic::x86_avx2_pmins_w:
11069   case Intrinsic::x86_avx2_pmins_d: {
11070     unsigned Opcode;
11071     switch (IntNo) {
11072     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11073     case Intrinsic::x86_sse2_pmaxu_b:
11074     case Intrinsic::x86_sse41_pmaxuw:
11075     case Intrinsic::x86_sse41_pmaxud:
11076     case Intrinsic::x86_avx2_pmaxu_b:
11077     case Intrinsic::x86_avx2_pmaxu_w:
11078     case Intrinsic::x86_avx2_pmaxu_d:
11079       Opcode = X86ISD::UMAX;
11080       break;
11081     case Intrinsic::x86_sse2_pminu_b:
11082     case Intrinsic::x86_sse41_pminuw:
11083     case Intrinsic::x86_sse41_pminud:
11084     case Intrinsic::x86_avx2_pminu_b:
11085     case Intrinsic::x86_avx2_pminu_w:
11086     case Intrinsic::x86_avx2_pminu_d:
11087       Opcode = X86ISD::UMIN;
11088       break;
11089     case Intrinsic::x86_sse41_pmaxsb:
11090     case Intrinsic::x86_sse2_pmaxs_w:
11091     case Intrinsic::x86_sse41_pmaxsd:
11092     case Intrinsic::x86_avx2_pmaxs_b:
11093     case Intrinsic::x86_avx2_pmaxs_w:
11094     case Intrinsic::x86_avx2_pmaxs_d:
11095       Opcode = X86ISD::SMAX;
11096       break;
11097     case Intrinsic::x86_sse41_pminsb:
11098     case Intrinsic::x86_sse2_pmins_w:
11099     case Intrinsic::x86_sse41_pminsd:
11100     case Intrinsic::x86_avx2_pmins_b:
11101     case Intrinsic::x86_avx2_pmins_w:
11102     case Intrinsic::x86_avx2_pmins_d:
11103       Opcode = X86ISD::SMIN;
11104       break;
11105     }
11106     return DAG.getNode(Opcode, dl, Op.getValueType(),
11107                        Op.getOperand(1), Op.getOperand(2));
11108   }
11109
11110   // SSE/SSE2/AVX floating point max/min intrinsics.
11111   case Intrinsic::x86_sse_max_ps:
11112   case Intrinsic::x86_sse2_max_pd:
11113   case Intrinsic::x86_avx_max_ps_256:
11114   case Intrinsic::x86_avx_max_pd_256:
11115   case Intrinsic::x86_sse_min_ps:
11116   case Intrinsic::x86_sse2_min_pd:
11117   case Intrinsic::x86_avx_min_ps_256:
11118   case Intrinsic::x86_avx_min_pd_256: {
11119     unsigned Opcode;
11120     switch (IntNo) {
11121     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11122     case Intrinsic::x86_sse_max_ps:
11123     case Intrinsic::x86_sse2_max_pd:
11124     case Intrinsic::x86_avx_max_ps_256:
11125     case Intrinsic::x86_avx_max_pd_256:
11126       Opcode = X86ISD::FMAX;
11127       break;
11128     case Intrinsic::x86_sse_min_ps:
11129     case Intrinsic::x86_sse2_min_pd:
11130     case Intrinsic::x86_avx_min_ps_256:
11131     case Intrinsic::x86_avx_min_pd_256:
11132       Opcode = X86ISD::FMIN;
11133       break;
11134     }
11135     return DAG.getNode(Opcode, dl, Op.getValueType(),
11136                        Op.getOperand(1), Op.getOperand(2));
11137   }
11138
11139   // AVX2 variable shift intrinsics
11140   case Intrinsic::x86_avx2_psllv_d:
11141   case Intrinsic::x86_avx2_psllv_q:
11142   case Intrinsic::x86_avx2_psllv_d_256:
11143   case Intrinsic::x86_avx2_psllv_q_256:
11144   case Intrinsic::x86_avx2_psrlv_d:
11145   case Intrinsic::x86_avx2_psrlv_q:
11146   case Intrinsic::x86_avx2_psrlv_d_256:
11147   case Intrinsic::x86_avx2_psrlv_q_256:
11148   case Intrinsic::x86_avx2_psrav_d:
11149   case Intrinsic::x86_avx2_psrav_d_256: {
11150     unsigned Opcode;
11151     switch (IntNo) {
11152     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11153     case Intrinsic::x86_avx2_psllv_d:
11154     case Intrinsic::x86_avx2_psllv_q:
11155     case Intrinsic::x86_avx2_psllv_d_256:
11156     case Intrinsic::x86_avx2_psllv_q_256:
11157       Opcode = ISD::SHL;
11158       break;
11159     case Intrinsic::x86_avx2_psrlv_d:
11160     case Intrinsic::x86_avx2_psrlv_q:
11161     case Intrinsic::x86_avx2_psrlv_d_256:
11162     case Intrinsic::x86_avx2_psrlv_q_256:
11163       Opcode = ISD::SRL;
11164       break;
11165     case Intrinsic::x86_avx2_psrav_d:
11166     case Intrinsic::x86_avx2_psrav_d_256:
11167       Opcode = ISD::SRA;
11168       break;
11169     }
11170     return DAG.getNode(Opcode, dl, Op.getValueType(),
11171                        Op.getOperand(1), Op.getOperand(2));
11172   }
11173
11174   case Intrinsic::x86_ssse3_pshuf_b_128:
11175   case Intrinsic::x86_avx2_pshuf_b:
11176     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11177                        Op.getOperand(1), Op.getOperand(2));
11178
11179   case Intrinsic::x86_ssse3_psign_b_128:
11180   case Intrinsic::x86_ssse3_psign_w_128:
11181   case Intrinsic::x86_ssse3_psign_d_128:
11182   case Intrinsic::x86_avx2_psign_b:
11183   case Intrinsic::x86_avx2_psign_w:
11184   case Intrinsic::x86_avx2_psign_d:
11185     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11186                        Op.getOperand(1), Op.getOperand(2));
11187
11188   case Intrinsic::x86_sse41_insertps:
11189     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11190                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11191
11192   case Intrinsic::x86_avx_vperm2f128_ps_256:
11193   case Intrinsic::x86_avx_vperm2f128_pd_256:
11194   case Intrinsic::x86_avx_vperm2f128_si_256:
11195   case Intrinsic::x86_avx2_vperm2i128:
11196     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11197                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11198
11199   case Intrinsic::x86_avx2_permd:
11200   case Intrinsic::x86_avx2_permps:
11201     // Operands intentionally swapped. Mask is last operand to intrinsic,
11202     // but second operand for node/intruction.
11203     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11204                        Op.getOperand(2), Op.getOperand(1));
11205
11206   case Intrinsic::x86_sse_sqrt_ps:
11207   case Intrinsic::x86_sse2_sqrt_pd:
11208   case Intrinsic::x86_avx_sqrt_ps_256:
11209   case Intrinsic::x86_avx_sqrt_pd_256:
11210     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11211
11212   // ptest and testp intrinsics. The intrinsic these come from are designed to
11213   // return an integer value, not just an instruction so lower it to the ptest
11214   // or testp pattern and a setcc for the result.
11215   case Intrinsic::x86_sse41_ptestz:
11216   case Intrinsic::x86_sse41_ptestc:
11217   case Intrinsic::x86_sse41_ptestnzc:
11218   case Intrinsic::x86_avx_ptestz_256:
11219   case Intrinsic::x86_avx_ptestc_256:
11220   case Intrinsic::x86_avx_ptestnzc_256:
11221   case Intrinsic::x86_avx_vtestz_ps:
11222   case Intrinsic::x86_avx_vtestc_ps:
11223   case Intrinsic::x86_avx_vtestnzc_ps:
11224   case Intrinsic::x86_avx_vtestz_pd:
11225   case Intrinsic::x86_avx_vtestc_pd:
11226   case Intrinsic::x86_avx_vtestnzc_pd:
11227   case Intrinsic::x86_avx_vtestz_ps_256:
11228   case Intrinsic::x86_avx_vtestc_ps_256:
11229   case Intrinsic::x86_avx_vtestnzc_ps_256:
11230   case Intrinsic::x86_avx_vtestz_pd_256:
11231   case Intrinsic::x86_avx_vtestc_pd_256:
11232   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11233     bool IsTestPacked = false;
11234     unsigned X86CC;
11235     switch (IntNo) {
11236     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11237     case Intrinsic::x86_avx_vtestz_ps:
11238     case Intrinsic::x86_avx_vtestz_pd:
11239     case Intrinsic::x86_avx_vtestz_ps_256:
11240     case Intrinsic::x86_avx_vtestz_pd_256:
11241       IsTestPacked = true; // Fallthrough
11242     case Intrinsic::x86_sse41_ptestz:
11243     case Intrinsic::x86_avx_ptestz_256:
11244       // ZF = 1
11245       X86CC = X86::COND_E;
11246       break;
11247     case Intrinsic::x86_avx_vtestc_ps:
11248     case Intrinsic::x86_avx_vtestc_pd:
11249     case Intrinsic::x86_avx_vtestc_ps_256:
11250     case Intrinsic::x86_avx_vtestc_pd_256:
11251       IsTestPacked = true; // Fallthrough
11252     case Intrinsic::x86_sse41_ptestc:
11253     case Intrinsic::x86_avx_ptestc_256:
11254       // CF = 1
11255       X86CC = X86::COND_B;
11256       break;
11257     case Intrinsic::x86_avx_vtestnzc_ps:
11258     case Intrinsic::x86_avx_vtestnzc_pd:
11259     case Intrinsic::x86_avx_vtestnzc_ps_256:
11260     case Intrinsic::x86_avx_vtestnzc_pd_256:
11261       IsTestPacked = true; // Fallthrough
11262     case Intrinsic::x86_sse41_ptestnzc:
11263     case Intrinsic::x86_avx_ptestnzc_256:
11264       // ZF and CF = 0
11265       X86CC = X86::COND_A;
11266       break;
11267     }
11268
11269     SDValue LHS = Op.getOperand(1);
11270     SDValue RHS = Op.getOperand(2);
11271     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11272     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11273     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11274     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11275     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11276   }
11277
11278   // SSE/AVX shift intrinsics
11279   case Intrinsic::x86_sse2_psll_w:
11280   case Intrinsic::x86_sse2_psll_d:
11281   case Intrinsic::x86_sse2_psll_q:
11282   case Intrinsic::x86_avx2_psll_w:
11283   case Intrinsic::x86_avx2_psll_d:
11284   case Intrinsic::x86_avx2_psll_q:
11285   case Intrinsic::x86_sse2_psrl_w:
11286   case Intrinsic::x86_sse2_psrl_d:
11287   case Intrinsic::x86_sse2_psrl_q:
11288   case Intrinsic::x86_avx2_psrl_w:
11289   case Intrinsic::x86_avx2_psrl_d:
11290   case Intrinsic::x86_avx2_psrl_q:
11291   case Intrinsic::x86_sse2_psra_w:
11292   case Intrinsic::x86_sse2_psra_d:
11293   case Intrinsic::x86_avx2_psra_w:
11294   case Intrinsic::x86_avx2_psra_d: {
11295     unsigned Opcode;
11296     switch (IntNo) {
11297     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11298     case Intrinsic::x86_sse2_psll_w:
11299     case Intrinsic::x86_sse2_psll_d:
11300     case Intrinsic::x86_sse2_psll_q:
11301     case Intrinsic::x86_avx2_psll_w:
11302     case Intrinsic::x86_avx2_psll_d:
11303     case Intrinsic::x86_avx2_psll_q:
11304       Opcode = X86ISD::VSHL;
11305       break;
11306     case Intrinsic::x86_sse2_psrl_w:
11307     case Intrinsic::x86_sse2_psrl_d:
11308     case Intrinsic::x86_sse2_psrl_q:
11309     case Intrinsic::x86_avx2_psrl_w:
11310     case Intrinsic::x86_avx2_psrl_d:
11311     case Intrinsic::x86_avx2_psrl_q:
11312       Opcode = X86ISD::VSRL;
11313       break;
11314     case Intrinsic::x86_sse2_psra_w:
11315     case Intrinsic::x86_sse2_psra_d:
11316     case Intrinsic::x86_avx2_psra_w:
11317     case Intrinsic::x86_avx2_psra_d:
11318       Opcode = X86ISD::VSRA;
11319       break;
11320     }
11321     return DAG.getNode(Opcode, dl, Op.getValueType(),
11322                        Op.getOperand(1), Op.getOperand(2));
11323   }
11324
11325   // SSE/AVX immediate shift intrinsics
11326   case Intrinsic::x86_sse2_pslli_w:
11327   case Intrinsic::x86_sse2_pslli_d:
11328   case Intrinsic::x86_sse2_pslli_q:
11329   case Intrinsic::x86_avx2_pslli_w:
11330   case Intrinsic::x86_avx2_pslli_d:
11331   case Intrinsic::x86_avx2_pslli_q:
11332   case Intrinsic::x86_sse2_psrli_w:
11333   case Intrinsic::x86_sse2_psrli_d:
11334   case Intrinsic::x86_sse2_psrli_q:
11335   case Intrinsic::x86_avx2_psrli_w:
11336   case Intrinsic::x86_avx2_psrli_d:
11337   case Intrinsic::x86_avx2_psrli_q:
11338   case Intrinsic::x86_sse2_psrai_w:
11339   case Intrinsic::x86_sse2_psrai_d:
11340   case Intrinsic::x86_avx2_psrai_w:
11341   case Intrinsic::x86_avx2_psrai_d: {
11342     unsigned Opcode;
11343     switch (IntNo) {
11344     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11345     case Intrinsic::x86_sse2_pslli_w:
11346     case Intrinsic::x86_sse2_pslli_d:
11347     case Intrinsic::x86_sse2_pslli_q:
11348     case Intrinsic::x86_avx2_pslli_w:
11349     case Intrinsic::x86_avx2_pslli_d:
11350     case Intrinsic::x86_avx2_pslli_q:
11351       Opcode = X86ISD::VSHLI;
11352       break;
11353     case Intrinsic::x86_sse2_psrli_w:
11354     case Intrinsic::x86_sse2_psrli_d:
11355     case Intrinsic::x86_sse2_psrli_q:
11356     case Intrinsic::x86_avx2_psrli_w:
11357     case Intrinsic::x86_avx2_psrli_d:
11358     case Intrinsic::x86_avx2_psrli_q:
11359       Opcode = X86ISD::VSRLI;
11360       break;
11361     case Intrinsic::x86_sse2_psrai_w:
11362     case Intrinsic::x86_sse2_psrai_d:
11363     case Intrinsic::x86_avx2_psrai_w:
11364     case Intrinsic::x86_avx2_psrai_d:
11365       Opcode = X86ISD::VSRAI;
11366       break;
11367     }
11368     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11369                                Op.getOperand(1), Op.getOperand(2), DAG);
11370   }
11371
11372   case Intrinsic::x86_sse42_pcmpistria128:
11373   case Intrinsic::x86_sse42_pcmpestria128:
11374   case Intrinsic::x86_sse42_pcmpistric128:
11375   case Intrinsic::x86_sse42_pcmpestric128:
11376   case Intrinsic::x86_sse42_pcmpistrio128:
11377   case Intrinsic::x86_sse42_pcmpestrio128:
11378   case Intrinsic::x86_sse42_pcmpistris128:
11379   case Intrinsic::x86_sse42_pcmpestris128:
11380   case Intrinsic::x86_sse42_pcmpistriz128:
11381   case Intrinsic::x86_sse42_pcmpestriz128: {
11382     unsigned Opcode;
11383     unsigned X86CC;
11384     switch (IntNo) {
11385     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11386     case Intrinsic::x86_sse42_pcmpistria128:
11387       Opcode = X86ISD::PCMPISTRI;
11388       X86CC = X86::COND_A;
11389       break;
11390     case Intrinsic::x86_sse42_pcmpestria128:
11391       Opcode = X86ISD::PCMPESTRI;
11392       X86CC = X86::COND_A;
11393       break;
11394     case Intrinsic::x86_sse42_pcmpistric128:
11395       Opcode = X86ISD::PCMPISTRI;
11396       X86CC = X86::COND_B;
11397       break;
11398     case Intrinsic::x86_sse42_pcmpestric128:
11399       Opcode = X86ISD::PCMPESTRI;
11400       X86CC = X86::COND_B;
11401       break;
11402     case Intrinsic::x86_sse42_pcmpistrio128:
11403       Opcode = X86ISD::PCMPISTRI;
11404       X86CC = X86::COND_O;
11405       break;
11406     case Intrinsic::x86_sse42_pcmpestrio128:
11407       Opcode = X86ISD::PCMPESTRI;
11408       X86CC = X86::COND_O;
11409       break;
11410     case Intrinsic::x86_sse42_pcmpistris128:
11411       Opcode = X86ISD::PCMPISTRI;
11412       X86CC = X86::COND_S;
11413       break;
11414     case Intrinsic::x86_sse42_pcmpestris128:
11415       Opcode = X86ISD::PCMPESTRI;
11416       X86CC = X86::COND_S;
11417       break;
11418     case Intrinsic::x86_sse42_pcmpistriz128:
11419       Opcode = X86ISD::PCMPISTRI;
11420       X86CC = X86::COND_E;
11421       break;
11422     case Intrinsic::x86_sse42_pcmpestriz128:
11423       Opcode = X86ISD::PCMPESTRI;
11424       X86CC = X86::COND_E;
11425       break;
11426     }
11427     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11428     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11429     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11430     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11431                                 DAG.getConstant(X86CC, MVT::i8),
11432                                 SDValue(PCMP.getNode(), 1));
11433     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11434   }
11435
11436   case Intrinsic::x86_sse42_pcmpistri128:
11437   case Intrinsic::x86_sse42_pcmpestri128: {
11438     unsigned Opcode;
11439     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11440       Opcode = X86ISD::PCMPISTRI;
11441     else
11442       Opcode = X86ISD::PCMPESTRI;
11443
11444     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11445     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11446     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11447   }
11448   case Intrinsic::x86_fma_vfmadd_ps:
11449   case Intrinsic::x86_fma_vfmadd_pd:
11450   case Intrinsic::x86_fma_vfmsub_ps:
11451   case Intrinsic::x86_fma_vfmsub_pd:
11452   case Intrinsic::x86_fma_vfnmadd_ps:
11453   case Intrinsic::x86_fma_vfnmadd_pd:
11454   case Intrinsic::x86_fma_vfnmsub_ps:
11455   case Intrinsic::x86_fma_vfnmsub_pd:
11456   case Intrinsic::x86_fma_vfmaddsub_ps:
11457   case Intrinsic::x86_fma_vfmaddsub_pd:
11458   case Intrinsic::x86_fma_vfmsubadd_ps:
11459   case Intrinsic::x86_fma_vfmsubadd_pd:
11460   case Intrinsic::x86_fma_vfmadd_ps_256:
11461   case Intrinsic::x86_fma_vfmadd_pd_256:
11462   case Intrinsic::x86_fma_vfmsub_ps_256:
11463   case Intrinsic::x86_fma_vfmsub_pd_256:
11464   case Intrinsic::x86_fma_vfnmadd_ps_256:
11465   case Intrinsic::x86_fma_vfnmadd_pd_256:
11466   case Intrinsic::x86_fma_vfnmsub_ps_256:
11467   case Intrinsic::x86_fma_vfnmsub_pd_256:
11468   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11469   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11470   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11471   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
11472     unsigned Opc;
11473     switch (IntNo) {
11474     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11475     case Intrinsic::x86_fma_vfmadd_ps:
11476     case Intrinsic::x86_fma_vfmadd_pd:
11477     case Intrinsic::x86_fma_vfmadd_ps_256:
11478     case Intrinsic::x86_fma_vfmadd_pd_256:
11479       Opc = X86ISD::FMADD;
11480       break;
11481     case Intrinsic::x86_fma_vfmsub_ps:
11482     case Intrinsic::x86_fma_vfmsub_pd:
11483     case Intrinsic::x86_fma_vfmsub_ps_256:
11484     case Intrinsic::x86_fma_vfmsub_pd_256:
11485       Opc = X86ISD::FMSUB;
11486       break;
11487     case Intrinsic::x86_fma_vfnmadd_ps:
11488     case Intrinsic::x86_fma_vfnmadd_pd:
11489     case Intrinsic::x86_fma_vfnmadd_ps_256:
11490     case Intrinsic::x86_fma_vfnmadd_pd_256:
11491       Opc = X86ISD::FNMADD;
11492       break;
11493     case Intrinsic::x86_fma_vfnmsub_ps:
11494     case Intrinsic::x86_fma_vfnmsub_pd:
11495     case Intrinsic::x86_fma_vfnmsub_ps_256:
11496     case Intrinsic::x86_fma_vfnmsub_pd_256:
11497       Opc = X86ISD::FNMSUB;
11498       break;
11499     case Intrinsic::x86_fma_vfmaddsub_ps:
11500     case Intrinsic::x86_fma_vfmaddsub_pd:
11501     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11502     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11503       Opc = X86ISD::FMADDSUB;
11504       break;
11505     case Intrinsic::x86_fma_vfmsubadd_ps:
11506     case Intrinsic::x86_fma_vfmsubadd_pd:
11507     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11508     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11509       Opc = X86ISD::FMSUBADD;
11510       break;
11511     }
11512
11513     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11514                        Op.getOperand(2), Op.getOperand(3));
11515   }
11516   }
11517 }
11518
11519 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
11520   SDLoc dl(Op);
11521   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11522   switch (IntNo) {
11523   default: return SDValue();    // Don't custom lower most intrinsics.
11524
11525   // RDRAND/RDSEED intrinsics.
11526   case Intrinsic::x86_rdrand_16:
11527   case Intrinsic::x86_rdrand_32:
11528   case Intrinsic::x86_rdrand_64:
11529   case Intrinsic::x86_rdseed_16:
11530   case Intrinsic::x86_rdseed_32:
11531   case Intrinsic::x86_rdseed_64: {
11532     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11533                        IntNo == Intrinsic::x86_rdseed_32 ||
11534                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11535                                                             X86ISD::RDRAND;
11536     // Emit the node with the right value type.
11537     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11538     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11539
11540     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11541     // Otherwise return the value from Rand, which is always 0, casted to i32.
11542     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11543                       DAG.getConstant(1, Op->getValueType(1)),
11544                       DAG.getConstant(X86::COND_B, MVT::i32),
11545                       SDValue(Result.getNode(), 1) };
11546     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11547                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11548                                   Ops, array_lengthof(Ops));
11549
11550     // Return { result, isValid, chain }.
11551     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11552                        SDValue(Result.getNode(), 2));
11553   }
11554
11555   // XTEST intrinsics.
11556   case Intrinsic::x86_xtest: {
11557     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11558     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11559     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11560                                 DAG.getConstant(X86::COND_NE, MVT::i8),
11561                                 InTrans);
11562     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11563     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11564                        Ret, SDValue(InTrans.getNode(), 1));
11565   }
11566   }
11567 }
11568
11569 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11570                                            SelectionDAG &DAG) const {
11571   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11572   MFI->setReturnAddressIsTaken(true);
11573
11574   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11575   SDLoc dl(Op);
11576   EVT PtrVT = getPointerTy();
11577
11578   if (Depth > 0) {
11579     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11580     const X86RegisterInfo *RegInfo =
11581       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11582     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11583     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11584                        DAG.getNode(ISD::ADD, dl, PtrVT,
11585                                    FrameAddr, Offset),
11586                        MachinePointerInfo(), false, false, false, 0);
11587   }
11588
11589   // Just load the return address.
11590   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11591   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11592                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11593 }
11594
11595 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11596   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11597   MFI->setFrameAddressIsTaken(true);
11598
11599   EVT VT = Op.getValueType();
11600   SDLoc dl(Op);  // FIXME probably not meaningful
11601   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11602   const X86RegisterInfo *RegInfo =
11603     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11604   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11605   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11606           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11607          "Invalid Frame Register!");
11608   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11609   while (Depth--)
11610     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11611                             MachinePointerInfo(),
11612                             false, false, false, 0);
11613   return FrameAddr;
11614 }
11615
11616 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11617                                                      SelectionDAG &DAG) const {
11618   const X86RegisterInfo *RegInfo =
11619     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11620   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11621 }
11622
11623 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11624   SDValue Chain     = Op.getOperand(0);
11625   SDValue Offset    = Op.getOperand(1);
11626   SDValue Handler   = Op.getOperand(2);
11627   SDLoc dl      (Op);
11628
11629   EVT PtrVT = getPointerTy();
11630   const X86RegisterInfo *RegInfo =
11631     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11632   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11633   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11634           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11635          "Invalid Frame Register!");
11636   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11637   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11638
11639   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11640                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11641   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11642   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11643                        false, false, 0);
11644   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11645
11646   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11647                      DAG.getRegister(StoreAddrReg, PtrVT));
11648 }
11649
11650 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11651                                                SelectionDAG &DAG) const {
11652   SDLoc DL(Op);
11653   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11654                      DAG.getVTList(MVT::i32, MVT::Other),
11655                      Op.getOperand(0), Op.getOperand(1));
11656 }
11657
11658 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11659                                                 SelectionDAG &DAG) const {
11660   SDLoc DL(Op);
11661   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11662                      Op.getOperand(0), Op.getOperand(1));
11663 }
11664
11665 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11666   return Op.getOperand(0);
11667 }
11668
11669 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11670                                                 SelectionDAG &DAG) const {
11671   SDValue Root = Op.getOperand(0);
11672   SDValue Trmp = Op.getOperand(1); // trampoline
11673   SDValue FPtr = Op.getOperand(2); // nested function
11674   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11675   SDLoc dl (Op);
11676
11677   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11678   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11679
11680   if (Subtarget->is64Bit()) {
11681     SDValue OutChains[6];
11682
11683     // Large code-model.
11684     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11685     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11686
11687     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11688     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11689
11690     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11691
11692     // Load the pointer to the nested function into R11.
11693     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11694     SDValue Addr = Trmp;
11695     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11696                                 Addr, MachinePointerInfo(TrmpAddr),
11697                                 false, false, 0);
11698
11699     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11700                        DAG.getConstant(2, MVT::i64));
11701     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11702                                 MachinePointerInfo(TrmpAddr, 2),
11703                                 false, false, 2);
11704
11705     // Load the 'nest' parameter value into R10.
11706     // R10 is specified in X86CallingConv.td
11707     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11708     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11709                        DAG.getConstant(10, MVT::i64));
11710     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11711                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11712                                 false, false, 0);
11713
11714     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11715                        DAG.getConstant(12, MVT::i64));
11716     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11717                                 MachinePointerInfo(TrmpAddr, 12),
11718                                 false, false, 2);
11719
11720     // Jump to the nested function.
11721     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11722     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11723                        DAG.getConstant(20, MVT::i64));
11724     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11725                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11726                                 false, false, 0);
11727
11728     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11729     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11730                        DAG.getConstant(22, MVT::i64));
11731     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11732                                 MachinePointerInfo(TrmpAddr, 22),
11733                                 false, false, 0);
11734
11735     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11736   } else {
11737     const Function *Func =
11738       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11739     CallingConv::ID CC = Func->getCallingConv();
11740     unsigned NestReg;
11741
11742     switch (CC) {
11743     default:
11744       llvm_unreachable("Unsupported calling convention");
11745     case CallingConv::C:
11746     case CallingConv::X86_StdCall: {
11747       // Pass 'nest' parameter in ECX.
11748       // Must be kept in sync with X86CallingConv.td
11749       NestReg = X86::ECX;
11750
11751       // Check that ECX wasn't needed by an 'inreg' parameter.
11752       FunctionType *FTy = Func->getFunctionType();
11753       const AttributeSet &Attrs = Func->getAttributes();
11754
11755       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11756         unsigned InRegCount = 0;
11757         unsigned Idx = 1;
11758
11759         for (FunctionType::param_iterator I = FTy->param_begin(),
11760              E = FTy->param_end(); I != E; ++I, ++Idx)
11761           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11762             // FIXME: should only count parameters that are lowered to integers.
11763             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11764
11765         if (InRegCount > 2) {
11766           report_fatal_error("Nest register in use - reduce number of inreg"
11767                              " parameters!");
11768         }
11769       }
11770       break;
11771     }
11772     case CallingConv::X86_FastCall:
11773     case CallingConv::X86_ThisCall:
11774     case CallingConv::Fast:
11775       // Pass 'nest' parameter in EAX.
11776       // Must be kept in sync with X86CallingConv.td
11777       NestReg = X86::EAX;
11778       break;
11779     }
11780
11781     SDValue OutChains[4];
11782     SDValue Addr, Disp;
11783
11784     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11785                        DAG.getConstant(10, MVT::i32));
11786     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11787
11788     // This is storing the opcode for MOV32ri.
11789     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11790     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11791     OutChains[0] = DAG.getStore(Root, dl,
11792                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11793                                 Trmp, MachinePointerInfo(TrmpAddr),
11794                                 false, false, 0);
11795
11796     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11797                        DAG.getConstant(1, MVT::i32));
11798     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11799                                 MachinePointerInfo(TrmpAddr, 1),
11800                                 false, false, 1);
11801
11802     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11803     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11804                        DAG.getConstant(5, MVT::i32));
11805     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11806                                 MachinePointerInfo(TrmpAddr, 5),
11807                                 false, false, 1);
11808
11809     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11810                        DAG.getConstant(6, MVT::i32));
11811     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11812                                 MachinePointerInfo(TrmpAddr, 6),
11813                                 false, false, 1);
11814
11815     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11816   }
11817 }
11818
11819 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11820                                             SelectionDAG &DAG) const {
11821   /*
11822    The rounding mode is in bits 11:10 of FPSR, and has the following
11823    settings:
11824      00 Round to nearest
11825      01 Round to -inf
11826      10 Round to +inf
11827      11 Round to 0
11828
11829   FLT_ROUNDS, on the other hand, expects the following:
11830     -1 Undefined
11831      0 Round to 0
11832      1 Round to nearest
11833      2 Round to +inf
11834      3 Round to -inf
11835
11836   To perform the conversion, we do:
11837     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11838   */
11839
11840   MachineFunction &MF = DAG.getMachineFunction();
11841   const TargetMachine &TM = MF.getTarget();
11842   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11843   unsigned StackAlignment = TFI.getStackAlignment();
11844   EVT VT = Op.getValueType();
11845   SDLoc DL(Op);
11846
11847   // Save FP Control Word to stack slot
11848   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11849   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11850
11851   MachineMemOperand *MMO =
11852    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11853                            MachineMemOperand::MOStore, 2, 2);
11854
11855   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11856   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11857                                           DAG.getVTList(MVT::Other),
11858                                           Ops, array_lengthof(Ops), MVT::i16,
11859                                           MMO);
11860
11861   // Load FP Control Word from stack slot
11862   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11863                             MachinePointerInfo(), false, false, false, 0);
11864
11865   // Transform as necessary
11866   SDValue CWD1 =
11867     DAG.getNode(ISD::SRL, DL, MVT::i16,
11868                 DAG.getNode(ISD::AND, DL, MVT::i16,
11869                             CWD, DAG.getConstant(0x800, MVT::i16)),
11870                 DAG.getConstant(11, MVT::i8));
11871   SDValue CWD2 =
11872     DAG.getNode(ISD::SRL, DL, MVT::i16,
11873                 DAG.getNode(ISD::AND, DL, MVT::i16,
11874                             CWD, DAG.getConstant(0x400, MVT::i16)),
11875                 DAG.getConstant(9, MVT::i8));
11876
11877   SDValue RetVal =
11878     DAG.getNode(ISD::AND, DL, MVT::i16,
11879                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11880                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11881                             DAG.getConstant(1, MVT::i16)),
11882                 DAG.getConstant(3, MVT::i16));
11883
11884   return DAG.getNode((VT.getSizeInBits() < 16 ?
11885                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11886 }
11887
11888 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11889   EVT VT = Op.getValueType();
11890   EVT OpVT = VT;
11891   unsigned NumBits = VT.getSizeInBits();
11892   SDLoc dl(Op);
11893
11894   Op = Op.getOperand(0);
11895   if (VT == MVT::i8) {
11896     // Zero extend to i32 since there is not an i8 bsr.
11897     OpVT = MVT::i32;
11898     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11899   }
11900
11901   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11902   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11903   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11904
11905   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11906   SDValue Ops[] = {
11907     Op,
11908     DAG.getConstant(NumBits+NumBits-1, OpVT),
11909     DAG.getConstant(X86::COND_E, MVT::i8),
11910     Op.getValue(1)
11911   };
11912   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11913
11914   // Finally xor with NumBits-1.
11915   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11916
11917   if (VT == MVT::i8)
11918     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11919   return Op;
11920 }
11921
11922 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11923   EVT VT = Op.getValueType();
11924   EVT OpVT = VT;
11925   unsigned NumBits = VT.getSizeInBits();
11926   SDLoc dl(Op);
11927
11928   Op = Op.getOperand(0);
11929   if (VT == MVT::i8) {
11930     // Zero extend to i32 since there is not an i8 bsr.
11931     OpVT = MVT::i32;
11932     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11933   }
11934
11935   // Issue a bsr (scan bits in reverse).
11936   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11937   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11938
11939   // And xor with NumBits-1.
11940   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11941
11942   if (VT == MVT::i8)
11943     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11944   return Op;
11945 }
11946
11947 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11948   EVT VT = Op.getValueType();
11949   unsigned NumBits = VT.getSizeInBits();
11950   SDLoc dl(Op);
11951   Op = Op.getOperand(0);
11952
11953   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11954   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11955   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11956
11957   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11958   SDValue Ops[] = {
11959     Op,
11960     DAG.getConstant(NumBits, VT),
11961     DAG.getConstant(X86::COND_E, MVT::i8),
11962     Op.getValue(1)
11963   };
11964   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11965 }
11966
11967 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11968 // ones, and then concatenate the result back.
11969 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11970   EVT VT = Op.getValueType();
11971
11972   assert(VT.is256BitVector() && VT.isInteger() &&
11973          "Unsupported value type for operation");
11974
11975   unsigned NumElems = VT.getVectorNumElements();
11976   SDLoc dl(Op);
11977
11978   // Extract the LHS vectors
11979   SDValue LHS = Op.getOperand(0);
11980   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11981   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11982
11983   // Extract the RHS vectors
11984   SDValue RHS = Op.getOperand(1);
11985   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11986   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11987
11988   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11989   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11990
11991   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11992                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11993                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11994 }
11995
11996 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11997   assert(Op.getValueType().is256BitVector() &&
11998          Op.getValueType().isInteger() &&
11999          "Only handle AVX 256-bit vector integer operation");
12000   return Lower256IntArith(Op, DAG);
12001 }
12002
12003 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
12004   assert(Op.getValueType().is256BitVector() &&
12005          Op.getValueType().isInteger() &&
12006          "Only handle AVX 256-bit vector integer operation");
12007   return Lower256IntArith(Op, DAG);
12008 }
12009
12010 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
12011                         SelectionDAG &DAG) {
12012   SDLoc dl(Op);
12013   EVT VT = Op.getValueType();
12014
12015   // Decompose 256-bit ops into smaller 128-bit ops.
12016   if (VT.is256BitVector() && !Subtarget->hasInt256())
12017     return Lower256IntArith(Op, DAG);
12018
12019   SDValue A = Op.getOperand(0);
12020   SDValue B = Op.getOperand(1);
12021
12022   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
12023   if (VT == MVT::v4i32) {
12024     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
12025            "Should not custom lower when pmuldq is available!");
12026
12027     // Extract the odd parts.
12028     static const int UnpackMask[] = { 1, -1, 3, -1 };
12029     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
12030     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
12031
12032     // Multiply the even parts.
12033     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
12034     // Now multiply odd parts.
12035     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
12036
12037     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
12038     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
12039
12040     // Merge the two vectors back together with a shuffle. This expands into 2
12041     // shuffles.
12042     static const int ShufMask[] = { 0, 4, 2, 6 };
12043     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
12044   }
12045
12046   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
12047          "Only know how to lower V2I64/V4I64 multiply");
12048
12049   //  Ahi = psrlqi(a, 32);
12050   //  Bhi = psrlqi(b, 32);
12051   //
12052   //  AloBlo = pmuludq(a, b);
12053   //  AloBhi = pmuludq(a, Bhi);
12054   //  AhiBlo = pmuludq(Ahi, b);
12055
12056   //  AloBhi = psllqi(AloBhi, 32);
12057   //  AhiBlo = psllqi(AhiBlo, 32);
12058   //  return AloBlo + AloBhi + AhiBlo;
12059
12060   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
12061
12062   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
12063   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
12064
12065   // Bit cast to 32-bit vectors for MULUDQ
12066   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
12067   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
12068   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
12069   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
12070   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
12071
12072   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
12073   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
12074   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
12075
12076   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
12077   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
12078
12079   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
12080   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
12081 }
12082
12083 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
12084   EVT VT = Op.getValueType();
12085   EVT EltTy = VT.getVectorElementType();
12086   unsigned NumElts = VT.getVectorNumElements();
12087   SDValue N0 = Op.getOperand(0);
12088   SDLoc dl(Op);
12089
12090   // Lower sdiv X, pow2-const.
12091   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
12092   if (!C)
12093     return SDValue();
12094
12095   APInt SplatValue, SplatUndef;
12096   unsigned SplatBitSize;
12097   bool HasAnyUndefs;
12098   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
12099                           HasAnyUndefs) ||
12100       EltTy.getSizeInBits() < SplatBitSize)
12101     return SDValue();
12102
12103   if ((SplatValue != 0) &&
12104       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
12105     unsigned lg2 = SplatValue.countTrailingZeros();
12106     // Splat the sign bit.
12107     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
12108     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
12109     // Add (N0 < 0) ? abs2 - 1 : 0;
12110     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
12111     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
12112     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
12113     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
12114     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
12115
12116     // If we're dividing by a positive value, we're done.  Otherwise, we must
12117     // negate the result.
12118     if (SplatValue.isNonNegative())
12119       return SRA;
12120
12121     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
12122     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
12123     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
12124   }
12125   return SDValue();
12126 }
12127
12128 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
12129                                          const X86Subtarget *Subtarget) {
12130   EVT VT = Op.getValueType();
12131   SDLoc dl(Op);
12132   SDValue R = Op.getOperand(0);
12133   SDValue Amt = Op.getOperand(1);
12134
12135   // Optimize shl/srl/sra with constant shift amount.
12136   if (isSplatVector(Amt.getNode())) {
12137     SDValue SclrAmt = Amt->getOperand(0);
12138     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12139       uint64_t ShiftAmt = C->getZExtValue();
12140
12141       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12142           (Subtarget->hasInt256() &&
12143            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
12144         if (Op.getOpcode() == ISD::SHL)
12145           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12146                              DAG.getConstant(ShiftAmt, MVT::i32));
12147         if (Op.getOpcode() == ISD::SRL)
12148           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12149                              DAG.getConstant(ShiftAmt, MVT::i32));
12150         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12151           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12152                              DAG.getConstant(ShiftAmt, MVT::i32));
12153       }
12154
12155       if (VT == MVT::v16i8) {
12156         if (Op.getOpcode() == ISD::SHL) {
12157           // Make a large shift.
12158           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
12159                                     DAG.getConstant(ShiftAmt, MVT::i32));
12160           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12161           // Zero out the rightmost bits.
12162           SmallVector<SDValue, 16> V(16,
12163                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12164                                                      MVT::i8));
12165           return DAG.getNode(ISD::AND, dl, VT, SHL,
12166                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12167         }
12168         if (Op.getOpcode() == ISD::SRL) {
12169           // Make a large shift.
12170           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
12171                                     DAG.getConstant(ShiftAmt, MVT::i32));
12172           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12173           // Zero out the leftmost bits.
12174           SmallVector<SDValue, 16> V(16,
12175                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12176                                                      MVT::i8));
12177           return DAG.getNode(ISD::AND, dl, VT, SRL,
12178                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12179         }
12180         if (Op.getOpcode() == ISD::SRA) {
12181           if (ShiftAmt == 7) {
12182             // R s>> 7  ===  R s< 0
12183             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12184             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12185           }
12186
12187           // R s>> a === ((R u>> a) ^ m) - m
12188           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12189           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12190                                                          MVT::i8));
12191           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12192           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12193           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12194           return Res;
12195         }
12196         llvm_unreachable("Unknown shift opcode.");
12197       }
12198
12199       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12200         if (Op.getOpcode() == ISD::SHL) {
12201           // Make a large shift.
12202           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
12203                                     DAG.getConstant(ShiftAmt, MVT::i32));
12204           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12205           // Zero out the rightmost bits.
12206           SmallVector<SDValue, 32> V(32,
12207                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12208                                                      MVT::i8));
12209           return DAG.getNode(ISD::AND, dl, VT, SHL,
12210                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12211         }
12212         if (Op.getOpcode() == ISD::SRL) {
12213           // Make a large shift.
12214           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
12215                                     DAG.getConstant(ShiftAmt, MVT::i32));
12216           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12217           // Zero out the leftmost bits.
12218           SmallVector<SDValue, 32> V(32,
12219                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12220                                                      MVT::i8));
12221           return DAG.getNode(ISD::AND, dl, VT, SRL,
12222                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12223         }
12224         if (Op.getOpcode() == ISD::SRA) {
12225           if (ShiftAmt == 7) {
12226             // R s>> 7  ===  R s< 0
12227             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12228             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12229           }
12230
12231           // R s>> a === ((R u>> a) ^ m) - m
12232           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12233           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12234                                                          MVT::i8));
12235           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12236           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12237           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12238           return Res;
12239         }
12240         llvm_unreachable("Unknown shift opcode.");
12241       }
12242     }
12243   }
12244
12245   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12246   if (!Subtarget->is64Bit() &&
12247       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12248       Amt.getOpcode() == ISD::BITCAST &&
12249       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12250     Amt = Amt.getOperand(0);
12251     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12252                      VT.getVectorNumElements();
12253     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12254     uint64_t ShiftAmt = 0;
12255     for (unsigned i = 0; i != Ratio; ++i) {
12256       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12257       if (C == 0)
12258         return SDValue();
12259       // 6 == Log2(64)
12260       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12261     }
12262     // Check remaining shift amounts.
12263     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12264       uint64_t ShAmt = 0;
12265       for (unsigned j = 0; j != Ratio; ++j) {
12266         ConstantSDNode *C =
12267           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12268         if (C == 0)
12269           return SDValue();
12270         // 6 == Log2(64)
12271         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12272       }
12273       if (ShAmt != ShiftAmt)
12274         return SDValue();
12275     }
12276     switch (Op.getOpcode()) {
12277     default:
12278       llvm_unreachable("Unknown shift opcode!");
12279     case ISD::SHL:
12280       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12281                          DAG.getConstant(ShiftAmt, MVT::i32));
12282     case ISD::SRL:
12283       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12284                          DAG.getConstant(ShiftAmt, MVT::i32));
12285     case ISD::SRA:
12286       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12287                          DAG.getConstant(ShiftAmt, MVT::i32));
12288     }
12289   }
12290
12291   return SDValue();
12292 }
12293
12294 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12295                                         const X86Subtarget* Subtarget) {
12296   EVT VT = Op.getValueType();
12297   SDLoc dl(Op);
12298   SDValue R = Op.getOperand(0);
12299   SDValue Amt = Op.getOperand(1);
12300
12301   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12302       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12303       (Subtarget->hasInt256() &&
12304        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12305         VT == MVT::v8i32 || VT == MVT::v16i16))) {
12306     SDValue BaseShAmt;
12307     EVT EltVT = VT.getVectorElementType();
12308
12309     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12310       unsigned NumElts = VT.getVectorNumElements();
12311       unsigned i, j;
12312       for (i = 0; i != NumElts; ++i) {
12313         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12314           continue;
12315         break;
12316       }
12317       for (j = i; j != NumElts; ++j) {
12318         SDValue Arg = Amt.getOperand(j);
12319         if (Arg.getOpcode() == ISD::UNDEF) continue;
12320         if (Arg != Amt.getOperand(i))
12321           break;
12322       }
12323       if (i != NumElts && j == NumElts)
12324         BaseShAmt = Amt.getOperand(i);
12325     } else {
12326       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12327         Amt = Amt.getOperand(0);
12328       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12329                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12330         SDValue InVec = Amt.getOperand(0);
12331         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12332           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12333           unsigned i = 0;
12334           for (; i != NumElts; ++i) {
12335             SDValue Arg = InVec.getOperand(i);
12336             if (Arg.getOpcode() == ISD::UNDEF) continue;
12337             BaseShAmt = Arg;
12338             break;
12339           }
12340         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12341            if (ConstantSDNode *C =
12342                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12343              unsigned SplatIdx =
12344                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12345              if (C->getZExtValue() == SplatIdx)
12346                BaseShAmt = InVec.getOperand(1);
12347            }
12348         }
12349         if (BaseShAmt.getNode() == 0)
12350           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12351                                   DAG.getIntPtrConstant(0));
12352       }
12353     }
12354
12355     if (BaseShAmt.getNode()) {
12356       if (EltVT.bitsGT(MVT::i32))
12357         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12358       else if (EltVT.bitsLT(MVT::i32))
12359         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12360
12361       switch (Op.getOpcode()) {
12362       default:
12363         llvm_unreachable("Unknown shift opcode!");
12364       case ISD::SHL:
12365         switch (VT.getSimpleVT().SimpleTy) {
12366         default: return SDValue();
12367         case MVT::v2i64:
12368         case MVT::v4i32:
12369         case MVT::v8i16:
12370         case MVT::v4i64:
12371         case MVT::v8i32:
12372         case MVT::v16i16:
12373           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12374         }
12375       case ISD::SRA:
12376         switch (VT.getSimpleVT().SimpleTy) {
12377         default: return SDValue();
12378         case MVT::v4i32:
12379         case MVT::v8i16:
12380         case MVT::v8i32:
12381         case MVT::v16i16:
12382           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12383         }
12384       case ISD::SRL:
12385         switch (VT.getSimpleVT().SimpleTy) {
12386         default: return SDValue();
12387         case MVT::v2i64:
12388         case MVT::v4i32:
12389         case MVT::v8i16:
12390         case MVT::v4i64:
12391         case MVT::v8i32:
12392         case MVT::v16i16:
12393           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12394         }
12395       }
12396     }
12397   }
12398
12399   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12400   if (!Subtarget->is64Bit() &&
12401       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12402       Amt.getOpcode() == ISD::BITCAST &&
12403       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12404     Amt = Amt.getOperand(0);
12405     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12406                      VT.getVectorNumElements();
12407     std::vector<SDValue> Vals(Ratio);
12408     for (unsigned i = 0; i != Ratio; ++i)
12409       Vals[i] = Amt.getOperand(i);
12410     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12411       for (unsigned j = 0; j != Ratio; ++j)
12412         if (Vals[j] != Amt.getOperand(i + j))
12413           return SDValue();
12414     }
12415     switch (Op.getOpcode()) {
12416     default:
12417       llvm_unreachable("Unknown shift opcode!");
12418     case ISD::SHL:
12419       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12420     case ISD::SRL:
12421       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12422     case ISD::SRA:
12423       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12424     }
12425   }
12426
12427   return SDValue();
12428 }
12429
12430 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
12431                           SelectionDAG &DAG) {
12432
12433   EVT VT = Op.getValueType();
12434   SDLoc dl(Op);
12435   SDValue R = Op.getOperand(0);
12436   SDValue Amt = Op.getOperand(1);
12437   SDValue V;
12438
12439   if (!Subtarget->hasSSE2())
12440     return SDValue();
12441
12442   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12443   if (V.getNode())
12444     return V;
12445
12446   V = LowerScalarVariableShift(Op, DAG, Subtarget);
12447   if (V.getNode())
12448       return V;
12449
12450   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12451   if (Subtarget->hasInt256()) {
12452     if (Op.getOpcode() == ISD::SRL &&
12453         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12454          VT == MVT::v4i64 || VT == MVT::v8i32))
12455       return Op;
12456     if (Op.getOpcode() == ISD::SHL &&
12457         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12458          VT == MVT::v4i64 || VT == MVT::v8i32))
12459       return Op;
12460     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12461       return Op;
12462   }
12463
12464   // Lower SHL with variable shift amount.
12465   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12466     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12467
12468     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12469     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12470     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12471     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12472   }
12473   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12474     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12475
12476     // a = a << 5;
12477     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12478     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12479
12480     // Turn 'a' into a mask suitable for VSELECT
12481     SDValue VSelM = DAG.getConstant(0x80, VT);
12482     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12483     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12484
12485     SDValue CM1 = DAG.getConstant(0x0f, VT);
12486     SDValue CM2 = DAG.getConstant(0x3f, VT);
12487
12488     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12489     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12490     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12491                             DAG.getConstant(4, MVT::i32), DAG);
12492     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12493     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12494
12495     // a += a
12496     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12497     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12498     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12499
12500     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12501     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12502     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12503                             DAG.getConstant(2, MVT::i32), DAG);
12504     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12505     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12506
12507     // a += a
12508     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12509     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12510     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12511
12512     // return VSELECT(r, r+r, a);
12513     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
12514                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
12515     return R;
12516   }
12517
12518   // Decompose 256-bit shifts into smaller 128-bit shifts.
12519   if (VT.is256BitVector()) {
12520     unsigned NumElems = VT.getVectorNumElements();
12521     MVT EltVT = VT.getVectorElementType().getSimpleVT();
12522     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12523
12524     // Extract the two vectors
12525     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
12526     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
12527
12528     // Recreate the shift amount vectors
12529     SDValue Amt1, Amt2;
12530     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12531       // Constant shift amount
12532       SmallVector<SDValue, 4> Amt1Csts;
12533       SmallVector<SDValue, 4> Amt2Csts;
12534       for (unsigned i = 0; i != NumElems/2; ++i)
12535         Amt1Csts.push_back(Amt->getOperand(i));
12536       for (unsigned i = NumElems/2; i != NumElems; ++i)
12537         Amt2Csts.push_back(Amt->getOperand(i));
12538
12539       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12540                                  &Amt1Csts[0], NumElems/2);
12541       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12542                                  &Amt2Csts[0], NumElems/2);
12543     } else {
12544       // Variable shift amount
12545       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12546       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12547     }
12548
12549     // Issue new vector shifts for the smaller types
12550     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12551     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12552
12553     // Concatenate the result back
12554     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12555   }
12556
12557   return SDValue();
12558 }
12559
12560 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12561   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12562   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12563   // looks for this combo and may remove the "setcc" instruction if the "setcc"
12564   // has only one use.
12565   SDNode *N = Op.getNode();
12566   SDValue LHS = N->getOperand(0);
12567   SDValue RHS = N->getOperand(1);
12568   unsigned BaseOp = 0;
12569   unsigned Cond = 0;
12570   SDLoc DL(Op);
12571   switch (Op.getOpcode()) {
12572   default: llvm_unreachable("Unknown ovf instruction!");
12573   case ISD::SADDO:
12574     // A subtract of one will be selected as a INC. Note that INC doesn't
12575     // set CF, so we can't do this for UADDO.
12576     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12577       if (C->isOne()) {
12578         BaseOp = X86ISD::INC;
12579         Cond = X86::COND_O;
12580         break;
12581       }
12582     BaseOp = X86ISD::ADD;
12583     Cond = X86::COND_O;
12584     break;
12585   case ISD::UADDO:
12586     BaseOp = X86ISD::ADD;
12587     Cond = X86::COND_B;
12588     break;
12589   case ISD::SSUBO:
12590     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12591     // set CF, so we can't do this for USUBO.
12592     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12593       if (C->isOne()) {
12594         BaseOp = X86ISD::DEC;
12595         Cond = X86::COND_O;
12596         break;
12597       }
12598     BaseOp = X86ISD::SUB;
12599     Cond = X86::COND_O;
12600     break;
12601   case ISD::USUBO:
12602     BaseOp = X86ISD::SUB;
12603     Cond = X86::COND_B;
12604     break;
12605   case ISD::SMULO:
12606     BaseOp = X86ISD::SMUL;
12607     Cond = X86::COND_O;
12608     break;
12609   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12610     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12611                                  MVT::i32);
12612     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12613
12614     SDValue SetCC =
12615       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12616                   DAG.getConstant(X86::COND_O, MVT::i32),
12617                   SDValue(Sum.getNode(), 2));
12618
12619     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12620   }
12621   }
12622
12623   // Also sets EFLAGS.
12624   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12625   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12626
12627   SDValue SetCC =
12628     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12629                 DAG.getConstant(Cond, MVT::i32),
12630                 SDValue(Sum.getNode(), 1));
12631
12632   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12633 }
12634
12635 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12636                                                   SelectionDAG &DAG) const {
12637   SDLoc dl(Op);
12638   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12639   EVT VT = Op.getValueType();
12640
12641   if (!Subtarget->hasSSE2() || !VT.isVector())
12642     return SDValue();
12643
12644   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12645                       ExtraVT.getScalarType().getSizeInBits();
12646   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12647
12648   switch (VT.getSimpleVT().SimpleTy) {
12649     default: return SDValue();
12650     case MVT::v8i32:
12651     case MVT::v16i16:
12652       if (!Subtarget->hasFp256())
12653         return SDValue();
12654       if (!Subtarget->hasInt256()) {
12655         // needs to be split
12656         unsigned NumElems = VT.getVectorNumElements();
12657
12658         // Extract the LHS vectors
12659         SDValue LHS = Op.getOperand(0);
12660         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12661         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12662
12663         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12664         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12665
12666         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12667         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12668         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12669                                    ExtraNumElems/2);
12670         SDValue Extra = DAG.getValueType(ExtraVT);
12671
12672         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12673         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12674
12675         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12676       }
12677       // fall through
12678     case MVT::v4i32:
12679     case MVT::v8i16: {
12680       // (sext (vzext x)) -> (vsext x)
12681       SDValue Op0 = Op.getOperand(0);
12682       SDValue Op00 = Op0.getOperand(0);
12683       SDValue Tmp1;
12684       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12685       if (Op0.getOpcode() == ISD::BITCAST &&
12686           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12687         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
12688       if (Tmp1.getNode()) {
12689         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12690         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12691                "This optimization is invalid without a VZEXT.");
12692         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12693       }
12694
12695       // If the above didn't work, then just use Shift-Left + Shift-Right.
12696       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12697       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12698     }
12699   }
12700 }
12701
12702 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12703                                  SelectionDAG &DAG) {
12704   SDLoc dl(Op);
12705   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12706     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12707   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12708     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12709
12710   // The only fence that needs an instruction is a sequentially-consistent
12711   // cross-thread fence.
12712   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12713     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12714     // no-sse2). There isn't any reason to disable it if the target processor
12715     // supports it.
12716     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12717       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12718
12719     SDValue Chain = Op.getOperand(0);
12720     SDValue Zero = DAG.getConstant(0, MVT::i32);
12721     SDValue Ops[] = {
12722       DAG.getRegister(X86::ESP, MVT::i32), // Base
12723       DAG.getTargetConstant(1, MVT::i8),   // Scale
12724       DAG.getRegister(0, MVT::i32),        // Index
12725       DAG.getTargetConstant(0, MVT::i32),  // Disp
12726       DAG.getRegister(0, MVT::i32),        // Segment.
12727       Zero,
12728       Chain
12729     };
12730     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12731     return SDValue(Res, 0);
12732   }
12733
12734   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12735   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12736 }
12737
12738 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12739                              SelectionDAG &DAG) {
12740   EVT T = Op.getValueType();
12741   SDLoc DL(Op);
12742   unsigned Reg = 0;
12743   unsigned size = 0;
12744   switch(T.getSimpleVT().SimpleTy) {
12745   default: llvm_unreachable("Invalid value type!");
12746   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12747   case MVT::i16: Reg = X86::AX;  size = 2; break;
12748   case MVT::i32: Reg = X86::EAX; size = 4; break;
12749   case MVT::i64:
12750     assert(Subtarget->is64Bit() && "Node not type legal!");
12751     Reg = X86::RAX; size = 8;
12752     break;
12753   }
12754   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12755                                     Op.getOperand(2), SDValue());
12756   SDValue Ops[] = { cpIn.getValue(0),
12757                     Op.getOperand(1),
12758                     Op.getOperand(3),
12759                     DAG.getTargetConstant(size, MVT::i8),
12760                     cpIn.getValue(1) };
12761   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12762   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12763   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12764                                            Ops, array_lengthof(Ops), T, MMO);
12765   SDValue cpOut =
12766     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12767   return cpOut;
12768 }
12769
12770 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12771                                      SelectionDAG &DAG) {
12772   assert(Subtarget->is64Bit() && "Result not type legalized?");
12773   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12774   SDValue TheChain = Op.getOperand(0);
12775   SDLoc dl(Op);
12776   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12777   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12778   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12779                                    rax.getValue(2));
12780   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12781                             DAG.getConstant(32, MVT::i8));
12782   SDValue Ops[] = {
12783     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12784     rdx.getValue(1)
12785   };
12786   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12787 }
12788
12789 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
12790                             SelectionDAG &DAG) {
12791   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
12792   MVT DstVT = Op.getSimpleValueType();
12793   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12794          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12795   assert((DstVT == MVT::i64 ||
12796           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12797          "Unexpected custom BITCAST");
12798   // i64 <=> MMX conversions are Legal.
12799   if (SrcVT==MVT::i64 && DstVT.isVector())
12800     return Op;
12801   if (DstVT==MVT::i64 && SrcVT.isVector())
12802     return Op;
12803   // MMX <=> MMX conversions are Legal.
12804   if (SrcVT.isVector() && DstVT.isVector())
12805     return Op;
12806   // All other conversions need to be expanded.
12807   return SDValue();
12808 }
12809
12810 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12811   SDNode *Node = Op.getNode();
12812   SDLoc dl(Node);
12813   EVT T = Node->getValueType(0);
12814   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12815                               DAG.getConstant(0, T), Node->getOperand(2));
12816   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12817                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12818                        Node->getOperand(0),
12819                        Node->getOperand(1), negOp,
12820                        cast<AtomicSDNode>(Node)->getSrcValue(),
12821                        cast<AtomicSDNode>(Node)->getAlignment(),
12822                        cast<AtomicSDNode>(Node)->getOrdering(),
12823                        cast<AtomicSDNode>(Node)->getSynchScope());
12824 }
12825
12826 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12827   SDNode *Node = Op.getNode();
12828   SDLoc dl(Node);
12829   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12830
12831   // Convert seq_cst store -> xchg
12832   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12833   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12834   //        (The only way to get a 16-byte store is cmpxchg16b)
12835   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12836   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12837       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12838     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12839                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12840                                  Node->getOperand(0),
12841                                  Node->getOperand(1), Node->getOperand(2),
12842                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12843                                  cast<AtomicSDNode>(Node)->getOrdering(),
12844                                  cast<AtomicSDNode>(Node)->getSynchScope());
12845     return Swap.getValue(1);
12846   }
12847   // Other atomic stores have a simple pattern.
12848   return Op;
12849 }
12850
12851 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12852   EVT VT = Op.getNode()->getValueType(0);
12853
12854   // Let legalize expand this if it isn't a legal type yet.
12855   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12856     return SDValue();
12857
12858   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12859
12860   unsigned Opc;
12861   bool ExtraOp = false;
12862   switch (Op.getOpcode()) {
12863   default: llvm_unreachable("Invalid code");
12864   case ISD::ADDC: Opc = X86ISD::ADD; break;
12865   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12866   case ISD::SUBC: Opc = X86ISD::SUB; break;
12867   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12868   }
12869
12870   if (!ExtraOp)
12871     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12872                        Op.getOperand(1));
12873   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12874                      Op.getOperand(1), Op.getOperand(2));
12875 }
12876
12877 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
12878                             SelectionDAG &DAG) {
12879   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12880
12881   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12882   // which returns the values as { float, float } (in XMM0) or
12883   // { double, double } (which is returned in XMM0, XMM1).
12884   SDLoc dl(Op);
12885   SDValue Arg = Op.getOperand(0);
12886   EVT ArgVT = Arg.getValueType();
12887   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12888
12889   TargetLowering::ArgListTy Args;
12890   TargetLowering::ArgListEntry Entry;
12891
12892   Entry.Node = Arg;
12893   Entry.Ty = ArgTy;
12894   Entry.isSExt = false;
12895   Entry.isZExt = false;
12896   Args.push_back(Entry);
12897
12898   bool isF64 = ArgVT == MVT::f64;
12899   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12900   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12901   // the results are returned via SRet in memory.
12902   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12903   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12904   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
12905
12906   Type *RetTy = isF64
12907     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12908     : (Type*)VectorType::get(ArgTy, 4);
12909   TargetLowering::
12910     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12911                          false, false, false, false, 0,
12912                          CallingConv::C, /*isTaillCall=*/false,
12913                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12914                          Callee, Args, DAG, dl);
12915   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
12916
12917   if (isF64)
12918     // Returned in xmm0 and xmm1.
12919     return CallResult.first;
12920
12921   // Returned in bits 0:31 and 32:64 xmm0.
12922   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12923                                CallResult.first, DAG.getIntPtrConstant(0));
12924   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12925                                CallResult.first, DAG.getIntPtrConstant(1));
12926   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12927   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12928 }
12929
12930 /// LowerOperation - Provide custom lowering hooks for some operations.
12931 ///
12932 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12933   switch (Op.getOpcode()) {
12934   default: llvm_unreachable("Should not custom lower this!");
12935   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12936   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12937   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12938   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12939   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12940   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12941   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12942   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12943   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12944   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12945   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12946   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12947   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12948   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12949   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12950   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12951   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12952   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12953   case ISD::SHL_PARTS:
12954   case ISD::SRA_PARTS:
12955   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12956   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12957   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12958   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12959   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
12960   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
12961   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
12962   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12963   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12964   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12965   case ISD::FABS:               return LowerFABS(Op, DAG);
12966   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12967   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12968   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12969   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12970   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12971   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12972   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12973   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12974   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12975   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12976   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12977   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12978   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12979   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12980   case ISD::FRAME_TO_ARGS_OFFSET:
12981                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12982   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12983   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12984   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12985   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12986   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12987   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12988   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12989   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12990   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12991   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12992   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12993   case ISD::SRA:
12994   case ISD::SRL:
12995   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
12996   case ISD::SADDO:
12997   case ISD::UADDO:
12998   case ISD::SSUBO:
12999   case ISD::USUBO:
13000   case ISD::SMULO:
13001   case ISD::UMULO:              return LowerXALUO(Op, DAG);
13002   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
13003   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
13004   case ISD::ADDC:
13005   case ISD::ADDE:
13006   case ISD::SUBC:
13007   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
13008   case ISD::ADD:                return LowerADD(Op, DAG);
13009   case ISD::SUB:                return LowerSUB(Op, DAG);
13010   case ISD::SDIV:               return LowerSDIV(Op, DAG);
13011   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
13012   }
13013 }
13014
13015 static void ReplaceATOMIC_LOAD(SDNode *Node,
13016                                   SmallVectorImpl<SDValue> &Results,
13017                                   SelectionDAG &DAG) {
13018   SDLoc dl(Node);
13019   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
13020
13021   // Convert wide load -> cmpxchg8b/cmpxchg16b
13022   // FIXME: On 32-bit, load -> fild or movq would be more efficient
13023   //        (The only way to get a 16-byte load is cmpxchg16b)
13024   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
13025   SDValue Zero = DAG.getConstant(0, VT);
13026   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
13027                                Node->getOperand(0),
13028                                Node->getOperand(1), Zero, Zero,
13029                                cast<AtomicSDNode>(Node)->getMemOperand(),
13030                                cast<AtomicSDNode>(Node)->getOrdering(),
13031                                cast<AtomicSDNode>(Node)->getSynchScope());
13032   Results.push_back(Swap.getValue(0));
13033   Results.push_back(Swap.getValue(1));
13034 }
13035
13036 static void
13037 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
13038                         SelectionDAG &DAG, unsigned NewOp) {
13039   SDLoc dl(Node);
13040   assert (Node->getValueType(0) == MVT::i64 &&
13041           "Only know how to expand i64 atomics");
13042
13043   SDValue Chain = Node->getOperand(0);
13044   SDValue In1 = Node->getOperand(1);
13045   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13046                              Node->getOperand(2), DAG.getIntPtrConstant(0));
13047   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
13048                              Node->getOperand(2), DAG.getIntPtrConstant(1));
13049   SDValue Ops[] = { Chain, In1, In2L, In2H };
13050   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13051   SDValue Result =
13052     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
13053                             cast<MemSDNode>(Node)->getMemOperand());
13054   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
13055   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
13056   Results.push_back(Result.getValue(2));
13057 }
13058
13059 /// ReplaceNodeResults - Replace a node with an illegal result type
13060 /// with a new node built out of custom code.
13061 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
13062                                            SmallVectorImpl<SDValue>&Results,
13063                                            SelectionDAG &DAG) const {
13064   SDLoc dl(N);
13065   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13066   switch (N->getOpcode()) {
13067   default:
13068     llvm_unreachable("Do not know how to custom type legalize this operation!");
13069   case ISD::SIGN_EXTEND_INREG:
13070   case ISD::ADDC:
13071   case ISD::ADDE:
13072   case ISD::SUBC:
13073   case ISD::SUBE:
13074     // We don't want to expand or promote these.
13075     return;
13076   case ISD::FP_TO_SINT:
13077   case ISD::FP_TO_UINT: {
13078     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
13079
13080     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
13081       return;
13082
13083     std::pair<SDValue,SDValue> Vals =
13084         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
13085     SDValue FIST = Vals.first, StackSlot = Vals.second;
13086     if (FIST.getNode() != 0) {
13087       EVT VT = N->getValueType(0);
13088       // Return a load from the stack slot.
13089       if (StackSlot.getNode() != 0)
13090         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
13091                                       MachinePointerInfo(),
13092                                       false, false, false, 0));
13093       else
13094         Results.push_back(FIST);
13095     }
13096     return;
13097   }
13098   case ISD::UINT_TO_FP: {
13099     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
13100     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
13101         N->getValueType(0) != MVT::v2f32)
13102       return;
13103     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
13104                                  N->getOperand(0));
13105     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
13106                                      MVT::f64);
13107     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
13108     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
13109                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
13110     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
13111     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
13112     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
13113     return;
13114   }
13115   case ISD::FP_ROUND: {
13116     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
13117         return;
13118     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
13119     Results.push_back(V);
13120     return;
13121   }
13122   case ISD::READCYCLECOUNTER: {
13123     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13124     SDValue TheChain = N->getOperand(0);
13125     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
13126     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
13127                                      rd.getValue(1));
13128     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
13129                                      eax.getValue(2));
13130     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13131     SDValue Ops[] = { eax, edx };
13132     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
13133                                   array_lengthof(Ops)));
13134     Results.push_back(edx.getValue(1));
13135     return;
13136   }
13137   case ISD::ATOMIC_CMP_SWAP: {
13138     EVT T = N->getValueType(0);
13139     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13140     bool Regs64bit = T == MVT::i128;
13141     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13142     SDValue cpInL, cpInH;
13143     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13144                         DAG.getConstant(0, HalfT));
13145     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13146                         DAG.getConstant(1, HalfT));
13147     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13148                              Regs64bit ? X86::RAX : X86::EAX,
13149                              cpInL, SDValue());
13150     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13151                              Regs64bit ? X86::RDX : X86::EDX,
13152                              cpInH, cpInL.getValue(1));
13153     SDValue swapInL, swapInH;
13154     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13155                           DAG.getConstant(0, HalfT));
13156     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13157                           DAG.getConstant(1, HalfT));
13158     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13159                                Regs64bit ? X86::RBX : X86::EBX,
13160                                swapInL, cpInH.getValue(1));
13161     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13162                                Regs64bit ? X86::RCX : X86::ECX,
13163                                swapInH, swapInL.getValue(1));
13164     SDValue Ops[] = { swapInH.getValue(0),
13165                       N->getOperand(1),
13166                       swapInH.getValue(1) };
13167     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13168     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13169     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13170                                   X86ISD::LCMPXCHG8_DAG;
13171     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13172                                              Ops, array_lengthof(Ops), T, MMO);
13173     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13174                                         Regs64bit ? X86::RAX : X86::EAX,
13175                                         HalfT, Result.getValue(1));
13176     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13177                                         Regs64bit ? X86::RDX : X86::EDX,
13178                                         HalfT, cpOutL.getValue(2));
13179     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13180     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13181     Results.push_back(cpOutH.getValue(1));
13182     return;
13183   }
13184   case ISD::ATOMIC_LOAD_ADD:
13185   case ISD::ATOMIC_LOAD_AND:
13186   case ISD::ATOMIC_LOAD_NAND:
13187   case ISD::ATOMIC_LOAD_OR:
13188   case ISD::ATOMIC_LOAD_SUB:
13189   case ISD::ATOMIC_LOAD_XOR:
13190   case ISD::ATOMIC_LOAD_MAX:
13191   case ISD::ATOMIC_LOAD_MIN:
13192   case ISD::ATOMIC_LOAD_UMAX:
13193   case ISD::ATOMIC_LOAD_UMIN:
13194   case ISD::ATOMIC_SWAP: {
13195     unsigned Opc;
13196     switch (N->getOpcode()) {
13197     default: llvm_unreachable("Unexpected opcode");
13198     case ISD::ATOMIC_LOAD_ADD:
13199       Opc = X86ISD::ATOMADD64_DAG;
13200       break;
13201     case ISD::ATOMIC_LOAD_AND:
13202       Opc = X86ISD::ATOMAND64_DAG;
13203       break;
13204     case ISD::ATOMIC_LOAD_NAND:
13205       Opc = X86ISD::ATOMNAND64_DAG;
13206       break;
13207     case ISD::ATOMIC_LOAD_OR:
13208       Opc = X86ISD::ATOMOR64_DAG;
13209       break;
13210     case ISD::ATOMIC_LOAD_SUB:
13211       Opc = X86ISD::ATOMSUB64_DAG;
13212       break;
13213     case ISD::ATOMIC_LOAD_XOR:
13214       Opc = X86ISD::ATOMXOR64_DAG;
13215       break;
13216     case ISD::ATOMIC_LOAD_MAX:
13217       Opc = X86ISD::ATOMMAX64_DAG;
13218       break;
13219     case ISD::ATOMIC_LOAD_MIN:
13220       Opc = X86ISD::ATOMMIN64_DAG;
13221       break;
13222     case ISD::ATOMIC_LOAD_UMAX:
13223       Opc = X86ISD::ATOMUMAX64_DAG;
13224       break;
13225     case ISD::ATOMIC_LOAD_UMIN:
13226       Opc = X86ISD::ATOMUMIN64_DAG;
13227       break;
13228     case ISD::ATOMIC_SWAP:
13229       Opc = X86ISD::ATOMSWAP64_DAG;
13230       break;
13231     }
13232     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13233     return;
13234   }
13235   case ISD::ATOMIC_LOAD:
13236     ReplaceATOMIC_LOAD(N, Results, DAG);
13237   }
13238 }
13239
13240 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13241   switch (Opcode) {
13242   default: return NULL;
13243   case X86ISD::BSF:                return "X86ISD::BSF";
13244   case X86ISD::BSR:                return "X86ISD::BSR";
13245   case X86ISD::SHLD:               return "X86ISD::SHLD";
13246   case X86ISD::SHRD:               return "X86ISD::SHRD";
13247   case X86ISD::FAND:               return "X86ISD::FAND";
13248   case X86ISD::FANDN:              return "X86ISD::FANDN";
13249   case X86ISD::FOR:                return "X86ISD::FOR";
13250   case X86ISD::FXOR:               return "X86ISD::FXOR";
13251   case X86ISD::FSRL:               return "X86ISD::FSRL";
13252   case X86ISD::FILD:               return "X86ISD::FILD";
13253   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13254   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13255   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13256   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13257   case X86ISD::FLD:                return "X86ISD::FLD";
13258   case X86ISD::FST:                return "X86ISD::FST";
13259   case X86ISD::CALL:               return "X86ISD::CALL";
13260   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13261   case X86ISD::BT:                 return "X86ISD::BT";
13262   case X86ISD::CMP:                return "X86ISD::CMP";
13263   case X86ISD::COMI:               return "X86ISD::COMI";
13264   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13265   case X86ISD::CMPM:               return "X86ISD::CMPM";
13266   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
13267   case X86ISD::SETCC:              return "X86ISD::SETCC";
13268   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13269   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
13270   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
13271   case X86ISD::CMOV:               return "X86ISD::CMOV";
13272   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13273   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13274   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13275   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13276   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13277   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13278   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13279   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13280   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13281   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13282   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13283   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13284   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13285   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13286   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13287   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13288   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13289   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13290   case X86ISD::HADD:               return "X86ISD::HADD";
13291   case X86ISD::HSUB:               return "X86ISD::HSUB";
13292   case X86ISD::FHADD:              return "X86ISD::FHADD";
13293   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13294   case X86ISD::UMAX:               return "X86ISD::UMAX";
13295   case X86ISD::UMIN:               return "X86ISD::UMIN";
13296   case X86ISD::SMAX:               return "X86ISD::SMAX";
13297   case X86ISD::SMIN:               return "X86ISD::SMIN";
13298   case X86ISD::FMAX:               return "X86ISD::FMAX";
13299   case X86ISD::FMIN:               return "X86ISD::FMIN";
13300   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13301   case X86ISD::FMINC:              return "X86ISD::FMINC";
13302   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13303   case X86ISD::FRCP:               return "X86ISD::FRCP";
13304   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13305   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13306   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13307   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13308   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13309   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13310   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13311   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13312   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13313   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13314   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13315   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13316   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13317   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13318   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13319   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13320   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13321   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13322   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13323   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13324   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13325   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13326   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13327   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13328   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13329   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13330   case X86ISD::VSHL:               return "X86ISD::VSHL";
13331   case X86ISD::VSRL:               return "X86ISD::VSRL";
13332   case X86ISD::VSRA:               return "X86ISD::VSRA";
13333   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13334   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13335   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13336   case X86ISD::CMPP:               return "X86ISD::CMPP";
13337   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13338   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13339   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
13340   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
13341   case X86ISD::ADD:                return "X86ISD::ADD";
13342   case X86ISD::SUB:                return "X86ISD::SUB";
13343   case X86ISD::ADC:                return "X86ISD::ADC";
13344   case X86ISD::SBB:                return "X86ISD::SBB";
13345   case X86ISD::SMUL:               return "X86ISD::SMUL";
13346   case X86ISD::UMUL:               return "X86ISD::UMUL";
13347   case X86ISD::INC:                return "X86ISD::INC";
13348   case X86ISD::DEC:                return "X86ISD::DEC";
13349   case X86ISD::OR:                 return "X86ISD::OR";
13350   case X86ISD::XOR:                return "X86ISD::XOR";
13351   case X86ISD::AND:                return "X86ISD::AND";
13352   case X86ISD::BLSI:               return "X86ISD::BLSI";
13353   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13354   case X86ISD::BLSR:               return "X86ISD::BLSR";
13355   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13356   case X86ISD::PTEST:              return "X86ISD::PTEST";
13357   case X86ISD::TESTP:              return "X86ISD::TESTP";
13358   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13359   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13360   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13361   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13362   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
13363   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
13364   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
13365   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
13366   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
13367   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
13368   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
13369   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
13370   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
13371   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
13372   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
13373   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
13374   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
13375   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
13376   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
13377   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
13378   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
13379   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
13380   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
13381   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
13382   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
13383   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13384   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
13385   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
13386   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
13387   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
13388   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
13389   case X86ISD::SAHF:               return "X86ISD::SAHF";
13390   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
13391   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
13392   case X86ISD::FMADD:              return "X86ISD::FMADD";
13393   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
13394   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
13395   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
13396   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
13397   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
13398   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
13399   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
13400   case X86ISD::XTEST:              return "X86ISD::XTEST";
13401   }
13402 }
13403
13404 // isLegalAddressingMode - Return true if the addressing mode represented
13405 // by AM is legal for this target, for a load/store of the specified type.
13406 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13407                                               Type *Ty) const {
13408   // X86 supports extremely general addressing modes.
13409   CodeModel::Model M = getTargetMachine().getCodeModel();
13410   Reloc::Model R = getTargetMachine().getRelocationModel();
13411
13412   // X86 allows a sign-extended 32-bit immediate field as a displacement.
13413   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13414     return false;
13415
13416   if (AM.BaseGV) {
13417     unsigned GVFlags =
13418       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13419
13420     // If a reference to this global requires an extra load, we can't fold it.
13421     if (isGlobalStubReference(GVFlags))
13422       return false;
13423
13424     // If BaseGV requires a register for the PIC base, we cannot also have a
13425     // BaseReg specified.
13426     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13427       return false;
13428
13429     // If lower 4G is not available, then we must use rip-relative addressing.
13430     if ((M != CodeModel::Small || R != Reloc::Static) &&
13431         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13432       return false;
13433   }
13434
13435   switch (AM.Scale) {
13436   case 0:
13437   case 1:
13438   case 2:
13439   case 4:
13440   case 8:
13441     // These scales always work.
13442     break;
13443   case 3:
13444   case 5:
13445   case 9:
13446     // These scales are formed with basereg+scalereg.  Only accept if there is
13447     // no basereg yet.
13448     if (AM.HasBaseReg)
13449       return false;
13450     break;
13451   default:  // Other stuff never works.
13452     return false;
13453   }
13454
13455   return true;
13456 }
13457
13458 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13459   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13460     return false;
13461   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13462   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13463   return NumBits1 > NumBits2;
13464 }
13465
13466 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
13467   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13468     return false;
13469
13470   if (!isTypeLegal(EVT::getEVT(Ty1)))
13471     return false;
13472
13473   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
13474
13475   // Assuming the caller doesn't have a zeroext or signext return parameter,
13476   // truncation all the way down to i1 is valid.
13477   return true;
13478 }
13479
13480 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13481   return isInt<32>(Imm);
13482 }
13483
13484 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13485   // Can also use sub to handle negated immediates.
13486   return isInt<32>(Imm);
13487 }
13488
13489 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13490   if (!VT1.isInteger() || !VT2.isInteger())
13491     return false;
13492   unsigned NumBits1 = VT1.getSizeInBits();
13493   unsigned NumBits2 = VT2.getSizeInBits();
13494   return NumBits1 > NumBits2;
13495 }
13496
13497 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13498   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13499   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
13500 }
13501
13502 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
13503   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13504   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
13505 }
13506
13507 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13508   EVT VT1 = Val.getValueType();
13509   if (isZExtFree(VT1, VT2))
13510     return true;
13511
13512   if (Val.getOpcode() != ISD::LOAD)
13513     return false;
13514
13515   if (!VT1.isSimple() || !VT1.isInteger() ||
13516       !VT2.isSimple() || !VT2.isInteger())
13517     return false;
13518
13519   switch (VT1.getSimpleVT().SimpleTy) {
13520   default: break;
13521   case MVT::i8:
13522   case MVT::i16:
13523   case MVT::i32:
13524     // X86 has 8, 16, and 32-bit zero-extending loads.
13525     return true;
13526   }
13527
13528   return false;
13529 }
13530
13531 bool
13532 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13533   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
13534     return false;
13535
13536   VT = VT.getScalarType();
13537
13538   if (!VT.isSimple())
13539     return false;
13540
13541   switch (VT.getSimpleVT().SimpleTy) {
13542   case MVT::f32:
13543   case MVT::f64:
13544     return true;
13545   default:
13546     break;
13547   }
13548
13549   return false;
13550 }
13551
13552 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
13553   // i16 instructions are longer (0x66 prefix) and potentially slower.
13554   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
13555 }
13556
13557 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13558 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13559 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13560 /// are assumed to be legal.
13561 bool
13562 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13563                                       EVT VT) const {
13564   if (!VT.isSimple())
13565     return false;
13566
13567   MVT SVT = VT.getSimpleVT();
13568
13569   // Very little shuffling can be done for 64-bit vectors right now.
13570   if (VT.getSizeInBits() == 64)
13571     return false;
13572
13573   // FIXME: pshufb, blends, shifts.
13574   return (SVT.getVectorNumElements() == 2 ||
13575           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13576           isMOVLMask(M, SVT) ||
13577           isSHUFPMask(M, SVT, Subtarget->hasFp256()) ||
13578           isPSHUFDMask(M, SVT) ||
13579           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
13580           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
13581           isPALIGNRMask(M, SVT, Subtarget) ||
13582           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
13583           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
13584           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
13585           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
13586 }
13587
13588 bool
13589 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13590                                           EVT VT) const {
13591   if (!VT.isSimple())
13592     return false;
13593
13594   MVT SVT = VT.getSimpleVT();
13595   unsigned NumElts = SVT.getVectorNumElements();
13596   // FIXME: This collection of masks seems suspect.
13597   if (NumElts == 2)
13598     return true;
13599   if (NumElts == 4 && SVT.is128BitVector()) {
13600     return (isMOVLMask(Mask, SVT)  ||
13601             isCommutedMOVLMask(Mask, SVT, true) ||
13602             isSHUFPMask(Mask, SVT, Subtarget->hasFp256()) ||
13603             isSHUFPMask(Mask, SVT, Subtarget->hasFp256(), /* Commuted */ true));
13604   }
13605   return false;
13606 }
13607
13608 //===----------------------------------------------------------------------===//
13609 //                           X86 Scheduler Hooks
13610 //===----------------------------------------------------------------------===//
13611
13612 /// Utility function to emit xbegin specifying the start of an RTM region.
13613 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13614                                      const TargetInstrInfo *TII) {
13615   DebugLoc DL = MI->getDebugLoc();
13616
13617   const BasicBlock *BB = MBB->getBasicBlock();
13618   MachineFunction::iterator I = MBB;
13619   ++I;
13620
13621   // For the v = xbegin(), we generate
13622   //
13623   // thisMBB:
13624   //  xbegin sinkMBB
13625   //
13626   // mainMBB:
13627   //  eax = -1
13628   //
13629   // sinkMBB:
13630   //  v = eax
13631
13632   MachineBasicBlock *thisMBB = MBB;
13633   MachineFunction *MF = MBB->getParent();
13634   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13635   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13636   MF->insert(I, mainMBB);
13637   MF->insert(I, sinkMBB);
13638
13639   // Transfer the remainder of BB and its successor edges to sinkMBB.
13640   sinkMBB->splice(sinkMBB->begin(), MBB,
13641                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13642   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13643
13644   // thisMBB:
13645   //  xbegin sinkMBB
13646   //  # fallthrough to mainMBB
13647   //  # abortion to sinkMBB
13648   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13649   thisMBB->addSuccessor(mainMBB);
13650   thisMBB->addSuccessor(sinkMBB);
13651
13652   // mainMBB:
13653   //  EAX = -1
13654   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13655   mainMBB->addSuccessor(sinkMBB);
13656
13657   // sinkMBB:
13658   // EAX is live into the sinkMBB
13659   sinkMBB->addLiveIn(X86::EAX);
13660   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13661           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13662     .addReg(X86::EAX);
13663
13664   MI->eraseFromParent();
13665   return sinkMBB;
13666 }
13667
13668 // Get CMPXCHG opcode for the specified data type.
13669 static unsigned getCmpXChgOpcode(EVT VT) {
13670   switch (VT.getSimpleVT().SimpleTy) {
13671   case MVT::i8:  return X86::LCMPXCHG8;
13672   case MVT::i16: return X86::LCMPXCHG16;
13673   case MVT::i32: return X86::LCMPXCHG32;
13674   case MVT::i64: return X86::LCMPXCHG64;
13675   default:
13676     break;
13677   }
13678   llvm_unreachable("Invalid operand size!");
13679 }
13680
13681 // Get LOAD opcode for the specified data type.
13682 static unsigned getLoadOpcode(EVT VT) {
13683   switch (VT.getSimpleVT().SimpleTy) {
13684   case MVT::i8:  return X86::MOV8rm;
13685   case MVT::i16: return X86::MOV16rm;
13686   case MVT::i32: return X86::MOV32rm;
13687   case MVT::i64: return X86::MOV64rm;
13688   default:
13689     break;
13690   }
13691   llvm_unreachable("Invalid operand size!");
13692 }
13693
13694 // Get opcode of the non-atomic one from the specified atomic instruction.
13695 static unsigned getNonAtomicOpcode(unsigned Opc) {
13696   switch (Opc) {
13697   case X86::ATOMAND8:  return X86::AND8rr;
13698   case X86::ATOMAND16: return X86::AND16rr;
13699   case X86::ATOMAND32: return X86::AND32rr;
13700   case X86::ATOMAND64: return X86::AND64rr;
13701   case X86::ATOMOR8:   return X86::OR8rr;
13702   case X86::ATOMOR16:  return X86::OR16rr;
13703   case X86::ATOMOR32:  return X86::OR32rr;
13704   case X86::ATOMOR64:  return X86::OR64rr;
13705   case X86::ATOMXOR8:  return X86::XOR8rr;
13706   case X86::ATOMXOR16: return X86::XOR16rr;
13707   case X86::ATOMXOR32: return X86::XOR32rr;
13708   case X86::ATOMXOR64: return X86::XOR64rr;
13709   }
13710   llvm_unreachable("Unhandled atomic-load-op opcode!");
13711 }
13712
13713 // Get opcode of the non-atomic one from the specified atomic instruction with
13714 // extra opcode.
13715 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13716                                                unsigned &ExtraOpc) {
13717   switch (Opc) {
13718   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13719   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13720   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13721   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13722   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13723   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13724   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13725   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13726   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13727   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13728   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13729   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13730   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13731   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13732   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13733   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13734   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13735   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13736   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13737   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13738   }
13739   llvm_unreachable("Unhandled atomic-load-op opcode!");
13740 }
13741
13742 // Get opcode of the non-atomic one from the specified atomic instruction for
13743 // 64-bit data type on 32-bit target.
13744 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13745   switch (Opc) {
13746   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13747   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13748   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13749   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13750   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13751   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13752   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13753   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13754   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13755   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13756   }
13757   llvm_unreachable("Unhandled atomic-load-op opcode!");
13758 }
13759
13760 // Get opcode of the non-atomic one from the specified atomic instruction for
13761 // 64-bit data type on 32-bit target with extra opcode.
13762 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13763                                                    unsigned &HiOpc,
13764                                                    unsigned &ExtraOpc) {
13765   switch (Opc) {
13766   case X86::ATOMNAND6432:
13767     ExtraOpc = X86::NOT32r;
13768     HiOpc = X86::AND32rr;
13769     return X86::AND32rr;
13770   }
13771   llvm_unreachable("Unhandled atomic-load-op opcode!");
13772 }
13773
13774 // Get pseudo CMOV opcode from the specified data type.
13775 static unsigned getPseudoCMOVOpc(EVT VT) {
13776   switch (VT.getSimpleVT().SimpleTy) {
13777   case MVT::i8:  return X86::CMOV_GR8;
13778   case MVT::i16: return X86::CMOV_GR16;
13779   case MVT::i32: return X86::CMOV_GR32;
13780   default:
13781     break;
13782   }
13783   llvm_unreachable("Unknown CMOV opcode!");
13784 }
13785
13786 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13787 // They will be translated into a spin-loop or compare-exchange loop from
13788 //
13789 //    ...
13790 //    dst = atomic-fetch-op MI.addr, MI.val
13791 //    ...
13792 //
13793 // to
13794 //
13795 //    ...
13796 //    t1 = LOAD MI.addr
13797 // loop:
13798 //    t4 = phi(t1, t3 / loop)
13799 //    t2 = OP MI.val, t4
13800 //    EAX = t4
13801 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13802 //    t3 = EAX
13803 //    JNE loop
13804 // sink:
13805 //    dst = t3
13806 //    ...
13807 MachineBasicBlock *
13808 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13809                                        MachineBasicBlock *MBB) const {
13810   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13811   DebugLoc DL = MI->getDebugLoc();
13812
13813   MachineFunction *MF = MBB->getParent();
13814   MachineRegisterInfo &MRI = MF->getRegInfo();
13815
13816   const BasicBlock *BB = MBB->getBasicBlock();
13817   MachineFunction::iterator I = MBB;
13818   ++I;
13819
13820   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13821          "Unexpected number of operands");
13822
13823   assert(MI->hasOneMemOperand() &&
13824          "Expected atomic-load-op to have one memoperand");
13825
13826   // Memory Reference
13827   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13828   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13829
13830   unsigned DstReg, SrcReg;
13831   unsigned MemOpndSlot;
13832
13833   unsigned CurOp = 0;
13834
13835   DstReg = MI->getOperand(CurOp++).getReg();
13836   MemOpndSlot = CurOp;
13837   CurOp += X86::AddrNumOperands;
13838   SrcReg = MI->getOperand(CurOp++).getReg();
13839
13840   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13841   MVT::SimpleValueType VT = *RC->vt_begin();
13842   unsigned t1 = MRI.createVirtualRegister(RC);
13843   unsigned t2 = MRI.createVirtualRegister(RC);
13844   unsigned t3 = MRI.createVirtualRegister(RC);
13845   unsigned t4 = MRI.createVirtualRegister(RC);
13846   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13847
13848   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13849   unsigned LOADOpc = getLoadOpcode(VT);
13850
13851   // For the atomic load-arith operator, we generate
13852   //
13853   //  thisMBB:
13854   //    t1 = LOAD [MI.addr]
13855   //  mainMBB:
13856   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13857   //    t1 = OP MI.val, EAX
13858   //    EAX = t4
13859   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13860   //    t3 = EAX
13861   //    JNE mainMBB
13862   //  sinkMBB:
13863   //    dst = t3
13864
13865   MachineBasicBlock *thisMBB = MBB;
13866   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13867   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13868   MF->insert(I, mainMBB);
13869   MF->insert(I, sinkMBB);
13870
13871   MachineInstrBuilder MIB;
13872
13873   // Transfer the remainder of BB and its successor edges to sinkMBB.
13874   sinkMBB->splice(sinkMBB->begin(), MBB,
13875                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13876   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13877
13878   // thisMBB:
13879   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13880   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13881     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13882     if (NewMO.isReg())
13883       NewMO.setIsKill(false);
13884     MIB.addOperand(NewMO);
13885   }
13886   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13887     unsigned flags = (*MMOI)->getFlags();
13888     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13889     MachineMemOperand *MMO =
13890       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13891                                (*MMOI)->getSize(),
13892                                (*MMOI)->getBaseAlignment(),
13893                                (*MMOI)->getTBAAInfo(),
13894                                (*MMOI)->getRanges());
13895     MIB.addMemOperand(MMO);
13896   }
13897
13898   thisMBB->addSuccessor(mainMBB);
13899
13900   // mainMBB:
13901   MachineBasicBlock *origMainMBB = mainMBB;
13902
13903   // Add a PHI.
13904   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13905                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13906
13907   unsigned Opc = MI->getOpcode();
13908   switch (Opc) {
13909   default:
13910     llvm_unreachable("Unhandled atomic-load-op opcode!");
13911   case X86::ATOMAND8:
13912   case X86::ATOMAND16:
13913   case X86::ATOMAND32:
13914   case X86::ATOMAND64:
13915   case X86::ATOMOR8:
13916   case X86::ATOMOR16:
13917   case X86::ATOMOR32:
13918   case X86::ATOMOR64:
13919   case X86::ATOMXOR8:
13920   case X86::ATOMXOR16:
13921   case X86::ATOMXOR32:
13922   case X86::ATOMXOR64: {
13923     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13924     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13925       .addReg(t4);
13926     break;
13927   }
13928   case X86::ATOMNAND8:
13929   case X86::ATOMNAND16:
13930   case X86::ATOMNAND32:
13931   case X86::ATOMNAND64: {
13932     unsigned Tmp = MRI.createVirtualRegister(RC);
13933     unsigned NOTOpc;
13934     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13935     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13936       .addReg(t4);
13937     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13938     break;
13939   }
13940   case X86::ATOMMAX8:
13941   case X86::ATOMMAX16:
13942   case X86::ATOMMAX32:
13943   case X86::ATOMMAX64:
13944   case X86::ATOMMIN8:
13945   case X86::ATOMMIN16:
13946   case X86::ATOMMIN32:
13947   case X86::ATOMMIN64:
13948   case X86::ATOMUMAX8:
13949   case X86::ATOMUMAX16:
13950   case X86::ATOMUMAX32:
13951   case X86::ATOMUMAX64:
13952   case X86::ATOMUMIN8:
13953   case X86::ATOMUMIN16:
13954   case X86::ATOMUMIN32:
13955   case X86::ATOMUMIN64: {
13956     unsigned CMPOpc;
13957     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13958
13959     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13960       .addReg(SrcReg)
13961       .addReg(t4);
13962
13963     if (Subtarget->hasCMov()) {
13964       if (VT != MVT::i8) {
13965         // Native support
13966         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13967           .addReg(SrcReg)
13968           .addReg(t4);
13969       } else {
13970         // Promote i8 to i32 to use CMOV32
13971         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13972         const TargetRegisterClass *RC32 =
13973           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13974         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13975         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13976         unsigned Tmp = MRI.createVirtualRegister(RC32);
13977
13978         unsigned Undef = MRI.createVirtualRegister(RC32);
13979         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13980
13981         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13982           .addReg(Undef)
13983           .addReg(SrcReg)
13984           .addImm(X86::sub_8bit);
13985         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13986           .addReg(Undef)
13987           .addReg(t4)
13988           .addImm(X86::sub_8bit);
13989
13990         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13991           .addReg(SrcReg32)
13992           .addReg(AccReg32);
13993
13994         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13995           .addReg(Tmp, 0, X86::sub_8bit);
13996       }
13997     } else {
13998       // Use pseudo select and lower them.
13999       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
14000              "Invalid atomic-load-op transformation!");
14001       unsigned SelOpc = getPseudoCMOVOpc(VT);
14002       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
14003       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
14004       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
14005               .addReg(SrcReg).addReg(t4)
14006               .addImm(CC);
14007       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14008       // Replace the original PHI node as mainMBB is changed after CMOV
14009       // lowering.
14010       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
14011         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
14012       Phi->eraseFromParent();
14013     }
14014     break;
14015   }
14016   }
14017
14018   // Copy PhyReg back from virtual register.
14019   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
14020     .addReg(t4);
14021
14022   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14023   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14024     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14025     if (NewMO.isReg())
14026       NewMO.setIsKill(false);
14027     MIB.addOperand(NewMO);
14028   }
14029   MIB.addReg(t2);
14030   MIB.setMemRefs(MMOBegin, MMOEnd);
14031
14032   // Copy PhyReg back to virtual register.
14033   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
14034     .addReg(PhyReg);
14035
14036   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14037
14038   mainMBB->addSuccessor(origMainMBB);
14039   mainMBB->addSuccessor(sinkMBB);
14040
14041   // sinkMBB:
14042   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14043           TII->get(TargetOpcode::COPY), DstReg)
14044     .addReg(t3);
14045
14046   MI->eraseFromParent();
14047   return sinkMBB;
14048 }
14049
14050 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
14051 // instructions. They will be translated into a spin-loop or compare-exchange
14052 // loop from
14053 //
14054 //    ...
14055 //    dst = atomic-fetch-op MI.addr, MI.val
14056 //    ...
14057 //
14058 // to
14059 //
14060 //    ...
14061 //    t1L = LOAD [MI.addr + 0]
14062 //    t1H = LOAD [MI.addr + 4]
14063 // loop:
14064 //    t4L = phi(t1L, t3L / loop)
14065 //    t4H = phi(t1H, t3H / loop)
14066 //    t2L = OP MI.val.lo, t4L
14067 //    t2H = OP MI.val.hi, t4H
14068 //    EAX = t4L
14069 //    EDX = t4H
14070 //    EBX = t2L
14071 //    ECX = t2H
14072 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14073 //    t3L = EAX
14074 //    t3H = EDX
14075 //    JNE loop
14076 // sink:
14077 //    dstL = t3L
14078 //    dstH = t3H
14079 //    ...
14080 MachineBasicBlock *
14081 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
14082                                            MachineBasicBlock *MBB) const {
14083   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14084   DebugLoc DL = MI->getDebugLoc();
14085
14086   MachineFunction *MF = MBB->getParent();
14087   MachineRegisterInfo &MRI = MF->getRegInfo();
14088
14089   const BasicBlock *BB = MBB->getBasicBlock();
14090   MachineFunction::iterator I = MBB;
14091   ++I;
14092
14093   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
14094          "Unexpected number of operands");
14095
14096   assert(MI->hasOneMemOperand() &&
14097          "Expected atomic-load-op32 to have one memoperand");
14098
14099   // Memory Reference
14100   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14101   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14102
14103   unsigned DstLoReg, DstHiReg;
14104   unsigned SrcLoReg, SrcHiReg;
14105   unsigned MemOpndSlot;
14106
14107   unsigned CurOp = 0;
14108
14109   DstLoReg = MI->getOperand(CurOp++).getReg();
14110   DstHiReg = MI->getOperand(CurOp++).getReg();
14111   MemOpndSlot = CurOp;
14112   CurOp += X86::AddrNumOperands;
14113   SrcLoReg = MI->getOperand(CurOp++).getReg();
14114   SrcHiReg = MI->getOperand(CurOp++).getReg();
14115
14116   const TargetRegisterClass *RC = &X86::GR32RegClass;
14117   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
14118
14119   unsigned t1L = MRI.createVirtualRegister(RC);
14120   unsigned t1H = MRI.createVirtualRegister(RC);
14121   unsigned t2L = MRI.createVirtualRegister(RC);
14122   unsigned t2H = MRI.createVirtualRegister(RC);
14123   unsigned t3L = MRI.createVirtualRegister(RC);
14124   unsigned t3H = MRI.createVirtualRegister(RC);
14125   unsigned t4L = MRI.createVirtualRegister(RC);
14126   unsigned t4H = MRI.createVirtualRegister(RC);
14127
14128   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
14129   unsigned LOADOpc = X86::MOV32rm;
14130
14131   // For the atomic load-arith operator, we generate
14132   //
14133   //  thisMBB:
14134   //    t1L = LOAD [MI.addr + 0]
14135   //    t1H = LOAD [MI.addr + 4]
14136   //  mainMBB:
14137   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
14138   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
14139   //    t2L = OP MI.val.lo, t4L
14140   //    t2H = OP MI.val.hi, t4H
14141   //    EBX = t2L
14142   //    ECX = t2H
14143   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
14144   //    t3L = EAX
14145   //    t3H = EDX
14146   //    JNE loop
14147   //  sinkMBB:
14148   //    dstL = t3L
14149   //    dstH = t3H
14150
14151   MachineBasicBlock *thisMBB = MBB;
14152   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14153   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14154   MF->insert(I, mainMBB);
14155   MF->insert(I, sinkMBB);
14156
14157   MachineInstrBuilder MIB;
14158
14159   // Transfer the remainder of BB and its successor edges to sinkMBB.
14160   sinkMBB->splice(sinkMBB->begin(), MBB,
14161                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14162   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14163
14164   // thisMBB:
14165   // Lo
14166   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14167   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14168     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14169     if (NewMO.isReg())
14170       NewMO.setIsKill(false);
14171     MIB.addOperand(NewMO);
14172   }
14173   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14174     unsigned flags = (*MMOI)->getFlags();
14175     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14176     MachineMemOperand *MMO =
14177       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14178                                (*MMOI)->getSize(),
14179                                (*MMOI)->getBaseAlignment(),
14180                                (*MMOI)->getTBAAInfo(),
14181                                (*MMOI)->getRanges());
14182     MIB.addMemOperand(MMO);
14183   };
14184   MachineInstr *LowMI = MIB;
14185
14186   // Hi
14187   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14188   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14189     if (i == X86::AddrDisp) {
14190       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14191     } else {
14192       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14193       if (NewMO.isReg())
14194         NewMO.setIsKill(false);
14195       MIB.addOperand(NewMO);
14196     }
14197   }
14198   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14199
14200   thisMBB->addSuccessor(mainMBB);
14201
14202   // mainMBB:
14203   MachineBasicBlock *origMainMBB = mainMBB;
14204
14205   // Add PHIs.
14206   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14207                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14208   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14209                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14210
14211   unsigned Opc = MI->getOpcode();
14212   switch (Opc) {
14213   default:
14214     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14215   case X86::ATOMAND6432:
14216   case X86::ATOMOR6432:
14217   case X86::ATOMXOR6432:
14218   case X86::ATOMADD6432:
14219   case X86::ATOMSUB6432: {
14220     unsigned HiOpc;
14221     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14222     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14223       .addReg(SrcLoReg);
14224     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14225       .addReg(SrcHiReg);
14226     break;
14227   }
14228   case X86::ATOMNAND6432: {
14229     unsigned HiOpc, NOTOpc;
14230     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14231     unsigned TmpL = MRI.createVirtualRegister(RC);
14232     unsigned TmpH = MRI.createVirtualRegister(RC);
14233     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14234       .addReg(t4L);
14235     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14236       .addReg(t4H);
14237     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14238     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14239     break;
14240   }
14241   case X86::ATOMMAX6432:
14242   case X86::ATOMMIN6432:
14243   case X86::ATOMUMAX6432:
14244   case X86::ATOMUMIN6432: {
14245     unsigned HiOpc;
14246     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14247     unsigned cL = MRI.createVirtualRegister(RC8);
14248     unsigned cH = MRI.createVirtualRegister(RC8);
14249     unsigned cL32 = MRI.createVirtualRegister(RC);
14250     unsigned cH32 = MRI.createVirtualRegister(RC);
14251     unsigned cc = MRI.createVirtualRegister(RC);
14252     // cl := cmp src_lo, lo
14253     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14254       .addReg(SrcLoReg).addReg(t4L);
14255     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14256     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14257     // ch := cmp src_hi, hi
14258     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14259       .addReg(SrcHiReg).addReg(t4H);
14260     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14261     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14262     // cc := if (src_hi == hi) ? cl : ch;
14263     if (Subtarget->hasCMov()) {
14264       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14265         .addReg(cH32).addReg(cL32);
14266     } else {
14267       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14268               .addReg(cH32).addReg(cL32)
14269               .addImm(X86::COND_E);
14270       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14271     }
14272     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14273     if (Subtarget->hasCMov()) {
14274       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14275         .addReg(SrcLoReg).addReg(t4L);
14276       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14277         .addReg(SrcHiReg).addReg(t4H);
14278     } else {
14279       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14280               .addReg(SrcLoReg).addReg(t4L)
14281               .addImm(X86::COND_NE);
14282       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14283       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14284       // 2nd CMOV lowering.
14285       mainMBB->addLiveIn(X86::EFLAGS);
14286       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14287               .addReg(SrcHiReg).addReg(t4H)
14288               .addImm(X86::COND_NE);
14289       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14290       // Replace the original PHI node as mainMBB is changed after CMOV
14291       // lowering.
14292       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14293         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14294       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14295         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14296       PhiL->eraseFromParent();
14297       PhiH->eraseFromParent();
14298     }
14299     break;
14300   }
14301   case X86::ATOMSWAP6432: {
14302     unsigned HiOpc;
14303     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14304     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14305     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14306     break;
14307   }
14308   }
14309
14310   // Copy EDX:EAX back from HiReg:LoReg
14311   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14312   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14313   // Copy ECX:EBX from t1H:t1L
14314   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14315   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14316
14317   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
14318   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14319     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14320     if (NewMO.isReg())
14321       NewMO.setIsKill(false);
14322     MIB.addOperand(NewMO);
14323   }
14324   MIB.setMemRefs(MMOBegin, MMOEnd);
14325
14326   // Copy EDX:EAX back to t3H:t3L
14327   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14328   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14329
14330   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14331
14332   mainMBB->addSuccessor(origMainMBB);
14333   mainMBB->addSuccessor(sinkMBB);
14334
14335   // sinkMBB:
14336   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14337           TII->get(TargetOpcode::COPY), DstLoReg)
14338     .addReg(t3L);
14339   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14340           TII->get(TargetOpcode::COPY), DstHiReg)
14341     .addReg(t3H);
14342
14343   MI->eraseFromParent();
14344   return sinkMBB;
14345 }
14346
14347 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14348 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14349 // in the .td file.
14350 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14351                                        const TargetInstrInfo *TII) {
14352   unsigned Opc;
14353   switch (MI->getOpcode()) {
14354   default: llvm_unreachable("illegal opcode!");
14355   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14356   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14357   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14358   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14359   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14360   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14361   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14362   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14363   }
14364
14365   DebugLoc dl = MI->getDebugLoc();
14366   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14367
14368   unsigned NumArgs = MI->getNumOperands();
14369   for (unsigned i = 1; i < NumArgs; ++i) {
14370     MachineOperand &Op = MI->getOperand(i);
14371     if (!(Op.isReg() && Op.isImplicit()))
14372       MIB.addOperand(Op);
14373   }
14374   if (MI->hasOneMemOperand())
14375     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14376
14377   BuildMI(*BB, MI, dl,
14378     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14379     .addReg(X86::XMM0);
14380
14381   MI->eraseFromParent();
14382   return BB;
14383 }
14384
14385 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14386 // defs in an instruction pattern
14387 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14388                                        const TargetInstrInfo *TII) {
14389   unsigned Opc;
14390   switch (MI->getOpcode()) {
14391   default: llvm_unreachable("illegal opcode!");
14392   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
14393   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14394   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
14395   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14396   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
14397   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14398   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
14399   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14400   }
14401
14402   DebugLoc dl = MI->getDebugLoc();
14403   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14404
14405   unsigned NumArgs = MI->getNumOperands(); // remove the results
14406   for (unsigned i = 1; i < NumArgs; ++i) {
14407     MachineOperand &Op = MI->getOperand(i);
14408     if (!(Op.isReg() && Op.isImplicit()))
14409       MIB.addOperand(Op);
14410   }
14411   if (MI->hasOneMemOperand())
14412     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14413
14414   BuildMI(*BB, MI, dl,
14415     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14416     .addReg(X86::ECX);
14417
14418   MI->eraseFromParent();
14419   return BB;
14420 }
14421
14422 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14423                                        const TargetInstrInfo *TII,
14424                                        const X86Subtarget* Subtarget) {
14425   DebugLoc dl = MI->getDebugLoc();
14426
14427   // Address into RAX/EAX, other two args into ECX, EDX.
14428   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14429   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14430   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14431   for (int i = 0; i < X86::AddrNumOperands; ++i)
14432     MIB.addOperand(MI->getOperand(i));
14433
14434   unsigned ValOps = X86::AddrNumOperands;
14435   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14436     .addReg(MI->getOperand(ValOps).getReg());
14437   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14438     .addReg(MI->getOperand(ValOps+1).getReg());
14439
14440   // The instruction doesn't actually take any operands though.
14441   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14442
14443   MI->eraseFromParent(); // The pseudo is gone now.
14444   return BB;
14445 }
14446
14447 MachineBasicBlock *
14448 X86TargetLowering::EmitVAARG64WithCustomInserter(
14449                    MachineInstr *MI,
14450                    MachineBasicBlock *MBB) const {
14451   // Emit va_arg instruction on X86-64.
14452
14453   // Operands to this pseudo-instruction:
14454   // 0  ) Output        : destination address (reg)
14455   // 1-5) Input         : va_list address (addr, i64mem)
14456   // 6  ) ArgSize       : Size (in bytes) of vararg type
14457   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14458   // 8  ) Align         : Alignment of type
14459   // 9  ) EFLAGS (implicit-def)
14460
14461   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14462   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14463
14464   unsigned DestReg = MI->getOperand(0).getReg();
14465   MachineOperand &Base = MI->getOperand(1);
14466   MachineOperand &Scale = MI->getOperand(2);
14467   MachineOperand &Index = MI->getOperand(3);
14468   MachineOperand &Disp = MI->getOperand(4);
14469   MachineOperand &Segment = MI->getOperand(5);
14470   unsigned ArgSize = MI->getOperand(6).getImm();
14471   unsigned ArgMode = MI->getOperand(7).getImm();
14472   unsigned Align = MI->getOperand(8).getImm();
14473
14474   // Memory Reference
14475   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14476   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14477   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14478
14479   // Machine Information
14480   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14481   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14482   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14483   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14484   DebugLoc DL = MI->getDebugLoc();
14485
14486   // struct va_list {
14487   //   i32   gp_offset
14488   //   i32   fp_offset
14489   //   i64   overflow_area (address)
14490   //   i64   reg_save_area (address)
14491   // }
14492   // sizeof(va_list) = 24
14493   // alignment(va_list) = 8
14494
14495   unsigned TotalNumIntRegs = 6;
14496   unsigned TotalNumXMMRegs = 8;
14497   bool UseGPOffset = (ArgMode == 1);
14498   bool UseFPOffset = (ArgMode == 2);
14499   unsigned MaxOffset = TotalNumIntRegs * 8 +
14500                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
14501
14502   /* Align ArgSize to a multiple of 8 */
14503   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
14504   bool NeedsAlign = (Align > 8);
14505
14506   MachineBasicBlock *thisMBB = MBB;
14507   MachineBasicBlock *overflowMBB;
14508   MachineBasicBlock *offsetMBB;
14509   MachineBasicBlock *endMBB;
14510
14511   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
14512   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
14513   unsigned OffsetReg = 0;
14514
14515   if (!UseGPOffset && !UseFPOffset) {
14516     // If we only pull from the overflow region, we don't create a branch.
14517     // We don't need to alter control flow.
14518     OffsetDestReg = 0; // unused
14519     OverflowDestReg = DestReg;
14520
14521     offsetMBB = NULL;
14522     overflowMBB = thisMBB;
14523     endMBB = thisMBB;
14524   } else {
14525     // First emit code to check if gp_offset (or fp_offset) is below the bound.
14526     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
14527     // If not, pull from overflow_area. (branch to overflowMBB)
14528     //
14529     //       thisMBB
14530     //         |     .
14531     //         |        .
14532     //     offsetMBB   overflowMBB
14533     //         |        .
14534     //         |     .
14535     //        endMBB
14536
14537     // Registers for the PHI in endMBB
14538     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
14539     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
14540
14541     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14542     MachineFunction *MF = MBB->getParent();
14543     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14544     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14545     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14546
14547     MachineFunction::iterator MBBIter = MBB;
14548     ++MBBIter;
14549
14550     // Insert the new basic blocks
14551     MF->insert(MBBIter, offsetMBB);
14552     MF->insert(MBBIter, overflowMBB);
14553     MF->insert(MBBIter, endMBB);
14554
14555     // Transfer the remainder of MBB and its successor edges to endMBB.
14556     endMBB->splice(endMBB->begin(), thisMBB,
14557                     llvm::next(MachineBasicBlock::iterator(MI)),
14558                     thisMBB->end());
14559     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
14560
14561     // Make offsetMBB and overflowMBB successors of thisMBB
14562     thisMBB->addSuccessor(offsetMBB);
14563     thisMBB->addSuccessor(overflowMBB);
14564
14565     // endMBB is a successor of both offsetMBB and overflowMBB
14566     offsetMBB->addSuccessor(endMBB);
14567     overflowMBB->addSuccessor(endMBB);
14568
14569     // Load the offset value into a register
14570     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14571     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14572       .addOperand(Base)
14573       .addOperand(Scale)
14574       .addOperand(Index)
14575       .addDisp(Disp, UseFPOffset ? 4 : 0)
14576       .addOperand(Segment)
14577       .setMemRefs(MMOBegin, MMOEnd);
14578
14579     // Check if there is enough room left to pull this argument.
14580     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14581       .addReg(OffsetReg)
14582       .addImm(MaxOffset + 8 - ArgSizeA8);
14583
14584     // Branch to "overflowMBB" if offset >= max
14585     // Fall through to "offsetMBB" otherwise
14586     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14587       .addMBB(overflowMBB);
14588   }
14589
14590   // In offsetMBB, emit code to use the reg_save_area.
14591   if (offsetMBB) {
14592     assert(OffsetReg != 0);
14593
14594     // Read the reg_save_area address.
14595     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14596     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14597       .addOperand(Base)
14598       .addOperand(Scale)
14599       .addOperand(Index)
14600       .addDisp(Disp, 16)
14601       .addOperand(Segment)
14602       .setMemRefs(MMOBegin, MMOEnd);
14603
14604     // Zero-extend the offset
14605     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14606       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14607         .addImm(0)
14608         .addReg(OffsetReg)
14609         .addImm(X86::sub_32bit);
14610
14611     // Add the offset to the reg_save_area to get the final address.
14612     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14613       .addReg(OffsetReg64)
14614       .addReg(RegSaveReg);
14615
14616     // Compute the offset for the next argument
14617     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14618     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14619       .addReg(OffsetReg)
14620       .addImm(UseFPOffset ? 16 : 8);
14621
14622     // Store it back into the va_list.
14623     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14624       .addOperand(Base)
14625       .addOperand(Scale)
14626       .addOperand(Index)
14627       .addDisp(Disp, UseFPOffset ? 4 : 0)
14628       .addOperand(Segment)
14629       .addReg(NextOffsetReg)
14630       .setMemRefs(MMOBegin, MMOEnd);
14631
14632     // Jump to endMBB
14633     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14634       .addMBB(endMBB);
14635   }
14636
14637   //
14638   // Emit code to use overflow area
14639   //
14640
14641   // Load the overflow_area address into a register.
14642   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14643   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14644     .addOperand(Base)
14645     .addOperand(Scale)
14646     .addOperand(Index)
14647     .addDisp(Disp, 8)
14648     .addOperand(Segment)
14649     .setMemRefs(MMOBegin, MMOEnd);
14650
14651   // If we need to align it, do so. Otherwise, just copy the address
14652   // to OverflowDestReg.
14653   if (NeedsAlign) {
14654     // Align the overflow address
14655     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14656     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14657
14658     // aligned_addr = (addr + (align-1)) & ~(align-1)
14659     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14660       .addReg(OverflowAddrReg)
14661       .addImm(Align-1);
14662
14663     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14664       .addReg(TmpReg)
14665       .addImm(~(uint64_t)(Align-1));
14666   } else {
14667     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14668       .addReg(OverflowAddrReg);
14669   }
14670
14671   // Compute the next overflow address after this argument.
14672   // (the overflow address should be kept 8-byte aligned)
14673   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14674   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14675     .addReg(OverflowDestReg)
14676     .addImm(ArgSizeA8);
14677
14678   // Store the new overflow address.
14679   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14680     .addOperand(Base)
14681     .addOperand(Scale)
14682     .addOperand(Index)
14683     .addDisp(Disp, 8)
14684     .addOperand(Segment)
14685     .addReg(NextAddrReg)
14686     .setMemRefs(MMOBegin, MMOEnd);
14687
14688   // If we branched, emit the PHI to the front of endMBB.
14689   if (offsetMBB) {
14690     BuildMI(*endMBB, endMBB->begin(), DL,
14691             TII->get(X86::PHI), DestReg)
14692       .addReg(OffsetDestReg).addMBB(offsetMBB)
14693       .addReg(OverflowDestReg).addMBB(overflowMBB);
14694   }
14695
14696   // Erase the pseudo instruction
14697   MI->eraseFromParent();
14698
14699   return endMBB;
14700 }
14701
14702 MachineBasicBlock *
14703 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14704                                                  MachineInstr *MI,
14705                                                  MachineBasicBlock *MBB) const {
14706   // Emit code to save XMM registers to the stack. The ABI says that the
14707   // number of registers to save is given in %al, so it's theoretically
14708   // possible to do an indirect jump trick to avoid saving all of them,
14709   // however this code takes a simpler approach and just executes all
14710   // of the stores if %al is non-zero. It's less code, and it's probably
14711   // easier on the hardware branch predictor, and stores aren't all that
14712   // expensive anyway.
14713
14714   // Create the new basic blocks. One block contains all the XMM stores,
14715   // and one block is the final destination regardless of whether any
14716   // stores were performed.
14717   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14718   MachineFunction *F = MBB->getParent();
14719   MachineFunction::iterator MBBIter = MBB;
14720   ++MBBIter;
14721   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14722   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14723   F->insert(MBBIter, XMMSaveMBB);
14724   F->insert(MBBIter, EndMBB);
14725
14726   // Transfer the remainder of MBB and its successor edges to EndMBB.
14727   EndMBB->splice(EndMBB->begin(), MBB,
14728                  llvm::next(MachineBasicBlock::iterator(MI)),
14729                  MBB->end());
14730   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14731
14732   // The original block will now fall through to the XMM save block.
14733   MBB->addSuccessor(XMMSaveMBB);
14734   // The XMMSaveMBB will fall through to the end block.
14735   XMMSaveMBB->addSuccessor(EndMBB);
14736
14737   // Now add the instructions.
14738   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14739   DebugLoc DL = MI->getDebugLoc();
14740
14741   unsigned CountReg = MI->getOperand(0).getReg();
14742   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14743   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14744
14745   if (!Subtarget->isTargetWin64()) {
14746     // If %al is 0, branch around the XMM save block.
14747     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14748     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14749     MBB->addSuccessor(EndMBB);
14750   }
14751
14752   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14753   // In the XMM save block, save all the XMM argument registers.
14754   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14755     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14756     MachineMemOperand *MMO =
14757       F->getMachineMemOperand(
14758           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14759         MachineMemOperand::MOStore,
14760         /*Size=*/16, /*Align=*/16);
14761     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14762       .addFrameIndex(RegSaveFrameIndex)
14763       .addImm(/*Scale=*/1)
14764       .addReg(/*IndexReg=*/0)
14765       .addImm(/*Disp=*/Offset)
14766       .addReg(/*Segment=*/0)
14767       .addReg(MI->getOperand(i).getReg())
14768       .addMemOperand(MMO);
14769   }
14770
14771   MI->eraseFromParent();   // The pseudo instruction is gone now.
14772
14773   return EndMBB;
14774 }
14775
14776 // The EFLAGS operand of SelectItr might be missing a kill marker
14777 // because there were multiple uses of EFLAGS, and ISel didn't know
14778 // which to mark. Figure out whether SelectItr should have had a
14779 // kill marker, and set it if it should. Returns the correct kill
14780 // marker value.
14781 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14782                                      MachineBasicBlock* BB,
14783                                      const TargetRegisterInfo* TRI) {
14784   // Scan forward through BB for a use/def of EFLAGS.
14785   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14786   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14787     const MachineInstr& mi = *miI;
14788     if (mi.readsRegister(X86::EFLAGS))
14789       return false;
14790     if (mi.definesRegister(X86::EFLAGS))
14791       break; // Should have kill-flag - update below.
14792   }
14793
14794   // If we hit the end of the block, check whether EFLAGS is live into a
14795   // successor.
14796   if (miI == BB->end()) {
14797     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14798                                           sEnd = BB->succ_end();
14799          sItr != sEnd; ++sItr) {
14800       MachineBasicBlock* succ = *sItr;
14801       if (succ->isLiveIn(X86::EFLAGS))
14802         return false;
14803     }
14804   }
14805
14806   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14807   // out. SelectMI should have a kill flag on EFLAGS.
14808   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14809   return true;
14810 }
14811
14812 MachineBasicBlock *
14813 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14814                                      MachineBasicBlock *BB) const {
14815   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14816   DebugLoc DL = MI->getDebugLoc();
14817
14818   // To "insert" a SELECT_CC instruction, we actually have to insert the
14819   // diamond control-flow pattern.  The incoming instruction knows the
14820   // destination vreg to set, the condition code register to branch on, the
14821   // true/false values to select between, and a branch opcode to use.
14822   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14823   MachineFunction::iterator It = BB;
14824   ++It;
14825
14826   //  thisMBB:
14827   //  ...
14828   //   TrueVal = ...
14829   //   cmpTY ccX, r1, r2
14830   //   bCC copy1MBB
14831   //   fallthrough --> copy0MBB
14832   MachineBasicBlock *thisMBB = BB;
14833   MachineFunction *F = BB->getParent();
14834   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14835   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14836   F->insert(It, copy0MBB);
14837   F->insert(It, sinkMBB);
14838
14839   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14840   // live into the sink and copy blocks.
14841   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14842   if (!MI->killsRegister(X86::EFLAGS) &&
14843       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14844     copy0MBB->addLiveIn(X86::EFLAGS);
14845     sinkMBB->addLiveIn(X86::EFLAGS);
14846   }
14847
14848   // Transfer the remainder of BB and its successor edges to sinkMBB.
14849   sinkMBB->splice(sinkMBB->begin(), BB,
14850                   llvm::next(MachineBasicBlock::iterator(MI)),
14851                   BB->end());
14852   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14853
14854   // Add the true and fallthrough blocks as its successors.
14855   BB->addSuccessor(copy0MBB);
14856   BB->addSuccessor(sinkMBB);
14857
14858   // Create the conditional branch instruction.
14859   unsigned Opc =
14860     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14861   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14862
14863   //  copy0MBB:
14864   //   %FalseValue = ...
14865   //   # fallthrough to sinkMBB
14866   copy0MBB->addSuccessor(sinkMBB);
14867
14868   //  sinkMBB:
14869   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14870   //  ...
14871   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14872           TII->get(X86::PHI), MI->getOperand(0).getReg())
14873     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14874     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14875
14876   MI->eraseFromParent();   // The pseudo instruction is gone now.
14877   return sinkMBB;
14878 }
14879
14880 MachineBasicBlock *
14881 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14882                                         bool Is64Bit) const {
14883   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14884   DebugLoc DL = MI->getDebugLoc();
14885   MachineFunction *MF = BB->getParent();
14886   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14887
14888   assert(getTargetMachine().Options.EnableSegmentedStacks);
14889
14890   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14891   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14892
14893   // BB:
14894   //  ... [Till the alloca]
14895   // If stacklet is not large enough, jump to mallocMBB
14896   //
14897   // bumpMBB:
14898   //  Allocate by subtracting from RSP
14899   //  Jump to continueMBB
14900   //
14901   // mallocMBB:
14902   //  Allocate by call to runtime
14903   //
14904   // continueMBB:
14905   //  ...
14906   //  [rest of original BB]
14907   //
14908
14909   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14910   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14911   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14912
14913   MachineRegisterInfo &MRI = MF->getRegInfo();
14914   const TargetRegisterClass *AddrRegClass =
14915     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14916
14917   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14918     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14919     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14920     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14921     sizeVReg = MI->getOperand(1).getReg(),
14922     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14923
14924   MachineFunction::iterator MBBIter = BB;
14925   ++MBBIter;
14926
14927   MF->insert(MBBIter, bumpMBB);
14928   MF->insert(MBBIter, mallocMBB);
14929   MF->insert(MBBIter, continueMBB);
14930
14931   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14932                       (MachineBasicBlock::iterator(MI)), BB->end());
14933   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14934
14935   // Add code to the main basic block to check if the stack limit has been hit,
14936   // and if so, jump to mallocMBB otherwise to bumpMBB.
14937   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14938   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14939     .addReg(tmpSPVReg).addReg(sizeVReg);
14940   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14941     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14942     .addReg(SPLimitVReg);
14943   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14944
14945   // bumpMBB simply decreases the stack pointer, since we know the current
14946   // stacklet has enough space.
14947   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14948     .addReg(SPLimitVReg);
14949   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14950     .addReg(SPLimitVReg);
14951   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14952
14953   // Calls into a routine in libgcc to allocate more space from the heap.
14954   const uint32_t *RegMask =
14955     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14956   if (Is64Bit) {
14957     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14958       .addReg(sizeVReg);
14959     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14960       .addExternalSymbol("__morestack_allocate_stack_space")
14961       .addRegMask(RegMask)
14962       .addReg(X86::RDI, RegState::Implicit)
14963       .addReg(X86::RAX, RegState::ImplicitDefine);
14964   } else {
14965     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14966       .addImm(12);
14967     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14968     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14969       .addExternalSymbol("__morestack_allocate_stack_space")
14970       .addRegMask(RegMask)
14971       .addReg(X86::EAX, RegState::ImplicitDefine);
14972   }
14973
14974   if (!Is64Bit)
14975     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14976       .addImm(16);
14977
14978   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14979     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14980   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14981
14982   // Set up the CFG correctly.
14983   BB->addSuccessor(bumpMBB);
14984   BB->addSuccessor(mallocMBB);
14985   mallocMBB->addSuccessor(continueMBB);
14986   bumpMBB->addSuccessor(continueMBB);
14987
14988   // Take care of the PHI nodes.
14989   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14990           MI->getOperand(0).getReg())
14991     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14992     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14993
14994   // Delete the original pseudo instruction.
14995   MI->eraseFromParent();
14996
14997   // And we're done.
14998   return continueMBB;
14999 }
15000
15001 MachineBasicBlock *
15002 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
15003                                           MachineBasicBlock *BB) const {
15004   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15005   DebugLoc DL = MI->getDebugLoc();
15006
15007   assert(!Subtarget->isTargetEnvMacho());
15008
15009   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
15010   // non-trivial part is impdef of ESP.
15011
15012   if (Subtarget->isTargetWin64()) {
15013     if (Subtarget->isTargetCygMing()) {
15014       // ___chkstk(Mingw64):
15015       // Clobbers R10, R11, RAX and EFLAGS.
15016       // Updates RSP.
15017       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15018         .addExternalSymbol("___chkstk")
15019         .addReg(X86::RAX, RegState::Implicit)
15020         .addReg(X86::RSP, RegState::Implicit)
15021         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
15022         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
15023         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15024     } else {
15025       // __chkstk(MSVCRT): does not update stack pointer.
15026       // Clobbers R10, R11 and EFLAGS.
15027       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
15028         .addExternalSymbol("__chkstk")
15029         .addReg(X86::RAX, RegState::Implicit)
15030         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15031       // RAX has the offset to be subtracted from RSP.
15032       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
15033         .addReg(X86::RSP)
15034         .addReg(X86::RAX);
15035     }
15036   } else {
15037     const char *StackProbeSymbol =
15038       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
15039
15040     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
15041       .addExternalSymbol(StackProbeSymbol)
15042       .addReg(X86::EAX, RegState::Implicit)
15043       .addReg(X86::ESP, RegState::Implicit)
15044       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
15045       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
15046       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
15047   }
15048
15049   MI->eraseFromParent();   // The pseudo instruction is gone now.
15050   return BB;
15051 }
15052
15053 MachineBasicBlock *
15054 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
15055                                       MachineBasicBlock *BB) const {
15056   // This is pretty easy.  We're taking the value that we received from
15057   // our load from the relocation, sticking it in either RDI (x86-64)
15058   // or EAX and doing an indirect call.  The return value will then
15059   // be in the normal return register.
15060   const X86InstrInfo *TII
15061     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
15062   DebugLoc DL = MI->getDebugLoc();
15063   MachineFunction *F = BB->getParent();
15064
15065   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
15066   assert(MI->getOperand(3).isGlobal() && "This should be a global");
15067
15068   // Get a register mask for the lowered call.
15069   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
15070   // proper register mask.
15071   const uint32_t *RegMask =
15072     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
15073   if (Subtarget->is64Bit()) {
15074     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15075                                       TII->get(X86::MOV64rm), X86::RDI)
15076     .addReg(X86::RIP)
15077     .addImm(0).addReg(0)
15078     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15079                       MI->getOperand(3).getTargetFlags())
15080     .addReg(0);
15081     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
15082     addDirectMem(MIB, X86::RDI);
15083     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
15084   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
15085     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15086                                       TII->get(X86::MOV32rm), X86::EAX)
15087     .addReg(0)
15088     .addImm(0).addReg(0)
15089     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15090                       MI->getOperand(3).getTargetFlags())
15091     .addReg(0);
15092     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15093     addDirectMem(MIB, X86::EAX);
15094     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15095   } else {
15096     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
15097                                       TII->get(X86::MOV32rm), X86::EAX)
15098     .addReg(TII->getGlobalBaseReg(F))
15099     .addImm(0).addReg(0)
15100     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
15101                       MI->getOperand(3).getTargetFlags())
15102     .addReg(0);
15103     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
15104     addDirectMem(MIB, X86::EAX);
15105     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
15106   }
15107
15108   MI->eraseFromParent(); // The pseudo instruction is gone now.
15109   return BB;
15110 }
15111
15112 MachineBasicBlock *
15113 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
15114                                     MachineBasicBlock *MBB) const {
15115   DebugLoc DL = MI->getDebugLoc();
15116   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15117
15118   MachineFunction *MF = MBB->getParent();
15119   MachineRegisterInfo &MRI = MF->getRegInfo();
15120
15121   const BasicBlock *BB = MBB->getBasicBlock();
15122   MachineFunction::iterator I = MBB;
15123   ++I;
15124
15125   // Memory Reference
15126   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15127   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15128
15129   unsigned DstReg;
15130   unsigned MemOpndSlot = 0;
15131
15132   unsigned CurOp = 0;
15133
15134   DstReg = MI->getOperand(CurOp++).getReg();
15135   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15136   assert(RC->hasType(MVT::i32) && "Invalid destination!");
15137   unsigned mainDstReg = MRI.createVirtualRegister(RC);
15138   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
15139
15140   MemOpndSlot = CurOp;
15141
15142   MVT PVT = getPointerTy();
15143   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15144          "Invalid Pointer Size!");
15145
15146   // For v = setjmp(buf), we generate
15147   //
15148   // thisMBB:
15149   //  buf[LabelOffset] = restoreMBB
15150   //  SjLjSetup restoreMBB
15151   //
15152   // mainMBB:
15153   //  v_main = 0
15154   //
15155   // sinkMBB:
15156   //  v = phi(main, restore)
15157   //
15158   // restoreMBB:
15159   //  v_restore = 1
15160
15161   MachineBasicBlock *thisMBB = MBB;
15162   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15163   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15164   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15165   MF->insert(I, mainMBB);
15166   MF->insert(I, sinkMBB);
15167   MF->push_back(restoreMBB);
15168
15169   MachineInstrBuilder MIB;
15170
15171   // Transfer the remainder of BB and its successor edges to sinkMBB.
15172   sinkMBB->splice(sinkMBB->begin(), MBB,
15173                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15174   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15175
15176   // thisMBB:
15177   unsigned PtrStoreOpc = 0;
15178   unsigned LabelReg = 0;
15179   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15180   Reloc::Model RM = getTargetMachine().getRelocationModel();
15181   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15182                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15183
15184   // Prepare IP either in reg or imm.
15185   if (!UseImmLabel) {
15186     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15187     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15188     LabelReg = MRI.createVirtualRegister(PtrRC);
15189     if (Subtarget->is64Bit()) {
15190       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15191               .addReg(X86::RIP)
15192               .addImm(0)
15193               .addReg(0)
15194               .addMBB(restoreMBB)
15195               .addReg(0);
15196     } else {
15197       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15198       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15199               .addReg(XII->getGlobalBaseReg(MF))
15200               .addImm(0)
15201               .addReg(0)
15202               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15203               .addReg(0);
15204     }
15205   } else
15206     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15207   // Store IP
15208   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15209   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15210     if (i == X86::AddrDisp)
15211       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15212     else
15213       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15214   }
15215   if (!UseImmLabel)
15216     MIB.addReg(LabelReg);
15217   else
15218     MIB.addMBB(restoreMBB);
15219   MIB.setMemRefs(MMOBegin, MMOEnd);
15220   // Setup
15221   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15222           .addMBB(restoreMBB);
15223
15224   const X86RegisterInfo *RegInfo =
15225     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15226   MIB.addRegMask(RegInfo->getNoPreservedMask());
15227   thisMBB->addSuccessor(mainMBB);
15228   thisMBB->addSuccessor(restoreMBB);
15229
15230   // mainMBB:
15231   //  EAX = 0
15232   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15233   mainMBB->addSuccessor(sinkMBB);
15234
15235   // sinkMBB:
15236   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15237           TII->get(X86::PHI), DstReg)
15238     .addReg(mainDstReg).addMBB(mainMBB)
15239     .addReg(restoreDstReg).addMBB(restoreMBB);
15240
15241   // restoreMBB:
15242   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15243   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15244   restoreMBB->addSuccessor(sinkMBB);
15245
15246   MI->eraseFromParent();
15247   return sinkMBB;
15248 }
15249
15250 MachineBasicBlock *
15251 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15252                                      MachineBasicBlock *MBB) const {
15253   DebugLoc DL = MI->getDebugLoc();
15254   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15255
15256   MachineFunction *MF = MBB->getParent();
15257   MachineRegisterInfo &MRI = MF->getRegInfo();
15258
15259   // Memory Reference
15260   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15261   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15262
15263   MVT PVT = getPointerTy();
15264   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15265          "Invalid Pointer Size!");
15266
15267   const TargetRegisterClass *RC =
15268     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15269   unsigned Tmp = MRI.createVirtualRegister(RC);
15270   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15271   const X86RegisterInfo *RegInfo =
15272     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15273   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15274   unsigned SP = RegInfo->getStackRegister();
15275
15276   MachineInstrBuilder MIB;
15277
15278   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15279   const int64_t SPOffset = 2 * PVT.getStoreSize();
15280
15281   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15282   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15283
15284   // Reload FP
15285   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15286   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15287     MIB.addOperand(MI->getOperand(i));
15288   MIB.setMemRefs(MMOBegin, MMOEnd);
15289   // Reload IP
15290   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15291   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15292     if (i == X86::AddrDisp)
15293       MIB.addDisp(MI->getOperand(i), LabelOffset);
15294     else
15295       MIB.addOperand(MI->getOperand(i));
15296   }
15297   MIB.setMemRefs(MMOBegin, MMOEnd);
15298   // Reload SP
15299   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15300   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15301     if (i == X86::AddrDisp)
15302       MIB.addDisp(MI->getOperand(i), SPOffset);
15303     else
15304       MIB.addOperand(MI->getOperand(i));
15305   }
15306   MIB.setMemRefs(MMOBegin, MMOEnd);
15307   // Jump
15308   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15309
15310   MI->eraseFromParent();
15311   return MBB;
15312 }
15313
15314 MachineBasicBlock *
15315 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15316                                                MachineBasicBlock *BB) const {
15317   switch (MI->getOpcode()) {
15318   default: llvm_unreachable("Unexpected instr type to insert");
15319   case X86::TAILJMPd64:
15320   case X86::TAILJMPr64:
15321   case X86::TAILJMPm64:
15322     llvm_unreachable("TAILJMP64 would not be touched here.");
15323   case X86::TCRETURNdi64:
15324   case X86::TCRETURNri64:
15325   case X86::TCRETURNmi64:
15326     return BB;
15327   case X86::WIN_ALLOCA:
15328     return EmitLoweredWinAlloca(MI, BB);
15329   case X86::SEG_ALLOCA_32:
15330     return EmitLoweredSegAlloca(MI, BB, false);
15331   case X86::SEG_ALLOCA_64:
15332     return EmitLoweredSegAlloca(MI, BB, true);
15333   case X86::TLSCall_32:
15334   case X86::TLSCall_64:
15335     return EmitLoweredTLSCall(MI, BB);
15336   case X86::CMOV_GR8:
15337   case X86::CMOV_FR32:
15338   case X86::CMOV_FR64:
15339   case X86::CMOV_V4F32:
15340   case X86::CMOV_V2F64:
15341   case X86::CMOV_V2I64:
15342   case X86::CMOV_V8F32:
15343   case X86::CMOV_V4F64:
15344   case X86::CMOV_V4I64:
15345   case X86::CMOV_GR16:
15346   case X86::CMOV_GR32:
15347   case X86::CMOV_RFP32:
15348   case X86::CMOV_RFP64:
15349   case X86::CMOV_RFP80:
15350     return EmitLoweredSelect(MI, BB);
15351
15352   case X86::FP32_TO_INT16_IN_MEM:
15353   case X86::FP32_TO_INT32_IN_MEM:
15354   case X86::FP32_TO_INT64_IN_MEM:
15355   case X86::FP64_TO_INT16_IN_MEM:
15356   case X86::FP64_TO_INT32_IN_MEM:
15357   case X86::FP64_TO_INT64_IN_MEM:
15358   case X86::FP80_TO_INT16_IN_MEM:
15359   case X86::FP80_TO_INT32_IN_MEM:
15360   case X86::FP80_TO_INT64_IN_MEM: {
15361     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15362     DebugLoc DL = MI->getDebugLoc();
15363
15364     // Change the floating point control register to use "round towards zero"
15365     // mode when truncating to an integer value.
15366     MachineFunction *F = BB->getParent();
15367     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15368     addFrameReference(BuildMI(*BB, MI, DL,
15369                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
15370
15371     // Load the old value of the high byte of the control word...
15372     unsigned OldCW =
15373       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15374     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15375                       CWFrameIdx);
15376
15377     // Set the high part to be round to zero...
15378     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15379       .addImm(0xC7F);
15380
15381     // Reload the modified control word now...
15382     addFrameReference(BuildMI(*BB, MI, DL,
15383                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15384
15385     // Restore the memory image of control word to original value
15386     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15387       .addReg(OldCW);
15388
15389     // Get the X86 opcode to use.
15390     unsigned Opc;
15391     switch (MI->getOpcode()) {
15392     default: llvm_unreachable("illegal opcode!");
15393     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15394     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15395     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15396     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15397     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15398     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15399     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15400     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15401     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15402     }
15403
15404     X86AddressMode AM;
15405     MachineOperand &Op = MI->getOperand(0);
15406     if (Op.isReg()) {
15407       AM.BaseType = X86AddressMode::RegBase;
15408       AM.Base.Reg = Op.getReg();
15409     } else {
15410       AM.BaseType = X86AddressMode::FrameIndexBase;
15411       AM.Base.FrameIndex = Op.getIndex();
15412     }
15413     Op = MI->getOperand(1);
15414     if (Op.isImm())
15415       AM.Scale = Op.getImm();
15416     Op = MI->getOperand(2);
15417     if (Op.isImm())
15418       AM.IndexReg = Op.getImm();
15419     Op = MI->getOperand(3);
15420     if (Op.isGlobal()) {
15421       AM.GV = Op.getGlobal();
15422     } else {
15423       AM.Disp = Op.getImm();
15424     }
15425     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15426                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15427
15428     // Reload the original control word now.
15429     addFrameReference(BuildMI(*BB, MI, DL,
15430                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15431
15432     MI->eraseFromParent();   // The pseudo instruction is gone now.
15433     return BB;
15434   }
15435     // String/text processing lowering.
15436   case X86::PCMPISTRM128REG:
15437   case X86::VPCMPISTRM128REG:
15438   case X86::PCMPISTRM128MEM:
15439   case X86::VPCMPISTRM128MEM:
15440   case X86::PCMPESTRM128REG:
15441   case X86::VPCMPESTRM128REG:
15442   case X86::PCMPESTRM128MEM:
15443   case X86::VPCMPESTRM128MEM:
15444     assert(Subtarget->hasSSE42() &&
15445            "Target must have SSE4.2 or AVX features enabled");
15446     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15447
15448   // String/text processing lowering.
15449   case X86::PCMPISTRIREG:
15450   case X86::VPCMPISTRIREG:
15451   case X86::PCMPISTRIMEM:
15452   case X86::VPCMPISTRIMEM:
15453   case X86::PCMPESTRIREG:
15454   case X86::VPCMPESTRIREG:
15455   case X86::PCMPESTRIMEM:
15456   case X86::VPCMPESTRIMEM:
15457     assert(Subtarget->hasSSE42() &&
15458            "Target must have SSE4.2 or AVX features enabled");
15459     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15460
15461   // Thread synchronization.
15462   case X86::MONITOR:
15463     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15464
15465   // xbegin
15466   case X86::XBEGIN:
15467     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15468
15469   // Atomic Lowering.
15470   case X86::ATOMAND8:
15471   case X86::ATOMAND16:
15472   case X86::ATOMAND32:
15473   case X86::ATOMAND64:
15474     // Fall through
15475   case X86::ATOMOR8:
15476   case X86::ATOMOR16:
15477   case X86::ATOMOR32:
15478   case X86::ATOMOR64:
15479     // Fall through
15480   case X86::ATOMXOR16:
15481   case X86::ATOMXOR8:
15482   case X86::ATOMXOR32:
15483   case X86::ATOMXOR64:
15484     // Fall through
15485   case X86::ATOMNAND8:
15486   case X86::ATOMNAND16:
15487   case X86::ATOMNAND32:
15488   case X86::ATOMNAND64:
15489     // Fall through
15490   case X86::ATOMMAX8:
15491   case X86::ATOMMAX16:
15492   case X86::ATOMMAX32:
15493   case X86::ATOMMAX64:
15494     // Fall through
15495   case X86::ATOMMIN8:
15496   case X86::ATOMMIN16:
15497   case X86::ATOMMIN32:
15498   case X86::ATOMMIN64:
15499     // Fall through
15500   case X86::ATOMUMAX8:
15501   case X86::ATOMUMAX16:
15502   case X86::ATOMUMAX32:
15503   case X86::ATOMUMAX64:
15504     // Fall through
15505   case X86::ATOMUMIN8:
15506   case X86::ATOMUMIN16:
15507   case X86::ATOMUMIN32:
15508   case X86::ATOMUMIN64:
15509     return EmitAtomicLoadArith(MI, BB);
15510
15511   // This group does 64-bit operations on a 32-bit host.
15512   case X86::ATOMAND6432:
15513   case X86::ATOMOR6432:
15514   case X86::ATOMXOR6432:
15515   case X86::ATOMNAND6432:
15516   case X86::ATOMADD6432:
15517   case X86::ATOMSUB6432:
15518   case X86::ATOMMAX6432:
15519   case X86::ATOMMIN6432:
15520   case X86::ATOMUMAX6432:
15521   case X86::ATOMUMIN6432:
15522   case X86::ATOMSWAP6432:
15523     return EmitAtomicLoadArith6432(MI, BB);
15524
15525   case X86::VASTART_SAVE_XMM_REGS:
15526     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
15527
15528   case X86::VAARG_64:
15529     return EmitVAARG64WithCustomInserter(MI, BB);
15530
15531   case X86::EH_SjLj_SetJmp32:
15532   case X86::EH_SjLj_SetJmp64:
15533     return emitEHSjLjSetJmp(MI, BB);
15534
15535   case X86::EH_SjLj_LongJmp32:
15536   case X86::EH_SjLj_LongJmp64:
15537     return emitEHSjLjLongJmp(MI, BB);
15538   }
15539 }
15540
15541 //===----------------------------------------------------------------------===//
15542 //                           X86 Optimization Hooks
15543 //===----------------------------------------------------------------------===//
15544
15545 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
15546                                                        APInt &KnownZero,
15547                                                        APInt &KnownOne,
15548                                                        const SelectionDAG &DAG,
15549                                                        unsigned Depth) const {
15550   unsigned BitWidth = KnownZero.getBitWidth();
15551   unsigned Opc = Op.getOpcode();
15552   assert((Opc >= ISD::BUILTIN_OP_END ||
15553           Opc == ISD::INTRINSIC_WO_CHAIN ||
15554           Opc == ISD::INTRINSIC_W_CHAIN ||
15555           Opc == ISD::INTRINSIC_VOID) &&
15556          "Should use MaskedValueIsZero if you don't know whether Op"
15557          " is a target node!");
15558
15559   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
15560   switch (Opc) {
15561   default: break;
15562   case X86ISD::ADD:
15563   case X86ISD::SUB:
15564   case X86ISD::ADC:
15565   case X86ISD::SBB:
15566   case X86ISD::SMUL:
15567   case X86ISD::UMUL:
15568   case X86ISD::INC:
15569   case X86ISD::DEC:
15570   case X86ISD::OR:
15571   case X86ISD::XOR:
15572   case X86ISD::AND:
15573     // These nodes' second result is a boolean.
15574     if (Op.getResNo() == 0)
15575       break;
15576     // Fallthrough
15577   case X86ISD::SETCC:
15578     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15579     break;
15580   case ISD::INTRINSIC_WO_CHAIN: {
15581     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15582     unsigned NumLoBits = 0;
15583     switch (IntId) {
15584     default: break;
15585     case Intrinsic::x86_sse_movmsk_ps:
15586     case Intrinsic::x86_avx_movmsk_ps_256:
15587     case Intrinsic::x86_sse2_movmsk_pd:
15588     case Intrinsic::x86_avx_movmsk_pd_256:
15589     case Intrinsic::x86_mmx_pmovmskb:
15590     case Intrinsic::x86_sse2_pmovmskb_128:
15591     case Intrinsic::x86_avx2_pmovmskb: {
15592       // High bits of movmskp{s|d}, pmovmskb are known zero.
15593       switch (IntId) {
15594         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15595         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
15596         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
15597         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
15598         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
15599         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
15600         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
15601         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
15602       }
15603       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15604       break;
15605     }
15606     }
15607     break;
15608   }
15609   }
15610 }
15611
15612 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15613                                                          unsigned Depth) const {
15614   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15615   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15616     return Op.getValueType().getScalarType().getSizeInBits();
15617
15618   // Fallback case.
15619   return 1;
15620 }
15621
15622 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15623 /// node is a GlobalAddress + offset.
15624 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15625                                        const GlobalValue* &GA,
15626                                        int64_t &Offset) const {
15627   if (N->getOpcode() == X86ISD::Wrapper) {
15628     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15629       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15630       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15631       return true;
15632     }
15633   }
15634   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15635 }
15636
15637 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15638 /// same as extracting the high 128-bit part of 256-bit vector and then
15639 /// inserting the result into the low part of a new 256-bit vector
15640 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15641   EVT VT = SVOp->getValueType(0);
15642   unsigned NumElems = VT.getVectorNumElements();
15643
15644   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15645   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15646     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15647         SVOp->getMaskElt(j) >= 0)
15648       return false;
15649
15650   return true;
15651 }
15652
15653 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15654 /// same as extracting the low 128-bit part of 256-bit vector and then
15655 /// inserting the result into the high part of a new 256-bit vector
15656 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15657   EVT VT = SVOp->getValueType(0);
15658   unsigned NumElems = VT.getVectorNumElements();
15659
15660   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15661   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15662     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15663         SVOp->getMaskElt(j) >= 0)
15664       return false;
15665
15666   return true;
15667 }
15668
15669 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15670 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15671                                         TargetLowering::DAGCombinerInfo &DCI,
15672                                         const X86Subtarget* Subtarget) {
15673   SDLoc dl(N);
15674   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15675   SDValue V1 = SVOp->getOperand(0);
15676   SDValue V2 = SVOp->getOperand(1);
15677   EVT VT = SVOp->getValueType(0);
15678   unsigned NumElems = VT.getVectorNumElements();
15679
15680   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15681       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15682     //
15683     //                   0,0,0,...
15684     //                      |
15685     //    V      UNDEF    BUILD_VECTOR    UNDEF
15686     //     \      /           \           /
15687     //  CONCAT_VECTOR         CONCAT_VECTOR
15688     //         \                  /
15689     //          \                /
15690     //          RESULT: V + zero extended
15691     //
15692     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15693         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15694         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15695       return SDValue();
15696
15697     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15698       return SDValue();
15699
15700     // To match the shuffle mask, the first half of the mask should
15701     // be exactly the first vector, and all the rest a splat with the
15702     // first element of the second one.
15703     for (unsigned i = 0; i != NumElems/2; ++i)
15704       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15705           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15706         return SDValue();
15707
15708     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15709     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15710       if (Ld->hasNUsesOfValue(1, 0)) {
15711         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15712         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15713         SDValue ResNode =
15714           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15715                                   array_lengthof(Ops),
15716                                   Ld->getMemoryVT(),
15717                                   Ld->getPointerInfo(),
15718                                   Ld->getAlignment(),
15719                                   false/*isVolatile*/, true/*ReadMem*/,
15720                                   false/*WriteMem*/);
15721
15722         // Make sure the newly-created LOAD is in the same position as Ld in
15723         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15724         // and update uses of Ld's output chain to use the TokenFactor.
15725         if (Ld->hasAnyUseOfValue(1)) {
15726           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15727                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15728           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15729           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15730                                  SDValue(ResNode.getNode(), 1));
15731         }
15732
15733         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15734       }
15735     }
15736
15737     // Emit a zeroed vector and insert the desired subvector on its
15738     // first half.
15739     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15740     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15741     return DCI.CombineTo(N, InsV);
15742   }
15743
15744   //===--------------------------------------------------------------------===//
15745   // Combine some shuffles into subvector extracts and inserts:
15746   //
15747
15748   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15749   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15750     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15751     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15752     return DCI.CombineTo(N, InsV);
15753   }
15754
15755   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15756   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15757     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15758     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15759     return DCI.CombineTo(N, InsV);
15760   }
15761
15762   return SDValue();
15763 }
15764
15765 /// PerformShuffleCombine - Performs several different shuffle combines.
15766 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15767                                      TargetLowering::DAGCombinerInfo &DCI,
15768                                      const X86Subtarget *Subtarget) {
15769   SDLoc dl(N);
15770   EVT VT = N->getValueType(0);
15771
15772   // Don't create instructions with illegal types after legalize types has run.
15773   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15774   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15775     return SDValue();
15776
15777   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15778   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15779       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15780     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15781
15782   // Only handle 128 wide vector from here on.
15783   if (!VT.is128BitVector())
15784     return SDValue();
15785
15786   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15787   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15788   // consecutive, non-overlapping, and in the right order.
15789   SmallVector<SDValue, 16> Elts;
15790   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15791     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15792
15793   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15794 }
15795
15796 /// PerformTruncateCombine - Converts truncate operation to
15797 /// a sequence of vector shuffle operations.
15798 /// It is possible when we truncate 256-bit vector to 128-bit vector
15799 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15800                                       TargetLowering::DAGCombinerInfo &DCI,
15801                                       const X86Subtarget *Subtarget)  {
15802   return SDValue();
15803 }
15804
15805 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15806 /// specific shuffle of a load can be folded into a single element load.
15807 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15808 /// shuffles have been customed lowered so we need to handle those here.
15809 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15810                                          TargetLowering::DAGCombinerInfo &DCI) {
15811   if (DCI.isBeforeLegalizeOps())
15812     return SDValue();
15813
15814   SDValue InVec = N->getOperand(0);
15815   SDValue EltNo = N->getOperand(1);
15816
15817   if (!isa<ConstantSDNode>(EltNo))
15818     return SDValue();
15819
15820   EVT VT = InVec.getValueType();
15821
15822   bool HasShuffleIntoBitcast = false;
15823   if (InVec.getOpcode() == ISD::BITCAST) {
15824     // Don't duplicate a load with other uses.
15825     if (!InVec.hasOneUse())
15826       return SDValue();
15827     EVT BCVT = InVec.getOperand(0).getValueType();
15828     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15829       return SDValue();
15830     InVec = InVec.getOperand(0);
15831     HasShuffleIntoBitcast = true;
15832   }
15833
15834   if (!isTargetShuffle(InVec.getOpcode()))
15835     return SDValue();
15836
15837   // Don't duplicate a load with other uses.
15838   if (!InVec.hasOneUse())
15839     return SDValue();
15840
15841   SmallVector<int, 16> ShuffleMask;
15842   bool UnaryShuffle;
15843   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15844                             UnaryShuffle))
15845     return SDValue();
15846
15847   // Select the input vector, guarding against out of range extract vector.
15848   unsigned NumElems = VT.getVectorNumElements();
15849   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15850   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15851   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15852                                          : InVec.getOperand(1);
15853
15854   // If inputs to shuffle are the same for both ops, then allow 2 uses
15855   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15856
15857   if (LdNode.getOpcode() == ISD::BITCAST) {
15858     // Don't duplicate a load with other uses.
15859     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15860       return SDValue();
15861
15862     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15863     LdNode = LdNode.getOperand(0);
15864   }
15865
15866   if (!ISD::isNormalLoad(LdNode.getNode()))
15867     return SDValue();
15868
15869   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15870
15871   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15872     return SDValue();
15873
15874   if (HasShuffleIntoBitcast) {
15875     // If there's a bitcast before the shuffle, check if the load type and
15876     // alignment is valid.
15877     unsigned Align = LN0->getAlignment();
15878     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15879     unsigned NewAlign = TLI.getDataLayout()->
15880       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15881
15882     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15883       return SDValue();
15884   }
15885
15886   // All checks match so transform back to vector_shuffle so that DAG combiner
15887   // can finish the job
15888   SDLoc dl(N);
15889
15890   // Create shuffle node taking into account the case that its a unary shuffle
15891   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15892   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15893                                  InVec.getOperand(0), Shuffle,
15894                                  &ShuffleMask[0]);
15895   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15896   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15897                      EltNo);
15898 }
15899
15900 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15901 /// generation and convert it from being a bunch of shuffles and extracts
15902 /// to a simple store and scalar loads to extract the elements.
15903 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15904                                          TargetLowering::DAGCombinerInfo &DCI) {
15905   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15906   if (NewOp.getNode())
15907     return NewOp;
15908
15909   SDValue InputVector = N->getOperand(0);
15910   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15911   // from mmx to v2i32 has a single usage.
15912   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15913       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15914       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15915     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15916                        N->getValueType(0),
15917                        InputVector.getNode()->getOperand(0));
15918
15919   // Only operate on vectors of 4 elements, where the alternative shuffling
15920   // gets to be more expensive.
15921   if (InputVector.getValueType() != MVT::v4i32)
15922     return SDValue();
15923
15924   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15925   // single use which is a sign-extend or zero-extend, and all elements are
15926   // used.
15927   SmallVector<SDNode *, 4> Uses;
15928   unsigned ExtractedElements = 0;
15929   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15930        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15931     if (UI.getUse().getResNo() != InputVector.getResNo())
15932       return SDValue();
15933
15934     SDNode *Extract = *UI;
15935     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15936       return SDValue();
15937
15938     if (Extract->getValueType(0) != MVT::i32)
15939       return SDValue();
15940     if (!Extract->hasOneUse())
15941       return SDValue();
15942     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15943         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15944       return SDValue();
15945     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15946       return SDValue();
15947
15948     // Record which element was extracted.
15949     ExtractedElements |=
15950       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15951
15952     Uses.push_back(Extract);
15953   }
15954
15955   // If not all the elements were used, this may not be worthwhile.
15956   if (ExtractedElements != 15)
15957     return SDValue();
15958
15959   // Ok, we've now decided to do the transformation.
15960   SDLoc dl(InputVector);
15961
15962   // Store the value to a temporary stack slot.
15963   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15964   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15965                             MachinePointerInfo(), false, false, 0);
15966
15967   // Replace each use (extract) with a load of the appropriate element.
15968   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15969        UE = Uses.end(); UI != UE; ++UI) {
15970     SDNode *Extract = *UI;
15971
15972     // cOMpute the element's address.
15973     SDValue Idx = Extract->getOperand(1);
15974     unsigned EltSize =
15975         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15976     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15977     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15978     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15979
15980     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15981                                      StackPtr, OffsetVal);
15982
15983     // Load the scalar.
15984     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15985                                      ScalarAddr, MachinePointerInfo(),
15986                                      false, false, false, 0);
15987
15988     // Replace the exact with the load.
15989     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15990   }
15991
15992   // The replacement was made in place; don't return anything.
15993   return SDValue();
15994 }
15995
15996 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15997 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15998                                    SDValue RHS, SelectionDAG &DAG,
15999                                    const X86Subtarget *Subtarget) {
16000   if (!VT.isVector())
16001     return 0;
16002
16003   switch (VT.getSimpleVT().SimpleTy) {
16004   default: return 0;
16005   case MVT::v32i8:
16006   case MVT::v16i16:
16007   case MVT::v8i32:
16008     if (!Subtarget->hasAVX2())
16009       return 0;
16010   case MVT::v16i8:
16011   case MVT::v8i16:
16012   case MVT::v4i32:
16013     if (!Subtarget->hasSSE2())
16014       return 0;
16015   }
16016
16017   // SSE2 has only a small subset of the operations.
16018   bool hasUnsigned = Subtarget->hasSSE41() ||
16019                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
16020   bool hasSigned = Subtarget->hasSSE41() ||
16021                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
16022
16023   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16024
16025   // Check for x CC y ? x : y.
16026   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16027       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16028     switch (CC) {
16029     default: break;
16030     case ISD::SETULT:
16031     case ISD::SETULE:
16032       return hasUnsigned ? X86ISD::UMIN : 0;
16033     case ISD::SETUGT:
16034     case ISD::SETUGE:
16035       return hasUnsigned ? X86ISD::UMAX : 0;
16036     case ISD::SETLT:
16037     case ISD::SETLE:
16038       return hasSigned ? X86ISD::SMIN : 0;
16039     case ISD::SETGT:
16040     case ISD::SETGE:
16041       return hasSigned ? X86ISD::SMAX : 0;
16042     }
16043   // Check for x CC y ? y : x -- a min/max with reversed arms.
16044   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16045              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16046     switch (CC) {
16047     default: break;
16048     case ISD::SETULT:
16049     case ISD::SETULE:
16050       return hasUnsigned ? X86ISD::UMAX : 0;
16051     case ISD::SETUGT:
16052     case ISD::SETUGE:
16053       return hasUnsigned ? X86ISD::UMIN : 0;
16054     case ISD::SETLT:
16055     case ISD::SETLE:
16056       return hasSigned ? X86ISD::SMAX : 0;
16057     case ISD::SETGT:
16058     case ISD::SETGE:
16059       return hasSigned ? X86ISD::SMIN : 0;
16060     }
16061   }
16062
16063   return 0;
16064 }
16065
16066 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
16067 /// nodes.
16068 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
16069                                     TargetLowering::DAGCombinerInfo &DCI,
16070                                     const X86Subtarget *Subtarget) {
16071   SDLoc DL(N);
16072   SDValue Cond = N->getOperand(0);
16073   // Get the LHS/RHS of the select.
16074   SDValue LHS = N->getOperand(1);
16075   SDValue RHS = N->getOperand(2);
16076   EVT VT = LHS.getValueType();
16077
16078   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
16079   // instructions match the semantics of the common C idiom x<y?x:y but not
16080   // x<=y?x:y, because of how they handle negative zero (which can be
16081   // ignored in unsafe-math mode).
16082   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
16083       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
16084       (Subtarget->hasSSE2() ||
16085        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
16086     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16087
16088     unsigned Opcode = 0;
16089     // Check for x CC y ? x : y.
16090     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16091         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16092       switch (CC) {
16093       default: break;
16094       case ISD::SETULT:
16095         // Converting this to a min would handle NaNs incorrectly, and swapping
16096         // the operands would cause it to handle comparisons between positive
16097         // and negative zero incorrectly.
16098         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16099           if (!DAG.getTarget().Options.UnsafeFPMath &&
16100               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16101             break;
16102           std::swap(LHS, RHS);
16103         }
16104         Opcode = X86ISD::FMIN;
16105         break;
16106       case ISD::SETOLE:
16107         // Converting this to a min would handle comparisons between positive
16108         // and negative zero incorrectly.
16109         if (!DAG.getTarget().Options.UnsafeFPMath &&
16110             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16111           break;
16112         Opcode = X86ISD::FMIN;
16113         break;
16114       case ISD::SETULE:
16115         // Converting this to a min would handle both negative zeros and NaNs
16116         // incorrectly, but we can swap the operands to fix both.
16117         std::swap(LHS, RHS);
16118       case ISD::SETOLT:
16119       case ISD::SETLT:
16120       case ISD::SETLE:
16121         Opcode = X86ISD::FMIN;
16122         break;
16123
16124       case ISD::SETOGE:
16125         // Converting this to a max would handle comparisons between positive
16126         // and negative zero incorrectly.
16127         if (!DAG.getTarget().Options.UnsafeFPMath &&
16128             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
16129           break;
16130         Opcode = X86ISD::FMAX;
16131         break;
16132       case ISD::SETUGT:
16133         // Converting this to a max would handle NaNs incorrectly, and swapping
16134         // the operands would cause it to handle comparisons between positive
16135         // and negative zero incorrectly.
16136         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
16137           if (!DAG.getTarget().Options.UnsafeFPMath &&
16138               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
16139             break;
16140           std::swap(LHS, RHS);
16141         }
16142         Opcode = X86ISD::FMAX;
16143         break;
16144       case ISD::SETUGE:
16145         // Converting this to a max would handle both negative zeros and NaNs
16146         // incorrectly, but we can swap the operands to fix both.
16147         std::swap(LHS, RHS);
16148       case ISD::SETOGT:
16149       case ISD::SETGT:
16150       case ISD::SETGE:
16151         Opcode = X86ISD::FMAX;
16152         break;
16153       }
16154     // Check for x CC y ? y : x -- a min/max with reversed arms.
16155     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16156                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16157       switch (CC) {
16158       default: break;
16159       case ISD::SETOGE:
16160         // Converting this to a min would handle comparisons between positive
16161         // and negative zero incorrectly, and swapping the operands would
16162         // cause it to handle NaNs incorrectly.
16163         if (!DAG.getTarget().Options.UnsafeFPMath &&
16164             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16165           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16166             break;
16167           std::swap(LHS, RHS);
16168         }
16169         Opcode = X86ISD::FMIN;
16170         break;
16171       case ISD::SETUGT:
16172         // Converting this to a min would handle NaNs incorrectly.
16173         if (!DAG.getTarget().Options.UnsafeFPMath &&
16174             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16175           break;
16176         Opcode = X86ISD::FMIN;
16177         break;
16178       case ISD::SETUGE:
16179         // Converting this to a min would handle both negative zeros and NaNs
16180         // incorrectly, but we can swap the operands to fix both.
16181         std::swap(LHS, RHS);
16182       case ISD::SETOGT:
16183       case ISD::SETGT:
16184       case ISD::SETGE:
16185         Opcode = X86ISD::FMIN;
16186         break;
16187
16188       case ISD::SETULT:
16189         // Converting this to a max would handle NaNs incorrectly.
16190         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16191           break;
16192         Opcode = X86ISD::FMAX;
16193         break;
16194       case ISD::SETOLE:
16195         // Converting this to a max would handle comparisons between positive
16196         // and negative zero incorrectly, and swapping the operands would
16197         // cause it to handle NaNs incorrectly.
16198         if (!DAG.getTarget().Options.UnsafeFPMath &&
16199             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16200           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16201             break;
16202           std::swap(LHS, RHS);
16203         }
16204         Opcode = X86ISD::FMAX;
16205         break;
16206       case ISD::SETULE:
16207         // Converting this to a max would handle both negative zeros and NaNs
16208         // incorrectly, but we can swap the operands to fix both.
16209         std::swap(LHS, RHS);
16210       case ISD::SETOLT:
16211       case ISD::SETLT:
16212       case ISD::SETLE:
16213         Opcode = X86ISD::FMAX;
16214         break;
16215       }
16216     }
16217
16218     if (Opcode)
16219       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16220   }
16221
16222   // If this is a select between two integer constants, try to do some
16223   // optimizations.
16224   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16225     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16226       // Don't do this for crazy integer types.
16227       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16228         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16229         // so that TrueC (the true value) is larger than FalseC.
16230         bool NeedsCondInvert = false;
16231
16232         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16233             // Efficiently invertible.
16234             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
16235              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
16236               isa<ConstantSDNode>(Cond.getOperand(1))))) {
16237           NeedsCondInvert = true;
16238           std::swap(TrueC, FalseC);
16239         }
16240
16241         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
16242         if (FalseC->getAPIntValue() == 0 &&
16243             TrueC->getAPIntValue().isPowerOf2()) {
16244           if (NeedsCondInvert) // Invert the condition if needed.
16245             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16246                                DAG.getConstant(1, Cond.getValueType()));
16247
16248           // Zero extend the condition if needed.
16249           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16250
16251           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16252           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16253                              DAG.getConstant(ShAmt, MVT::i8));
16254         }
16255
16256         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16257         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16258           if (NeedsCondInvert) // Invert the condition if needed.
16259             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16260                                DAG.getConstant(1, Cond.getValueType()));
16261
16262           // Zero extend the condition if needed.
16263           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16264                              FalseC->getValueType(0), Cond);
16265           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16266                              SDValue(FalseC, 0));
16267         }
16268
16269         // Optimize cases that will turn into an LEA instruction.  This requires
16270         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16271         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16272           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16273           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16274
16275           bool isFastMultiplier = false;
16276           if (Diff < 10) {
16277             switch ((unsigned char)Diff) {
16278               default: break;
16279               case 1:  // result = add base, cond
16280               case 2:  // result = lea base(    , cond*2)
16281               case 3:  // result = lea base(cond, cond*2)
16282               case 4:  // result = lea base(    , cond*4)
16283               case 5:  // result = lea base(cond, cond*4)
16284               case 8:  // result = lea base(    , cond*8)
16285               case 9:  // result = lea base(cond, cond*8)
16286                 isFastMultiplier = true;
16287                 break;
16288             }
16289           }
16290
16291           if (isFastMultiplier) {
16292             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16293             if (NeedsCondInvert) // Invert the condition if needed.
16294               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16295                                  DAG.getConstant(1, Cond.getValueType()));
16296
16297             // Zero extend the condition if needed.
16298             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16299                                Cond);
16300             // Scale the condition by the difference.
16301             if (Diff != 1)
16302               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16303                                  DAG.getConstant(Diff, Cond.getValueType()));
16304
16305             // Add the base if non-zero.
16306             if (FalseC->getAPIntValue() != 0)
16307               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16308                                  SDValue(FalseC, 0));
16309             return Cond;
16310           }
16311         }
16312       }
16313   }
16314
16315   // Canonicalize max and min:
16316   // (x > y) ? x : y -> (x >= y) ? x : y
16317   // (x < y) ? x : y -> (x <= y) ? x : y
16318   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16319   // the need for an extra compare
16320   // against zero. e.g.
16321   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16322   // subl   %esi, %edi
16323   // testl  %edi, %edi
16324   // movl   $0, %eax
16325   // cmovgl %edi, %eax
16326   // =>
16327   // xorl   %eax, %eax
16328   // subl   %esi, $edi
16329   // cmovsl %eax, %edi
16330   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16331       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16332       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16333     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16334     switch (CC) {
16335     default: break;
16336     case ISD::SETLT:
16337     case ISD::SETGT: {
16338       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16339       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16340                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
16341       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16342     }
16343     }
16344   }
16345
16346   // Match VSELECTs into subs with unsigned saturation.
16347   if (!DCI.isBeforeLegalize() &&
16348       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16349       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16350       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16351        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16352     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16353
16354     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16355     // left side invert the predicate to simplify logic below.
16356     SDValue Other;
16357     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16358       Other = RHS;
16359       CC = ISD::getSetCCInverse(CC, true);
16360     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16361       Other = LHS;
16362     }
16363
16364     if (Other.getNode() && Other->getNumOperands() == 2 &&
16365         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16366       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16367       SDValue CondRHS = Cond->getOperand(1);
16368
16369       // Look for a general sub with unsigned saturation first.
16370       // x >= y ? x-y : 0 --> subus x, y
16371       // x >  y ? x-y : 0 --> subus x, y
16372       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16373           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16374         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16375
16376       // If the RHS is a constant we have to reverse the const canonicalization.
16377       // x > C-1 ? x+-C : 0 --> subus x, C
16378       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16379           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16380         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16381         if (CondRHS.getConstantOperandVal(0) == -A-1)
16382           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16383                              DAG.getConstant(-A, VT));
16384       }
16385
16386       // Another special case: If C was a sign bit, the sub has been
16387       // canonicalized into a xor.
16388       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16389       //        it's safe to decanonicalize the xor?
16390       // x s< 0 ? x^C : 0 --> subus x, C
16391       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16392           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16393           isSplatVector(OpRHS.getNode())) {
16394         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16395         if (A.isSignBit())
16396           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16397       }
16398     }
16399   }
16400
16401   // Try to match a min/max vector operation.
16402   if (!DCI.isBeforeLegalize() &&
16403       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
16404     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
16405       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
16406
16407   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16408   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
16409       Cond.getOpcode() == ISD::SETCC) {
16410
16411     assert(Cond.getValueType().isVector() &&
16412            "vector select expects a vector selector!");
16413
16414     EVT IntVT = Cond.getValueType();
16415     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
16416     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
16417
16418     if (!TValIsAllOnes && !FValIsAllZeros) {
16419       // Try invert the condition if true value is not all 1s and false value
16420       // is not all 0s.
16421       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
16422       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
16423
16424       if (TValIsAllZeros || FValIsAllOnes) {
16425         SDValue CC = Cond.getOperand(2);
16426         ISD::CondCode NewCC =
16427           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
16428                                Cond.getOperand(0).getValueType().isInteger());
16429         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
16430         std::swap(LHS, RHS);
16431         TValIsAllOnes = FValIsAllOnes;
16432         FValIsAllZeros = TValIsAllZeros;
16433       }
16434     }
16435
16436     if (TValIsAllOnes || FValIsAllZeros) {
16437       SDValue Ret;
16438
16439       if (TValIsAllOnes && FValIsAllZeros)
16440         Ret = Cond;
16441       else if (TValIsAllOnes)
16442         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
16443                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
16444       else if (FValIsAllZeros)
16445         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
16446                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
16447
16448       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
16449     }
16450   }
16451
16452   // If we know that this node is legal then we know that it is going to be
16453   // matched by one of the SSE/AVX BLEND instructions. These instructions only
16454   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
16455   // to simplify previous instructions.
16456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16457   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
16458       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
16459     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
16460
16461     // Don't optimize vector selects that map to mask-registers.
16462     if (BitWidth == 1)
16463       return SDValue();
16464
16465     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
16466     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
16467
16468     APInt KnownZero, KnownOne;
16469     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
16470                                           DCI.isBeforeLegalizeOps());
16471     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
16472         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
16473       DCI.CommitTargetLoweringOpt(TLO);
16474   }
16475
16476   return SDValue();
16477 }
16478
16479 // Check whether a boolean test is testing a boolean value generated by
16480 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
16481 // code.
16482 //
16483 // Simplify the following patterns:
16484 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
16485 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
16486 // to (Op EFLAGS Cond)
16487 //
16488 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
16489 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
16490 // to (Op EFLAGS !Cond)
16491 //
16492 // where Op could be BRCOND or CMOV.
16493 //
16494 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
16495   // Quit if not CMP and SUB with its value result used.
16496   if (Cmp.getOpcode() != X86ISD::CMP &&
16497       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
16498       return SDValue();
16499
16500   // Quit if not used as a boolean value.
16501   if (CC != X86::COND_E && CC != X86::COND_NE)
16502     return SDValue();
16503
16504   // Check CMP operands. One of them should be 0 or 1 and the other should be
16505   // an SetCC or extended from it.
16506   SDValue Op1 = Cmp.getOperand(0);
16507   SDValue Op2 = Cmp.getOperand(1);
16508
16509   SDValue SetCC;
16510   const ConstantSDNode* C = 0;
16511   bool needOppositeCond = (CC == X86::COND_E);
16512   bool checkAgainstTrue = false; // Is it a comparison against 1?
16513
16514   if ((C = dyn_cast<ConstantSDNode>(Op1)))
16515     SetCC = Op2;
16516   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
16517     SetCC = Op1;
16518   else // Quit if all operands are not constants.
16519     return SDValue();
16520
16521   if (C->getZExtValue() == 1) {
16522     needOppositeCond = !needOppositeCond;
16523     checkAgainstTrue = true;
16524   } else if (C->getZExtValue() != 0)
16525     // Quit if the constant is neither 0 or 1.
16526     return SDValue();
16527
16528   bool truncatedToBoolWithAnd = false;
16529   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
16530   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
16531          SetCC.getOpcode() == ISD::TRUNCATE ||
16532          SetCC.getOpcode() == ISD::AND) {
16533     if (SetCC.getOpcode() == ISD::AND) {
16534       int OpIdx = -1;
16535       ConstantSDNode *CS;
16536       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
16537           CS->getZExtValue() == 1)
16538         OpIdx = 1;
16539       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
16540           CS->getZExtValue() == 1)
16541         OpIdx = 0;
16542       if (OpIdx == -1)
16543         break;
16544       SetCC = SetCC.getOperand(OpIdx);
16545       truncatedToBoolWithAnd = true;
16546     } else
16547       SetCC = SetCC.getOperand(0);
16548   }
16549
16550   switch (SetCC.getOpcode()) {
16551   case X86ISD::SETCC_CARRY:
16552     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
16553     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
16554     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
16555     // truncated to i1 using 'and'.
16556     if (checkAgainstTrue && !truncatedToBoolWithAnd)
16557       break;
16558     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
16559            "Invalid use of SETCC_CARRY!");
16560     // FALL THROUGH
16561   case X86ISD::SETCC:
16562     // Set the condition code or opposite one if necessary.
16563     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
16564     if (needOppositeCond)
16565       CC = X86::GetOppositeBranchCondition(CC);
16566     return SetCC.getOperand(1);
16567   case X86ISD::CMOV: {
16568     // Check whether false/true value has canonical one, i.e. 0 or 1.
16569     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16570     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16571     // Quit if true value is not a constant.
16572     if (!TVal)
16573       return SDValue();
16574     // Quit if false value is not a constant.
16575     if (!FVal) {
16576       SDValue Op = SetCC.getOperand(0);
16577       // Skip 'zext' or 'trunc' node.
16578       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16579           Op.getOpcode() == ISD::TRUNCATE)
16580         Op = Op.getOperand(0);
16581       // A special case for rdrand/rdseed, where 0 is set if false cond is
16582       // found.
16583       if ((Op.getOpcode() != X86ISD::RDRAND &&
16584            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16585         return SDValue();
16586     }
16587     // Quit if false value is not the constant 0 or 1.
16588     bool FValIsFalse = true;
16589     if (FVal && FVal->getZExtValue() != 0) {
16590       if (FVal->getZExtValue() != 1)
16591         return SDValue();
16592       // If FVal is 1, opposite cond is needed.
16593       needOppositeCond = !needOppositeCond;
16594       FValIsFalse = false;
16595     }
16596     // Quit if TVal is not the constant opposite of FVal.
16597     if (FValIsFalse && TVal->getZExtValue() != 1)
16598       return SDValue();
16599     if (!FValIsFalse && TVal->getZExtValue() != 0)
16600       return SDValue();
16601     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16602     if (needOppositeCond)
16603       CC = X86::GetOppositeBranchCondition(CC);
16604     return SetCC.getOperand(3);
16605   }
16606   }
16607
16608   return SDValue();
16609 }
16610
16611 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16612 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16613                                   TargetLowering::DAGCombinerInfo &DCI,
16614                                   const X86Subtarget *Subtarget) {
16615   SDLoc DL(N);
16616
16617   // If the flag operand isn't dead, don't touch this CMOV.
16618   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16619     return SDValue();
16620
16621   SDValue FalseOp = N->getOperand(0);
16622   SDValue TrueOp = N->getOperand(1);
16623   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16624   SDValue Cond = N->getOperand(3);
16625
16626   if (CC == X86::COND_E || CC == X86::COND_NE) {
16627     switch (Cond.getOpcode()) {
16628     default: break;
16629     case X86ISD::BSR:
16630     case X86ISD::BSF:
16631       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16632       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16633         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16634     }
16635   }
16636
16637   SDValue Flags;
16638
16639   Flags = checkBoolTestSetCCCombine(Cond, CC);
16640   if (Flags.getNode() &&
16641       // Extra check as FCMOV only supports a subset of X86 cond.
16642       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16643     SDValue Ops[] = { FalseOp, TrueOp,
16644                       DAG.getConstant(CC, MVT::i8), Flags };
16645     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16646                        Ops, array_lengthof(Ops));
16647   }
16648
16649   // If this is a select between two integer constants, try to do some
16650   // optimizations.  Note that the operands are ordered the opposite of SELECT
16651   // operands.
16652   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16653     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16654       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16655       // larger than FalseC (the false value).
16656       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16657         CC = X86::GetOppositeBranchCondition(CC);
16658         std::swap(TrueC, FalseC);
16659         std::swap(TrueOp, FalseOp);
16660       }
16661
16662       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16663       // This is efficient for any integer data type (including i8/i16) and
16664       // shift amount.
16665       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16666         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16667                            DAG.getConstant(CC, MVT::i8), Cond);
16668
16669         // Zero extend the condition if needed.
16670         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16671
16672         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16673         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16674                            DAG.getConstant(ShAmt, MVT::i8));
16675         if (N->getNumValues() == 2)  // Dead flag value?
16676           return DCI.CombineTo(N, Cond, SDValue());
16677         return Cond;
16678       }
16679
16680       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16681       // for any integer data type, including i8/i16.
16682       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16683         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16684                            DAG.getConstant(CC, MVT::i8), Cond);
16685
16686         // Zero extend the condition if needed.
16687         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16688                            FalseC->getValueType(0), Cond);
16689         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16690                            SDValue(FalseC, 0));
16691
16692         if (N->getNumValues() == 2)  // Dead flag value?
16693           return DCI.CombineTo(N, Cond, SDValue());
16694         return Cond;
16695       }
16696
16697       // Optimize cases that will turn into an LEA instruction.  This requires
16698       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16699       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16700         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16701         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16702
16703         bool isFastMultiplier = false;
16704         if (Diff < 10) {
16705           switch ((unsigned char)Diff) {
16706           default: break;
16707           case 1:  // result = add base, cond
16708           case 2:  // result = lea base(    , cond*2)
16709           case 3:  // result = lea base(cond, cond*2)
16710           case 4:  // result = lea base(    , cond*4)
16711           case 5:  // result = lea base(cond, cond*4)
16712           case 8:  // result = lea base(    , cond*8)
16713           case 9:  // result = lea base(cond, cond*8)
16714             isFastMultiplier = true;
16715             break;
16716           }
16717         }
16718
16719         if (isFastMultiplier) {
16720           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16721           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16722                              DAG.getConstant(CC, MVT::i8), Cond);
16723           // Zero extend the condition if needed.
16724           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16725                              Cond);
16726           // Scale the condition by the difference.
16727           if (Diff != 1)
16728             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16729                                DAG.getConstant(Diff, Cond.getValueType()));
16730
16731           // Add the base if non-zero.
16732           if (FalseC->getAPIntValue() != 0)
16733             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16734                                SDValue(FalseC, 0));
16735           if (N->getNumValues() == 2)  // Dead flag value?
16736             return DCI.CombineTo(N, Cond, SDValue());
16737           return Cond;
16738         }
16739       }
16740     }
16741   }
16742
16743   // Handle these cases:
16744   //   (select (x != c), e, c) -> select (x != c), e, x),
16745   //   (select (x == c), c, e) -> select (x == c), x, e)
16746   // where the c is an integer constant, and the "select" is the combination
16747   // of CMOV and CMP.
16748   //
16749   // The rationale for this change is that the conditional-move from a constant
16750   // needs two instructions, however, conditional-move from a register needs
16751   // only one instruction.
16752   //
16753   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16754   //  some instruction-combining opportunities. This opt needs to be
16755   //  postponed as late as possible.
16756   //
16757   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16758     // the DCI.xxxx conditions are provided to postpone the optimization as
16759     // late as possible.
16760
16761     ConstantSDNode *CmpAgainst = 0;
16762     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16763         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16764         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16765
16766       if (CC == X86::COND_NE &&
16767           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16768         CC = X86::GetOppositeBranchCondition(CC);
16769         std::swap(TrueOp, FalseOp);
16770       }
16771
16772       if (CC == X86::COND_E &&
16773           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16774         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16775                           DAG.getConstant(CC, MVT::i8), Cond };
16776         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16777                            array_lengthof(Ops));
16778       }
16779     }
16780   }
16781
16782   return SDValue();
16783 }
16784
16785 /// PerformMulCombine - Optimize a single multiply with constant into two
16786 /// in order to implement it with two cheaper instructions, e.g.
16787 /// LEA + SHL, LEA + LEA.
16788 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16789                                  TargetLowering::DAGCombinerInfo &DCI) {
16790   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16791     return SDValue();
16792
16793   EVT VT = N->getValueType(0);
16794   if (VT != MVT::i64)
16795     return SDValue();
16796
16797   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16798   if (!C)
16799     return SDValue();
16800   uint64_t MulAmt = C->getZExtValue();
16801   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16802     return SDValue();
16803
16804   uint64_t MulAmt1 = 0;
16805   uint64_t MulAmt2 = 0;
16806   if ((MulAmt % 9) == 0) {
16807     MulAmt1 = 9;
16808     MulAmt2 = MulAmt / 9;
16809   } else if ((MulAmt % 5) == 0) {
16810     MulAmt1 = 5;
16811     MulAmt2 = MulAmt / 5;
16812   } else if ((MulAmt % 3) == 0) {
16813     MulAmt1 = 3;
16814     MulAmt2 = MulAmt / 3;
16815   }
16816   if (MulAmt2 &&
16817       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16818     SDLoc DL(N);
16819
16820     if (isPowerOf2_64(MulAmt2) &&
16821         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16822       // If second multiplifer is pow2, issue it first. We want the multiply by
16823       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16824       // is an add.
16825       std::swap(MulAmt1, MulAmt2);
16826
16827     SDValue NewMul;
16828     if (isPowerOf2_64(MulAmt1))
16829       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16830                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16831     else
16832       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16833                            DAG.getConstant(MulAmt1, VT));
16834
16835     if (isPowerOf2_64(MulAmt2))
16836       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16837                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16838     else
16839       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16840                            DAG.getConstant(MulAmt2, VT));
16841
16842     // Do not add new nodes to DAG combiner worklist.
16843     DCI.CombineTo(N, NewMul, false);
16844   }
16845   return SDValue();
16846 }
16847
16848 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16849   SDValue N0 = N->getOperand(0);
16850   SDValue N1 = N->getOperand(1);
16851   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16852   EVT VT = N0.getValueType();
16853
16854   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16855   // since the result of setcc_c is all zero's or all ones.
16856   if (VT.isInteger() && !VT.isVector() &&
16857       N1C && N0.getOpcode() == ISD::AND &&
16858       N0.getOperand(1).getOpcode() == ISD::Constant) {
16859     SDValue N00 = N0.getOperand(0);
16860     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16861         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16862           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16863          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16864       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16865       APInt ShAmt = N1C->getAPIntValue();
16866       Mask = Mask.shl(ShAmt);
16867       if (Mask != 0)
16868         return DAG.getNode(ISD::AND, SDLoc(N), VT,
16869                            N00, DAG.getConstant(Mask, VT));
16870     }
16871   }
16872
16873   // Hardware support for vector shifts is sparse which makes us scalarize the
16874   // vector operations in many cases. Also, on sandybridge ADD is faster than
16875   // shl.
16876   // (shl V, 1) -> add V,V
16877   if (isSplatVector(N1.getNode())) {
16878     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16879     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16880     // We shift all of the values by one. In many cases we do not have
16881     // hardware support for this operation. This is better expressed as an ADD
16882     // of two values.
16883     if (N1C && (1 == N1C->getZExtValue())) {
16884       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16885     }
16886   }
16887
16888   return SDValue();
16889 }
16890
16891 /// \brief Returns a vector of 0s if the node in input is a vector logical
16892 /// shift by a constant amount which is known to be bigger than or equal 
16893 /// to the vector element size in bits.
16894 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
16895                                       const X86Subtarget *Subtarget) {
16896   EVT VT = N->getValueType(0);
16897
16898   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
16899       (!Subtarget->hasInt256() ||
16900        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
16901     return SDValue();
16902
16903   SDValue Amt = N->getOperand(1);
16904   SDLoc DL(N);
16905   if (isSplatVector(Amt.getNode())) {
16906     SDValue SclrAmt = Amt->getOperand(0);
16907     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
16908       APInt ShiftAmt = C->getAPIntValue();
16909       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
16910
16911       // SSE2/AVX2 logical shifts always return a vector of 0s
16912       // if the shift amount is bigger than or equal to 
16913       // the element size. The constant shift amount will be
16914       // encoded as a 8-bit immediate.
16915       if (ShiftAmt.trunc(8).uge(MaxAmount))
16916         return getZeroVector(VT, Subtarget, DAG, DL);
16917     }
16918   }
16919
16920   return SDValue();
16921 }
16922
16923 /// PerformShiftCombine - Combine shifts.
16924 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16925                                    TargetLowering::DAGCombinerInfo &DCI,
16926                                    const X86Subtarget *Subtarget) {
16927   if (N->getOpcode() == ISD::SHL) {
16928     SDValue V = PerformSHLCombine(N, DAG);
16929     if (V.getNode()) return V;
16930   }
16931
16932   if (N->getOpcode() != ISD::SRA) {
16933     // Try to fold this logical shift into a zero vector.
16934     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
16935     if (V.getNode()) return V;
16936   }
16937
16938   return SDValue();
16939 }
16940
16941 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16942 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16943 // and friends.  Likewise for OR -> CMPNEQSS.
16944 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16945                             TargetLowering::DAGCombinerInfo &DCI,
16946                             const X86Subtarget *Subtarget) {
16947   unsigned opcode;
16948
16949   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16950   // we're requiring SSE2 for both.
16951   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16952     SDValue N0 = N->getOperand(0);
16953     SDValue N1 = N->getOperand(1);
16954     SDValue CMP0 = N0->getOperand(1);
16955     SDValue CMP1 = N1->getOperand(1);
16956     SDLoc DL(N);
16957
16958     // The SETCCs should both refer to the same CMP.
16959     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16960       return SDValue();
16961
16962     SDValue CMP00 = CMP0->getOperand(0);
16963     SDValue CMP01 = CMP0->getOperand(1);
16964     EVT     VT    = CMP00.getValueType();
16965
16966     if (VT == MVT::f32 || VT == MVT::f64) {
16967       bool ExpectingFlags = false;
16968       // Check for any users that want flags:
16969       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16970            !ExpectingFlags && UI != UE; ++UI)
16971         switch (UI->getOpcode()) {
16972         default:
16973         case ISD::BR_CC:
16974         case ISD::BRCOND:
16975         case ISD::SELECT:
16976           ExpectingFlags = true;
16977           break;
16978         case ISD::CopyToReg:
16979         case ISD::SIGN_EXTEND:
16980         case ISD::ZERO_EXTEND:
16981         case ISD::ANY_EXTEND:
16982           break;
16983         }
16984
16985       if (!ExpectingFlags) {
16986         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16987         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16988
16989         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16990           X86::CondCode tmp = cc0;
16991           cc0 = cc1;
16992           cc1 = tmp;
16993         }
16994
16995         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16996             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16997           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16998           X86ISD::NodeType NTOperator = is64BitFP ?
16999             X86ISD::FSETCCsd : X86ISD::FSETCCss;
17000           // FIXME: need symbolic constants for these magic numbers.
17001           // See X86ATTInstPrinter.cpp:printSSECC().
17002           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
17003           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
17004                                               DAG.getConstant(x86cc, MVT::i8));
17005           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
17006                                               OnesOrZeroesF);
17007           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
17008                                       DAG.getConstant(1, MVT::i32));
17009           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
17010           return OneBitOfTruth;
17011         }
17012       }
17013     }
17014   }
17015   return SDValue();
17016 }
17017
17018 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
17019 /// so it can be folded inside ANDNP.
17020 static bool CanFoldXORWithAllOnes(const SDNode *N) {
17021   EVT VT = N->getValueType(0);
17022
17023   // Match direct AllOnes for 128 and 256-bit vectors
17024   if (ISD::isBuildVectorAllOnes(N))
17025     return true;
17026
17027   // Look through a bit convert.
17028   if (N->getOpcode() == ISD::BITCAST)
17029     N = N->getOperand(0).getNode();
17030
17031   // Sometimes the operand may come from a insert_subvector building a 256-bit
17032   // allones vector
17033   if (VT.is256BitVector() &&
17034       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
17035     SDValue V1 = N->getOperand(0);
17036     SDValue V2 = N->getOperand(1);
17037
17038     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
17039         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
17040         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
17041         ISD::isBuildVectorAllOnes(V2.getNode()))
17042       return true;
17043   }
17044
17045   return false;
17046 }
17047
17048 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
17049 // register. In most cases we actually compare or select YMM-sized registers
17050 // and mixing the two types creates horrible code. This method optimizes
17051 // some of the transition sequences.
17052 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
17053                                  TargetLowering::DAGCombinerInfo &DCI,
17054                                  const X86Subtarget *Subtarget) {
17055   EVT VT = N->getValueType(0);
17056   if (!VT.is256BitVector())
17057     return SDValue();
17058
17059   assert((N->getOpcode() == ISD::ANY_EXTEND ||
17060           N->getOpcode() == ISD::ZERO_EXTEND ||
17061           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
17062
17063   SDValue Narrow = N->getOperand(0);
17064   EVT NarrowVT = Narrow->getValueType(0);
17065   if (!NarrowVT.is128BitVector())
17066     return SDValue();
17067
17068   if (Narrow->getOpcode() != ISD::XOR &&
17069       Narrow->getOpcode() != ISD::AND &&
17070       Narrow->getOpcode() != ISD::OR)
17071     return SDValue();
17072
17073   SDValue N0  = Narrow->getOperand(0);
17074   SDValue N1  = Narrow->getOperand(1);
17075   SDLoc DL(Narrow);
17076
17077   // The Left side has to be a trunc.
17078   if (N0.getOpcode() != ISD::TRUNCATE)
17079     return SDValue();
17080
17081   // The type of the truncated inputs.
17082   EVT WideVT = N0->getOperand(0)->getValueType(0);
17083   if (WideVT != VT)
17084     return SDValue();
17085
17086   // The right side has to be a 'trunc' or a constant vector.
17087   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
17088   bool RHSConst = (isSplatVector(N1.getNode()) &&
17089                    isa<ConstantSDNode>(N1->getOperand(0)));
17090   if (!RHSTrunc && !RHSConst)
17091     return SDValue();
17092
17093   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17094
17095   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
17096     return SDValue();
17097
17098   // Set N0 and N1 to hold the inputs to the new wide operation.
17099   N0 = N0->getOperand(0);
17100   if (RHSConst) {
17101     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
17102                      N1->getOperand(0));
17103     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
17104     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
17105   } else if (RHSTrunc) {
17106     N1 = N1->getOperand(0);
17107   }
17108
17109   // Generate the wide operation.
17110   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
17111   unsigned Opcode = N->getOpcode();
17112   switch (Opcode) {
17113   case ISD::ANY_EXTEND:
17114     return Op;
17115   case ISD::ZERO_EXTEND: {
17116     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
17117     APInt Mask = APInt::getAllOnesValue(InBits);
17118     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
17119     return DAG.getNode(ISD::AND, DL, VT,
17120                        Op, DAG.getConstant(Mask, VT));
17121   }
17122   case ISD::SIGN_EXTEND:
17123     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
17124                        Op, DAG.getValueType(NarrowVT));
17125   default:
17126     llvm_unreachable("Unexpected opcode");
17127   }
17128 }
17129
17130 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
17131                                  TargetLowering::DAGCombinerInfo &DCI,
17132                                  const X86Subtarget *Subtarget) {
17133   EVT VT = N->getValueType(0);
17134   if (DCI.isBeforeLegalizeOps())
17135     return SDValue();
17136
17137   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17138   if (R.getNode())
17139     return R;
17140
17141   // Create BLSI, and BLSR instructions
17142   // BLSI is X & (-X)
17143   // BLSR is X & (X-1)
17144   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
17145     SDValue N0 = N->getOperand(0);
17146     SDValue N1 = N->getOperand(1);
17147     SDLoc DL(N);
17148
17149     // Check LHS for neg
17150     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17151         isZero(N0.getOperand(0)))
17152       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17153
17154     // Check RHS for neg
17155     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17156         isZero(N1.getOperand(0)))
17157       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17158
17159     // Check LHS for X-1
17160     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17161         isAllOnes(N0.getOperand(1)))
17162       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17163
17164     // Check RHS for X-1
17165     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17166         isAllOnes(N1.getOperand(1)))
17167       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17168
17169     return SDValue();
17170   }
17171
17172   // Want to form ANDNP nodes:
17173   // 1) In the hopes of then easily combining them with OR and AND nodes
17174   //    to form PBLEND/PSIGN.
17175   // 2) To match ANDN packed intrinsics
17176   if (VT != MVT::v2i64 && VT != MVT::v4i64)
17177     return SDValue();
17178
17179   SDValue N0 = N->getOperand(0);
17180   SDValue N1 = N->getOperand(1);
17181   SDLoc DL(N);
17182
17183   // Check LHS for vnot
17184   if (N0.getOpcode() == ISD::XOR &&
17185       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17186       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17187     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17188
17189   // Check RHS for vnot
17190   if (N1.getOpcode() == ISD::XOR &&
17191       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17192       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17193     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17194
17195   return SDValue();
17196 }
17197
17198 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17199                                 TargetLowering::DAGCombinerInfo &DCI,
17200                                 const X86Subtarget *Subtarget) {
17201   EVT VT = N->getValueType(0);
17202   if (DCI.isBeforeLegalizeOps())
17203     return SDValue();
17204
17205   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17206   if (R.getNode())
17207     return R;
17208
17209   SDValue N0 = N->getOperand(0);
17210   SDValue N1 = N->getOperand(1);
17211
17212   // look for psign/blend
17213   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17214     if (!Subtarget->hasSSSE3() ||
17215         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17216       return SDValue();
17217
17218     // Canonicalize pandn to RHS
17219     if (N0.getOpcode() == X86ISD::ANDNP)
17220       std::swap(N0, N1);
17221     // or (and (m, y), (pandn m, x))
17222     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17223       SDValue Mask = N1.getOperand(0);
17224       SDValue X    = N1.getOperand(1);
17225       SDValue Y;
17226       if (N0.getOperand(0) == Mask)
17227         Y = N0.getOperand(1);
17228       if (N0.getOperand(1) == Mask)
17229         Y = N0.getOperand(0);
17230
17231       // Check to see if the mask appeared in both the AND and ANDNP and
17232       if (!Y.getNode())
17233         return SDValue();
17234
17235       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17236       // Look through mask bitcast.
17237       if (Mask.getOpcode() == ISD::BITCAST)
17238         Mask = Mask.getOperand(0);
17239       if (X.getOpcode() == ISD::BITCAST)
17240         X = X.getOperand(0);
17241       if (Y.getOpcode() == ISD::BITCAST)
17242         Y = Y.getOperand(0);
17243
17244       EVT MaskVT = Mask.getValueType();
17245
17246       // Validate that the Mask operand is a vector sra node.
17247       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
17248       // there is no psrai.b
17249       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
17250       unsigned SraAmt = ~0;
17251       if (Mask.getOpcode() == ISD::SRA) {
17252         SDValue Amt = Mask.getOperand(1);
17253         if (isSplatVector(Amt.getNode())) {
17254           SDValue SclrAmt = Amt->getOperand(0);
17255           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
17256             SraAmt = C->getZExtValue();
17257         }
17258       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
17259         SDValue SraC = Mask.getOperand(1);
17260         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
17261       }
17262       if ((SraAmt + 1) != EltBits)
17263         return SDValue();
17264
17265       SDLoc DL(N);
17266
17267       // Now we know we at least have a plendvb with the mask val.  See if
17268       // we can form a psignb/w/d.
17269       // psign = x.type == y.type == mask.type && y = sub(0, x);
17270       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17271           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17272           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17273         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17274                "Unsupported VT for PSIGN");
17275         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17276         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17277       }
17278       // PBLENDVB only available on SSE 4.1
17279       if (!Subtarget->hasSSE41())
17280         return SDValue();
17281
17282       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
17283
17284       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
17285       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
17286       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
17287       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
17288       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17289     }
17290   }
17291
17292   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
17293     return SDValue();
17294
17295   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
17296   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
17297     std::swap(N0, N1);
17298   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
17299     return SDValue();
17300   if (!N0.hasOneUse() || !N1.hasOneUse())
17301     return SDValue();
17302
17303   SDValue ShAmt0 = N0.getOperand(1);
17304   if (ShAmt0.getValueType() != MVT::i8)
17305     return SDValue();
17306   SDValue ShAmt1 = N1.getOperand(1);
17307   if (ShAmt1.getValueType() != MVT::i8)
17308     return SDValue();
17309   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17310     ShAmt0 = ShAmt0.getOperand(0);
17311   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17312     ShAmt1 = ShAmt1.getOperand(0);
17313
17314   SDLoc DL(N);
17315   unsigned Opc = X86ISD::SHLD;
17316   SDValue Op0 = N0.getOperand(0);
17317   SDValue Op1 = N1.getOperand(0);
17318   if (ShAmt0.getOpcode() == ISD::SUB) {
17319     Opc = X86ISD::SHRD;
17320     std::swap(Op0, Op1);
17321     std::swap(ShAmt0, ShAmt1);
17322   }
17323
17324   unsigned Bits = VT.getSizeInBits();
17325   if (ShAmt1.getOpcode() == ISD::SUB) {
17326     SDValue Sum = ShAmt1.getOperand(0);
17327     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17328       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17329       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17330         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17331       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17332         return DAG.getNode(Opc, DL, VT,
17333                            Op0, Op1,
17334                            DAG.getNode(ISD::TRUNCATE, DL,
17335                                        MVT::i8, ShAmt0));
17336     }
17337   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17338     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17339     if (ShAmt0C &&
17340         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
17341       return DAG.getNode(Opc, DL, VT,
17342                          N0.getOperand(0), N1.getOperand(0),
17343                          DAG.getNode(ISD::TRUNCATE, DL,
17344                                        MVT::i8, ShAmt0));
17345   }
17346
17347   return SDValue();
17348 }
17349
17350 // Generate NEG and CMOV for integer abs.
17351 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
17352   EVT VT = N->getValueType(0);
17353
17354   // Since X86 does not have CMOV for 8-bit integer, we don't convert
17355   // 8-bit integer abs to NEG and CMOV.
17356   if (VT.isInteger() && VT.getSizeInBits() == 8)
17357     return SDValue();
17358
17359   SDValue N0 = N->getOperand(0);
17360   SDValue N1 = N->getOperand(1);
17361   SDLoc DL(N);
17362
17363   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
17364   // and change it to SUB and CMOV.
17365   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
17366       N0.getOpcode() == ISD::ADD &&
17367       N0.getOperand(1) == N1 &&
17368       N1.getOpcode() == ISD::SRA &&
17369       N1.getOperand(0) == N0.getOperand(0))
17370     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
17371       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
17372         // Generate SUB & CMOV.
17373         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
17374                                   DAG.getConstant(0, VT), N0.getOperand(0));
17375
17376         SDValue Ops[] = { N0.getOperand(0), Neg,
17377                           DAG.getConstant(X86::COND_GE, MVT::i8),
17378                           SDValue(Neg.getNode(), 1) };
17379         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
17380                            Ops, array_lengthof(Ops));
17381       }
17382   return SDValue();
17383 }
17384
17385 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
17386 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
17387                                  TargetLowering::DAGCombinerInfo &DCI,
17388                                  const X86Subtarget *Subtarget) {
17389   EVT VT = N->getValueType(0);
17390   if (DCI.isBeforeLegalizeOps())
17391     return SDValue();
17392
17393   if (Subtarget->hasCMov()) {
17394     SDValue RV = performIntegerAbsCombine(N, DAG);
17395     if (RV.getNode())
17396       return RV;
17397   }
17398
17399   // Try forming BMI if it is available.
17400   if (!Subtarget->hasBMI())
17401     return SDValue();
17402
17403   if (VT != MVT::i32 && VT != MVT::i64)
17404     return SDValue();
17405
17406   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
17407
17408   // Create BLSMSK instructions by finding X ^ (X-1)
17409   SDValue N0 = N->getOperand(0);
17410   SDValue N1 = N->getOperand(1);
17411   SDLoc DL(N);
17412
17413   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17414       isAllOnes(N0.getOperand(1)))
17415     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
17416
17417   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17418       isAllOnes(N1.getOperand(1)))
17419     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
17420
17421   return SDValue();
17422 }
17423
17424 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
17425 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
17426                                   TargetLowering::DAGCombinerInfo &DCI,
17427                                   const X86Subtarget *Subtarget) {
17428   LoadSDNode *Ld = cast<LoadSDNode>(N);
17429   EVT RegVT = Ld->getValueType(0);
17430   EVT MemVT = Ld->getMemoryVT();
17431   SDLoc dl(Ld);
17432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17433   unsigned RegSz = RegVT.getSizeInBits();
17434
17435   // On Sandybridge unaligned 256bit loads are inefficient.
17436   ISD::LoadExtType Ext = Ld->getExtensionType();
17437   unsigned Alignment = Ld->getAlignment();
17438   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
17439   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
17440       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
17441     unsigned NumElems = RegVT.getVectorNumElements();
17442     if (NumElems < 2)
17443       return SDValue();
17444
17445     SDValue Ptr = Ld->getBasePtr();
17446     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
17447
17448     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17449                                   NumElems/2);
17450     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17451                                 Ld->getPointerInfo(), Ld->isVolatile(),
17452                                 Ld->isNonTemporal(), Ld->isInvariant(),
17453                                 Alignment);
17454     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17455     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17456                                 Ld->getPointerInfo(), Ld->isVolatile(),
17457                                 Ld->isNonTemporal(), Ld->isInvariant(),
17458                                 std::min(16U, Alignment));
17459     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17460                              Load1.getValue(1),
17461                              Load2.getValue(1));
17462
17463     SDValue NewVec = DAG.getUNDEF(RegVT);
17464     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
17465     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
17466     return DCI.CombineTo(N, NewVec, TF, true);
17467   }
17468
17469   // If this is a vector EXT Load then attempt to optimize it using a
17470   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
17471   // expansion is still better than scalar code.
17472   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
17473   // emit a shuffle and a arithmetic shift.
17474   // TODO: It is possible to support ZExt by zeroing the undef values
17475   // during the shuffle phase or after the shuffle.
17476   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
17477       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
17478     assert(MemVT != RegVT && "Cannot extend to the same type");
17479     assert(MemVT.isVector() && "Must load a vector from memory");
17480
17481     unsigned NumElems = RegVT.getVectorNumElements();
17482     unsigned MemSz = MemVT.getSizeInBits();
17483     assert(RegSz > MemSz && "Register size must be greater than the mem size");
17484
17485     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
17486       return SDValue();
17487
17488     // All sizes must be a power of two.
17489     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
17490       return SDValue();
17491
17492     // Attempt to load the original value using scalar loads.
17493     // Find the largest scalar type that divides the total loaded size.
17494     MVT SclrLoadTy = MVT::i8;
17495     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17496          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17497       MVT Tp = (MVT::SimpleValueType)tp;
17498       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
17499         SclrLoadTy = Tp;
17500       }
17501     }
17502
17503     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17504     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
17505         (64 <= MemSz))
17506       SclrLoadTy = MVT::f64;
17507
17508     // Calculate the number of scalar loads that we need to perform
17509     // in order to load our vector from memory.
17510     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
17511     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
17512       return SDValue();
17513
17514     unsigned loadRegZize = RegSz;
17515     if (Ext == ISD::SEXTLOAD && RegSz == 256)
17516       loadRegZize /= 2;
17517
17518     // Represent our vector as a sequence of elements which are the
17519     // largest scalar that we can load.
17520     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
17521       loadRegZize/SclrLoadTy.getSizeInBits());
17522
17523     // Represent the data using the same element type that is stored in
17524     // memory. In practice, we ''widen'' MemVT.
17525     EVT WideVecVT =
17526           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17527                        loadRegZize/MemVT.getScalarType().getSizeInBits());
17528
17529     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
17530       "Invalid vector type");
17531
17532     // We can't shuffle using an illegal type.
17533     if (!TLI.isTypeLegal(WideVecVT))
17534       return SDValue();
17535
17536     SmallVector<SDValue, 8> Chains;
17537     SDValue Ptr = Ld->getBasePtr();
17538     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
17539                                         TLI.getPointerTy());
17540     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
17541
17542     for (unsigned i = 0; i < NumLoads; ++i) {
17543       // Perform a single load.
17544       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
17545                                        Ptr, Ld->getPointerInfo(),
17546                                        Ld->isVolatile(), Ld->isNonTemporal(),
17547                                        Ld->isInvariant(), Ld->getAlignment());
17548       Chains.push_back(ScalarLoad.getValue(1));
17549       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
17550       // another round of DAGCombining.
17551       if (i == 0)
17552         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
17553       else
17554         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
17555                           ScalarLoad, DAG.getIntPtrConstant(i));
17556
17557       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17558     }
17559
17560     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17561                                Chains.size());
17562
17563     // Bitcast the loaded value to a vector of the original element type, in
17564     // the size of the target vector type.
17565     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
17566     unsigned SizeRatio = RegSz/MemSz;
17567
17568     if (Ext == ISD::SEXTLOAD) {
17569       // If we have SSE4.1 we can directly emit a VSEXT node.
17570       if (Subtarget->hasSSE41()) {
17571         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
17572         return DCI.CombineTo(N, Sext, TF, true);
17573       }
17574
17575       // Otherwise we'll shuffle the small elements in the high bits of the
17576       // larger type and perform an arithmetic shift. If the shift is not legal
17577       // it's better to scalarize.
17578       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
17579         return SDValue();
17580
17581       // Redistribute the loaded elements into the different locations.
17582       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17583       for (unsigned i = 0; i != NumElems; ++i)
17584         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
17585
17586       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17587                                            DAG.getUNDEF(WideVecVT),
17588                                            &ShuffleVec[0]);
17589
17590       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17591
17592       // Build the arithmetic shift.
17593       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
17594                      MemVT.getVectorElementType().getSizeInBits();
17595       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
17596                           DAG.getConstant(Amt, RegVT));
17597
17598       return DCI.CombineTo(N, Shuff, TF, true);
17599     }
17600
17601     // Redistribute the loaded elements into the different locations.
17602     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17603     for (unsigned i = 0; i != NumElems; ++i)
17604       ShuffleVec[i*SizeRatio] = i;
17605
17606     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17607                                          DAG.getUNDEF(WideVecVT),
17608                                          &ShuffleVec[0]);
17609
17610     // Bitcast to the requested type.
17611     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17612     // Replace the original load with the new sequence
17613     // and return the new chain.
17614     return DCI.CombineTo(N, Shuff, TF, true);
17615   }
17616
17617   return SDValue();
17618 }
17619
17620 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17621 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17622                                    const X86Subtarget *Subtarget) {
17623   StoreSDNode *St = cast<StoreSDNode>(N);
17624   EVT VT = St->getValue().getValueType();
17625   EVT StVT = St->getMemoryVT();
17626   SDLoc dl(St);
17627   SDValue StoredVal = St->getOperand(1);
17628   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17629
17630   // If we are saving a concatenation of two XMM registers, perform two stores.
17631   // On Sandy Bridge, 256-bit memory operations are executed by two
17632   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17633   // memory  operation.
17634   unsigned Alignment = St->getAlignment();
17635   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17636   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17637       StVT == VT && !IsAligned) {
17638     unsigned NumElems = VT.getVectorNumElements();
17639     if (NumElems < 2)
17640       return SDValue();
17641
17642     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17643     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17644
17645     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17646     SDValue Ptr0 = St->getBasePtr();
17647     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17648
17649     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17650                                 St->getPointerInfo(), St->isVolatile(),
17651                                 St->isNonTemporal(), Alignment);
17652     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17653                                 St->getPointerInfo(), St->isVolatile(),
17654                                 St->isNonTemporal(),
17655                                 std::min(16U, Alignment));
17656     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17657   }
17658
17659   // Optimize trunc store (of multiple scalars) to shuffle and store.
17660   // First, pack all of the elements in one place. Next, store to memory
17661   // in fewer chunks.
17662   if (St->isTruncatingStore() && VT.isVector()) {
17663     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17664     unsigned NumElems = VT.getVectorNumElements();
17665     assert(StVT != VT && "Cannot truncate to the same type");
17666     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17667     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17668
17669     // From, To sizes and ElemCount must be pow of two
17670     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17671     // We are going to use the original vector elt for storing.
17672     // Accumulated smaller vector elements must be a multiple of the store size.
17673     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17674
17675     unsigned SizeRatio  = FromSz / ToSz;
17676
17677     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17678
17679     // Create a type on which we perform the shuffle
17680     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17681             StVT.getScalarType(), NumElems*SizeRatio);
17682
17683     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17684
17685     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17686     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17687     for (unsigned i = 0; i != NumElems; ++i)
17688       ShuffleVec[i] = i * SizeRatio;
17689
17690     // Can't shuffle using an illegal type.
17691     if (!TLI.isTypeLegal(WideVecVT))
17692       return SDValue();
17693
17694     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17695                                          DAG.getUNDEF(WideVecVT),
17696                                          &ShuffleVec[0]);
17697     // At this point all of the data is stored at the bottom of the
17698     // register. We now need to save it to mem.
17699
17700     // Find the largest store unit
17701     MVT StoreType = MVT::i8;
17702     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17703          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17704       MVT Tp = (MVT::SimpleValueType)tp;
17705       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17706         StoreType = Tp;
17707     }
17708
17709     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17710     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17711         (64 <= NumElems * ToSz))
17712       StoreType = MVT::f64;
17713
17714     // Bitcast the original vector into a vector of store-size units
17715     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17716             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17717     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17718     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17719     SmallVector<SDValue, 8> Chains;
17720     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17721                                         TLI.getPointerTy());
17722     SDValue Ptr = St->getBasePtr();
17723
17724     // Perform one or more big stores into memory.
17725     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17726       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17727                                    StoreType, ShuffWide,
17728                                    DAG.getIntPtrConstant(i));
17729       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17730                                 St->getPointerInfo(), St->isVolatile(),
17731                                 St->isNonTemporal(), St->getAlignment());
17732       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17733       Chains.push_back(Ch);
17734     }
17735
17736     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17737                                Chains.size());
17738   }
17739
17740   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17741   // the FP state in cases where an emms may be missing.
17742   // A preferable solution to the general problem is to figure out the right
17743   // places to insert EMMS.  This qualifies as a quick hack.
17744
17745   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17746   if (VT.getSizeInBits() != 64)
17747     return SDValue();
17748
17749   const Function *F = DAG.getMachineFunction().getFunction();
17750   bool NoImplicitFloatOps = F->getAttributes().
17751     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17752   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17753                      && Subtarget->hasSSE2();
17754   if ((VT.isVector() ||
17755        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17756       isa<LoadSDNode>(St->getValue()) &&
17757       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17758       St->getChain().hasOneUse() && !St->isVolatile()) {
17759     SDNode* LdVal = St->getValue().getNode();
17760     LoadSDNode *Ld = 0;
17761     int TokenFactorIndex = -1;
17762     SmallVector<SDValue, 8> Ops;
17763     SDNode* ChainVal = St->getChain().getNode();
17764     // Must be a store of a load.  We currently handle two cases:  the load
17765     // is a direct child, and it's under an intervening TokenFactor.  It is
17766     // possible to dig deeper under nested TokenFactors.
17767     if (ChainVal == LdVal)
17768       Ld = cast<LoadSDNode>(St->getChain());
17769     else if (St->getValue().hasOneUse() &&
17770              ChainVal->getOpcode() == ISD::TokenFactor) {
17771       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17772         if (ChainVal->getOperand(i).getNode() == LdVal) {
17773           TokenFactorIndex = i;
17774           Ld = cast<LoadSDNode>(St->getValue());
17775         } else
17776           Ops.push_back(ChainVal->getOperand(i));
17777       }
17778     }
17779
17780     if (!Ld || !ISD::isNormalLoad(Ld))
17781       return SDValue();
17782
17783     // If this is not the MMX case, i.e. we are just turning i64 load/store
17784     // into f64 load/store, avoid the transformation if there are multiple
17785     // uses of the loaded value.
17786     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17787       return SDValue();
17788
17789     SDLoc LdDL(Ld);
17790     SDLoc StDL(N);
17791     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17792     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17793     // pair instead.
17794     if (Subtarget->is64Bit() || F64IsLegal) {
17795       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17796       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17797                                   Ld->getPointerInfo(), Ld->isVolatile(),
17798                                   Ld->isNonTemporal(), Ld->isInvariant(),
17799                                   Ld->getAlignment());
17800       SDValue NewChain = NewLd.getValue(1);
17801       if (TokenFactorIndex != -1) {
17802         Ops.push_back(NewChain);
17803         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17804                                Ops.size());
17805       }
17806       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17807                           St->getPointerInfo(),
17808                           St->isVolatile(), St->isNonTemporal(),
17809                           St->getAlignment());
17810     }
17811
17812     // Otherwise, lower to two pairs of 32-bit loads / stores.
17813     SDValue LoAddr = Ld->getBasePtr();
17814     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17815                                  DAG.getConstant(4, MVT::i32));
17816
17817     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17818                                Ld->getPointerInfo(),
17819                                Ld->isVolatile(), Ld->isNonTemporal(),
17820                                Ld->isInvariant(), Ld->getAlignment());
17821     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17822                                Ld->getPointerInfo().getWithOffset(4),
17823                                Ld->isVolatile(), Ld->isNonTemporal(),
17824                                Ld->isInvariant(),
17825                                MinAlign(Ld->getAlignment(), 4));
17826
17827     SDValue NewChain = LoLd.getValue(1);
17828     if (TokenFactorIndex != -1) {
17829       Ops.push_back(LoLd);
17830       Ops.push_back(HiLd);
17831       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17832                              Ops.size());
17833     }
17834
17835     LoAddr = St->getBasePtr();
17836     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17837                          DAG.getConstant(4, MVT::i32));
17838
17839     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17840                                 St->getPointerInfo(),
17841                                 St->isVolatile(), St->isNonTemporal(),
17842                                 St->getAlignment());
17843     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17844                                 St->getPointerInfo().getWithOffset(4),
17845                                 St->isVolatile(),
17846                                 St->isNonTemporal(),
17847                                 MinAlign(St->getAlignment(), 4));
17848     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17849   }
17850   return SDValue();
17851 }
17852
17853 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17854 /// and return the operands for the horizontal operation in LHS and RHS.  A
17855 /// horizontal operation performs the binary operation on successive elements
17856 /// of its first operand, then on successive elements of its second operand,
17857 /// returning the resulting values in a vector.  For example, if
17858 ///   A = < float a0, float a1, float a2, float a3 >
17859 /// and
17860 ///   B = < float b0, float b1, float b2, float b3 >
17861 /// then the result of doing a horizontal operation on A and B is
17862 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17863 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17864 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17865 /// set to A, RHS to B, and the routine returns 'true'.
17866 /// Note that the binary operation should have the property that if one of the
17867 /// operands is UNDEF then the result is UNDEF.
17868 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17869   // Look for the following pattern: if
17870   //   A = < float a0, float a1, float a2, float a3 >
17871   //   B = < float b0, float b1, float b2, float b3 >
17872   // and
17873   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17874   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17875   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17876   // which is A horizontal-op B.
17877
17878   // At least one of the operands should be a vector shuffle.
17879   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17880       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17881     return false;
17882
17883   MVT VT = LHS.getSimpleValueType();
17884
17885   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17886          "Unsupported vector type for horizontal add/sub");
17887
17888   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17889   // operate independently on 128-bit lanes.
17890   unsigned NumElts = VT.getVectorNumElements();
17891   unsigned NumLanes = VT.getSizeInBits()/128;
17892   unsigned NumLaneElts = NumElts / NumLanes;
17893   assert((NumLaneElts % 2 == 0) &&
17894          "Vector type should have an even number of elements in each lane");
17895   unsigned HalfLaneElts = NumLaneElts/2;
17896
17897   // View LHS in the form
17898   //   LHS = VECTOR_SHUFFLE A, B, LMask
17899   // If LHS is not a shuffle then pretend it is the shuffle
17900   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17901   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17902   // type VT.
17903   SDValue A, B;
17904   SmallVector<int, 16> LMask(NumElts);
17905   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17906     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17907       A = LHS.getOperand(0);
17908     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17909       B = LHS.getOperand(1);
17910     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17911     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17912   } else {
17913     if (LHS.getOpcode() != ISD::UNDEF)
17914       A = LHS;
17915     for (unsigned i = 0; i != NumElts; ++i)
17916       LMask[i] = i;
17917   }
17918
17919   // Likewise, view RHS in the form
17920   //   RHS = VECTOR_SHUFFLE C, D, RMask
17921   SDValue C, D;
17922   SmallVector<int, 16> RMask(NumElts);
17923   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17924     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17925       C = RHS.getOperand(0);
17926     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17927       D = RHS.getOperand(1);
17928     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17929     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17930   } else {
17931     if (RHS.getOpcode() != ISD::UNDEF)
17932       C = RHS;
17933     for (unsigned i = 0; i != NumElts; ++i)
17934       RMask[i] = i;
17935   }
17936
17937   // Check that the shuffles are both shuffling the same vectors.
17938   if (!(A == C && B == D) && !(A == D && B == C))
17939     return false;
17940
17941   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17942   if (!A.getNode() && !B.getNode())
17943     return false;
17944
17945   // If A and B occur in reverse order in RHS, then "swap" them (which means
17946   // rewriting the mask).
17947   if (A != C)
17948     CommuteVectorShuffleMask(RMask, NumElts);
17949
17950   // At this point LHS and RHS are equivalent to
17951   //   LHS = VECTOR_SHUFFLE A, B, LMask
17952   //   RHS = VECTOR_SHUFFLE A, B, RMask
17953   // Check that the masks correspond to performing a horizontal operation.
17954   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
17955     for (unsigned i = 0; i != NumLaneElts; ++i) {
17956       int LIdx = LMask[i+l], RIdx = RMask[i+l];
17957
17958       // Ignore any UNDEF components.
17959       if (LIdx < 0 || RIdx < 0 ||
17960           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17961           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17962         continue;
17963
17964       // Check that successive elements are being operated on.  If not, this is
17965       // not a horizontal operation.
17966       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
17967       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
17968       if (!(LIdx == Index && RIdx == Index + 1) &&
17969           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17970         return false;
17971     }
17972   }
17973
17974   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17975   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17976   return true;
17977 }
17978
17979 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17980 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17981                                   const X86Subtarget *Subtarget) {
17982   EVT VT = N->getValueType(0);
17983   SDValue LHS = N->getOperand(0);
17984   SDValue RHS = N->getOperand(1);
17985
17986   // Try to synthesize horizontal adds from adds of shuffles.
17987   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17988        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17989       isHorizontalBinOp(LHS, RHS, true))
17990     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17991   return SDValue();
17992 }
17993
17994 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17995 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17996                                   const X86Subtarget *Subtarget) {
17997   EVT VT = N->getValueType(0);
17998   SDValue LHS = N->getOperand(0);
17999   SDValue RHS = N->getOperand(1);
18000
18001   // Try to synthesize horizontal subs from subs of shuffles.
18002   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18003        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18004       isHorizontalBinOp(LHS, RHS, false))
18005     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
18006   return SDValue();
18007 }
18008
18009 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
18010 /// X86ISD::FXOR nodes.
18011 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
18012   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
18013   // F[X]OR(0.0, x) -> x
18014   // F[X]OR(x, 0.0) -> x
18015   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18016     if (C->getValueAPF().isPosZero())
18017       return N->getOperand(1);
18018   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18019     if (C->getValueAPF().isPosZero())
18020       return N->getOperand(0);
18021   return SDValue();
18022 }
18023
18024 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
18025 /// X86ISD::FMAX nodes.
18026 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
18027   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
18028
18029   // Only perform optimizations if UnsafeMath is used.
18030   if (!DAG.getTarget().Options.UnsafeFPMath)
18031     return SDValue();
18032
18033   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
18034   // into FMINC and FMAXC, which are Commutative operations.
18035   unsigned NewOp = 0;
18036   switch (N->getOpcode()) {
18037     default: llvm_unreachable("unknown opcode");
18038     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
18039     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
18040   }
18041
18042   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
18043                      N->getOperand(0), N->getOperand(1));
18044 }
18045
18046 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
18047 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
18048   // FAND(0.0, x) -> 0.0
18049   // FAND(x, 0.0) -> 0.0
18050   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18051     if (C->getValueAPF().isPosZero())
18052       return N->getOperand(0);
18053   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18054     if (C->getValueAPF().isPosZero())
18055       return N->getOperand(1);
18056   return SDValue();
18057 }
18058
18059 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
18060 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
18061   // FANDN(x, 0.0) -> 0.0
18062   // FANDN(0.0, x) -> x
18063   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
18064     if (C->getValueAPF().isPosZero())
18065       return N->getOperand(1);
18066   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
18067     if (C->getValueAPF().isPosZero())
18068       return N->getOperand(1);
18069   return SDValue();
18070 }
18071
18072 static SDValue PerformBTCombine(SDNode *N,
18073                                 SelectionDAG &DAG,
18074                                 TargetLowering::DAGCombinerInfo &DCI) {
18075   // BT ignores high bits in the bit index operand.
18076   SDValue Op1 = N->getOperand(1);
18077   if (Op1.hasOneUse()) {
18078     unsigned BitWidth = Op1.getValueSizeInBits();
18079     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
18080     APInt KnownZero, KnownOne;
18081     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
18082                                           !DCI.isBeforeLegalizeOps());
18083     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18084     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
18085         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
18086       DCI.CommitTargetLoweringOpt(TLO);
18087   }
18088   return SDValue();
18089 }
18090
18091 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
18092   SDValue Op = N->getOperand(0);
18093   if (Op.getOpcode() == ISD::BITCAST)
18094     Op = Op.getOperand(0);
18095   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
18096   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
18097       VT.getVectorElementType().getSizeInBits() ==
18098       OpVT.getVectorElementType().getSizeInBits()) {
18099     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
18100   }
18101   return SDValue();
18102 }
18103
18104 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
18105                                                const X86Subtarget *Subtarget) {
18106   EVT VT = N->getValueType(0);
18107   if (!VT.isVector())
18108     return SDValue();
18109
18110   SDValue N0 = N->getOperand(0);
18111   SDValue N1 = N->getOperand(1);
18112   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
18113   SDLoc dl(N);
18114
18115   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
18116   // both SSE and AVX2 since there is no sign-extended shift right
18117   // operation on a vector with 64-bit elements.
18118   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
18119   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
18120   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
18121       N0.getOpcode() == ISD::SIGN_EXTEND)) {
18122     SDValue N00 = N0.getOperand(0);
18123
18124     // EXTLOAD has a better solution on AVX2,
18125     // it may be replaced with X86ISD::VSEXT node.
18126     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
18127       if (!ISD::isNormalLoad(N00.getNode()))
18128         return SDValue();
18129
18130     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
18131         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
18132                                   N00, N1);
18133       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
18134     }
18135   }
18136   return SDValue();
18137 }
18138
18139 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
18140                                   TargetLowering::DAGCombinerInfo &DCI,
18141                                   const X86Subtarget *Subtarget) {
18142   if (!DCI.isBeforeLegalizeOps())
18143     return SDValue();
18144
18145   if (!Subtarget->hasFp256())
18146     return SDValue();
18147
18148   EVT VT = N->getValueType(0);
18149   if (VT.isVector() && VT.getSizeInBits() == 256) {
18150     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18151     if (R.getNode())
18152       return R;
18153   }
18154
18155   return SDValue();
18156 }
18157
18158 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18159                                  const X86Subtarget* Subtarget) {
18160   SDLoc dl(N);
18161   EVT VT = N->getValueType(0);
18162
18163   // Let legalize expand this if it isn't a legal type yet.
18164   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18165     return SDValue();
18166
18167   EVT ScalarVT = VT.getScalarType();
18168   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18169       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18170     return SDValue();
18171
18172   SDValue A = N->getOperand(0);
18173   SDValue B = N->getOperand(1);
18174   SDValue C = N->getOperand(2);
18175
18176   bool NegA = (A.getOpcode() == ISD::FNEG);
18177   bool NegB = (B.getOpcode() == ISD::FNEG);
18178   bool NegC = (C.getOpcode() == ISD::FNEG);
18179
18180   // Negative multiplication when NegA xor NegB
18181   bool NegMul = (NegA != NegB);
18182   if (NegA)
18183     A = A.getOperand(0);
18184   if (NegB)
18185     B = B.getOperand(0);
18186   if (NegC)
18187     C = C.getOperand(0);
18188
18189   unsigned Opcode;
18190   if (!NegMul)
18191     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18192   else
18193     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18194
18195   return DAG.getNode(Opcode, dl, VT, A, B, C);
18196 }
18197
18198 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18199                                   TargetLowering::DAGCombinerInfo &DCI,
18200                                   const X86Subtarget *Subtarget) {
18201   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
18202   //           (and (i32 x86isd::setcc_carry), 1)
18203   // This eliminates the zext. This transformation is necessary because
18204   // ISD::SETCC is always legalized to i8.
18205   SDLoc dl(N);
18206   SDValue N0 = N->getOperand(0);
18207   EVT VT = N->getValueType(0);
18208
18209   if (N0.getOpcode() == ISD::AND &&
18210       N0.hasOneUse() &&
18211       N0.getOperand(0).hasOneUse()) {
18212     SDValue N00 = N0.getOperand(0);
18213     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18214       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18215       if (!C || C->getZExtValue() != 1)
18216         return SDValue();
18217       return DAG.getNode(ISD::AND, dl, VT,
18218                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18219                                      N00.getOperand(0), N00.getOperand(1)),
18220                          DAG.getConstant(1, VT));
18221     }
18222   }
18223
18224   if (VT.is256BitVector()) {
18225     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18226     if (R.getNode())
18227       return R;
18228   }
18229
18230   return SDValue();
18231 }
18232
18233 // Optimize x == -y --> x+y == 0
18234 //          x != -y --> x+y != 0
18235 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
18236   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
18237   SDValue LHS = N->getOperand(0);
18238   SDValue RHS = N->getOperand(1);
18239
18240   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
18241     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
18242       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
18243         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18244                                    LHS.getValueType(), RHS, LHS.getOperand(1));
18245         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18246                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18247       }
18248   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
18249     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
18250       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
18251         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18252                                    RHS.getValueType(), LHS, RHS.getOperand(1));
18253         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18254                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18255       }
18256   return SDValue();
18257 }
18258
18259 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
18260 // as "sbb reg,reg", since it can be extended without zext and produces
18261 // an all-ones bit which is more useful than 0/1 in some cases.
18262 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
18263   return DAG.getNode(ISD::AND, DL, MVT::i8,
18264                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
18265                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
18266                      DAG.getConstant(1, MVT::i8));
18267 }
18268
18269 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
18270 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
18271                                    TargetLowering::DAGCombinerInfo &DCI,
18272                                    const X86Subtarget *Subtarget) {
18273   SDLoc DL(N);
18274   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
18275   SDValue EFLAGS = N->getOperand(1);
18276
18277   if (CC == X86::COND_A) {
18278     // Try to convert COND_A into COND_B in an attempt to facilitate
18279     // materializing "setb reg".
18280     //
18281     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
18282     // cannot take an immediate as its first operand.
18283     //
18284     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
18285         EFLAGS.getValueType().isInteger() &&
18286         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
18287       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
18288                                    EFLAGS.getNode()->getVTList(),
18289                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
18290       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
18291       return MaterializeSETB(DL, NewEFLAGS, DAG);
18292     }
18293   }
18294
18295   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
18296   // a zext and produces an all-ones bit which is more useful than 0/1 in some
18297   // cases.
18298   if (CC == X86::COND_B)
18299     return MaterializeSETB(DL, EFLAGS, DAG);
18300
18301   SDValue Flags;
18302
18303   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18304   if (Flags.getNode()) {
18305     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18306     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
18307   }
18308
18309   return SDValue();
18310 }
18311
18312 // Optimize branch condition evaluation.
18313 //
18314 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18315                                     TargetLowering::DAGCombinerInfo &DCI,
18316                                     const X86Subtarget *Subtarget) {
18317   SDLoc DL(N);
18318   SDValue Chain = N->getOperand(0);
18319   SDValue Dest = N->getOperand(1);
18320   SDValue EFLAGS = N->getOperand(3);
18321   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18322
18323   SDValue Flags;
18324
18325   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18326   if (Flags.getNode()) {
18327     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18328     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18329                        Flags);
18330   }
18331
18332   return SDValue();
18333 }
18334
18335 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18336                                         const X86TargetLowering *XTLI) {
18337   SDValue Op0 = N->getOperand(0);
18338   EVT InVT = Op0->getValueType(0);
18339
18340   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
18341   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
18342     SDLoc dl(N);
18343     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
18344     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
18345     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
18346   }
18347
18348   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
18349   // a 32-bit target where SSE doesn't support i64->FP operations.
18350   if (Op0.getOpcode() == ISD::LOAD) {
18351     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
18352     EVT VT = Ld->getValueType(0);
18353     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
18354         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
18355         !XTLI->getSubtarget()->is64Bit() &&
18356         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18357       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
18358                                           Ld->getChain(), Op0, DAG);
18359       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
18360       return FILDChain;
18361     }
18362   }
18363   return SDValue();
18364 }
18365
18366 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
18367 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
18368                                  X86TargetLowering::DAGCombinerInfo &DCI) {
18369   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
18370   // the result is either zero or one (depending on the input carry bit).
18371   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
18372   if (X86::isZeroNode(N->getOperand(0)) &&
18373       X86::isZeroNode(N->getOperand(1)) &&
18374       // We don't have a good way to replace an EFLAGS use, so only do this when
18375       // dead right now.
18376       SDValue(N, 1).use_empty()) {
18377     SDLoc DL(N);
18378     EVT VT = N->getValueType(0);
18379     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
18380     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
18381                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
18382                                            DAG.getConstant(X86::COND_B,MVT::i8),
18383                                            N->getOperand(2)),
18384                                DAG.getConstant(1, VT));
18385     return DCI.CombineTo(N, Res1, CarryOut);
18386   }
18387
18388   return SDValue();
18389 }
18390
18391 // fold (add Y, (sete  X, 0)) -> adc  0, Y
18392 //      (add Y, (setne X, 0)) -> sbb -1, Y
18393 //      (sub (sete  X, 0), Y) -> sbb  0, Y
18394 //      (sub (setne X, 0), Y) -> adc -1, Y
18395 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
18396   SDLoc DL(N);
18397
18398   // Look through ZExts.
18399   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
18400   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
18401     return SDValue();
18402
18403   SDValue SetCC = Ext.getOperand(0);
18404   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
18405     return SDValue();
18406
18407   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
18408   if (CC != X86::COND_E && CC != X86::COND_NE)
18409     return SDValue();
18410
18411   SDValue Cmp = SetCC.getOperand(1);
18412   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
18413       !X86::isZeroNode(Cmp.getOperand(1)) ||
18414       !Cmp.getOperand(0).getValueType().isInteger())
18415     return SDValue();
18416
18417   SDValue CmpOp0 = Cmp.getOperand(0);
18418   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
18419                                DAG.getConstant(1, CmpOp0.getValueType()));
18420
18421   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
18422   if (CC == X86::COND_NE)
18423     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
18424                        DL, OtherVal.getValueType(), OtherVal,
18425                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
18426   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
18427                      DL, OtherVal.getValueType(), OtherVal,
18428                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
18429 }
18430
18431 /// PerformADDCombine - Do target-specific dag combines on integer adds.
18432 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
18433                                  const X86Subtarget *Subtarget) {
18434   EVT VT = N->getValueType(0);
18435   SDValue Op0 = N->getOperand(0);
18436   SDValue Op1 = N->getOperand(1);
18437
18438   // Try to synthesize horizontal adds from adds of shuffles.
18439   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18440        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18441       isHorizontalBinOp(Op0, Op1, true))
18442     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
18443
18444   return OptimizeConditionalInDecrement(N, DAG);
18445 }
18446
18447 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
18448                                  const X86Subtarget *Subtarget) {
18449   SDValue Op0 = N->getOperand(0);
18450   SDValue Op1 = N->getOperand(1);
18451
18452   // X86 can't encode an immediate LHS of a sub. See if we can push the
18453   // negation into a preceding instruction.
18454   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
18455     // If the RHS of the sub is a XOR with one use and a constant, invert the
18456     // immediate. Then add one to the LHS of the sub so we can turn
18457     // X-Y -> X+~Y+1, saving one register.
18458     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
18459         isa<ConstantSDNode>(Op1.getOperand(1))) {
18460       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
18461       EVT VT = Op0.getValueType();
18462       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
18463                                    Op1.getOperand(0),
18464                                    DAG.getConstant(~XorC, VT));
18465       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
18466                          DAG.getConstant(C->getAPIntValue()+1, VT));
18467     }
18468   }
18469
18470   // Try to synthesize horizontal adds from adds of shuffles.
18471   EVT VT = N->getValueType(0);
18472   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18473        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18474       isHorizontalBinOp(Op0, Op1, true))
18475     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
18476
18477   return OptimizeConditionalInDecrement(N, DAG);
18478 }
18479
18480 /// performVZEXTCombine - Performs build vector combines
18481 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
18482                                         TargetLowering::DAGCombinerInfo &DCI,
18483                                         const X86Subtarget *Subtarget) {
18484   // (vzext (bitcast (vzext (x)) -> (vzext x)
18485   SDValue In = N->getOperand(0);
18486   while (In.getOpcode() == ISD::BITCAST)
18487     In = In.getOperand(0);
18488
18489   if (In.getOpcode() != X86ISD::VZEXT)
18490     return SDValue();
18491
18492   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
18493                      In.getOperand(0));
18494 }
18495
18496 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
18497                                              DAGCombinerInfo &DCI) const {
18498   SelectionDAG &DAG = DCI.DAG;
18499   switch (N->getOpcode()) {
18500   default: break;
18501   case ISD::EXTRACT_VECTOR_ELT:
18502     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
18503   case ISD::VSELECT:
18504   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
18505   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
18506   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
18507   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
18508   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
18509   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
18510   case ISD::SHL:
18511   case ISD::SRA:
18512   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
18513   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
18514   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
18515   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
18516   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
18517   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
18518   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
18519   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
18520   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
18521   case X86ISD::FXOR:
18522   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
18523   case X86ISD::FMIN:
18524   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
18525   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
18526   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
18527   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
18528   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
18529   case ISD::ANY_EXTEND:
18530   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
18531   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
18532   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
18533   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
18534   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
18535   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
18536   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
18537   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
18538   case X86ISD::SHUFP:       // Handle all target specific shuffles
18539   case X86ISD::PALIGNR:
18540   case X86ISD::UNPCKH:
18541   case X86ISD::UNPCKL:
18542   case X86ISD::MOVHLPS:
18543   case X86ISD::MOVLHPS:
18544   case X86ISD::PSHUFD:
18545   case X86ISD::PSHUFHW:
18546   case X86ISD::PSHUFLW:
18547   case X86ISD::MOVSS:
18548   case X86ISD::MOVSD:
18549   case X86ISD::VPERMILP:
18550   case X86ISD::VPERM2X128:
18551   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
18552   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
18553   }
18554
18555   return SDValue();
18556 }
18557
18558 /// isTypeDesirableForOp - Return true if the target has native support for
18559 /// the specified value type and it is 'desirable' to use the type for the
18560 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
18561 /// instruction encodings are longer and some i16 instructions are slow.
18562 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
18563   if (!isTypeLegal(VT))
18564     return false;
18565   if (VT != MVT::i16)
18566     return true;
18567
18568   switch (Opc) {
18569   default:
18570     return true;
18571   case ISD::LOAD:
18572   case ISD::SIGN_EXTEND:
18573   case ISD::ZERO_EXTEND:
18574   case ISD::ANY_EXTEND:
18575   case ISD::SHL:
18576   case ISD::SRL:
18577   case ISD::SUB:
18578   case ISD::ADD:
18579   case ISD::MUL:
18580   case ISD::AND:
18581   case ISD::OR:
18582   case ISD::XOR:
18583     return false;
18584   }
18585 }
18586
18587 /// IsDesirableToPromoteOp - This method query the target whether it is
18588 /// beneficial for dag combiner to promote the specified node. If true, it
18589 /// should return the desired promotion type by reference.
18590 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
18591   EVT VT = Op.getValueType();
18592   if (VT != MVT::i16)
18593     return false;
18594
18595   bool Promote = false;
18596   bool Commute = false;
18597   switch (Op.getOpcode()) {
18598   default: break;
18599   case ISD::LOAD: {
18600     LoadSDNode *LD = cast<LoadSDNode>(Op);
18601     // If the non-extending load has a single use and it's not live out, then it
18602     // might be folded.
18603     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
18604                                                      Op.hasOneUse()*/) {
18605       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18606              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
18607         // The only case where we'd want to promote LOAD (rather then it being
18608         // promoted as an operand is when it's only use is liveout.
18609         if (UI->getOpcode() != ISD::CopyToReg)
18610           return false;
18611       }
18612     }
18613     Promote = true;
18614     break;
18615   }
18616   case ISD::SIGN_EXTEND:
18617   case ISD::ZERO_EXTEND:
18618   case ISD::ANY_EXTEND:
18619     Promote = true;
18620     break;
18621   case ISD::SHL:
18622   case ISD::SRL: {
18623     SDValue N0 = Op.getOperand(0);
18624     // Look out for (store (shl (load), x)).
18625     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
18626       return false;
18627     Promote = true;
18628     break;
18629   }
18630   case ISD::ADD:
18631   case ISD::MUL:
18632   case ISD::AND:
18633   case ISD::OR:
18634   case ISD::XOR:
18635     Commute = true;
18636     // fallthrough
18637   case ISD::SUB: {
18638     SDValue N0 = Op.getOperand(0);
18639     SDValue N1 = Op.getOperand(1);
18640     if (!Commute && MayFoldLoad(N1))
18641       return false;
18642     // Avoid disabling potential load folding opportunities.
18643     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18644       return false;
18645     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18646       return false;
18647     Promote = true;
18648   }
18649   }
18650
18651   PVT = MVT::i32;
18652   return Promote;
18653 }
18654
18655 //===----------------------------------------------------------------------===//
18656 //                           X86 Inline Assembly Support
18657 //===----------------------------------------------------------------------===//
18658
18659 namespace {
18660   // Helper to match a string separated by whitespace.
18661   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18662     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18663
18664     for (unsigned i = 0, e = args.size(); i != e; ++i) {
18665       StringRef piece(*args[i]);
18666       if (!s.startswith(piece)) // Check if the piece matches.
18667         return false;
18668
18669       s = s.substr(piece.size());
18670       StringRef::size_type pos = s.find_first_not_of(" \t");
18671       if (pos == 0) // We matched a prefix.
18672         return false;
18673
18674       s = s.substr(pos);
18675     }
18676
18677     return s.empty();
18678   }
18679   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18680 }
18681
18682 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18683   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18684
18685   std::string AsmStr = IA->getAsmString();
18686
18687   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18688   if (!Ty || Ty->getBitWidth() % 16 != 0)
18689     return false;
18690
18691   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18692   SmallVector<StringRef, 4> AsmPieces;
18693   SplitString(AsmStr, AsmPieces, ";\n");
18694
18695   switch (AsmPieces.size()) {
18696   default: return false;
18697   case 1:
18698     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18699     // we will turn this bswap into something that will be lowered to logical
18700     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18701     // lower so don't worry about this.
18702     // bswap $0
18703     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18704         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18705         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18706         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18707         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18708         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18709       // No need to check constraints, nothing other than the equivalent of
18710       // "=r,0" would be valid here.
18711       return IntrinsicLowering::LowerToByteSwap(CI);
18712     }
18713
18714     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18715     if (CI->getType()->isIntegerTy(16) &&
18716         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18717         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18718          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18719       AsmPieces.clear();
18720       const std::string &ConstraintsStr = IA->getConstraintString();
18721       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18722       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18723       if (AsmPieces.size() == 4 &&
18724           AsmPieces[0] == "~{cc}" &&
18725           AsmPieces[1] == "~{dirflag}" &&
18726           AsmPieces[2] == "~{flags}" &&
18727           AsmPieces[3] == "~{fpsr}")
18728       return IntrinsicLowering::LowerToByteSwap(CI);
18729     }
18730     break;
18731   case 3:
18732     if (CI->getType()->isIntegerTy(32) &&
18733         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18734         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18735         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18736         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18737       AsmPieces.clear();
18738       const std::string &ConstraintsStr = IA->getConstraintString();
18739       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18740       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18741       if (AsmPieces.size() == 4 &&
18742           AsmPieces[0] == "~{cc}" &&
18743           AsmPieces[1] == "~{dirflag}" &&
18744           AsmPieces[2] == "~{flags}" &&
18745           AsmPieces[3] == "~{fpsr}")
18746         return IntrinsicLowering::LowerToByteSwap(CI);
18747     }
18748
18749     if (CI->getType()->isIntegerTy(64)) {
18750       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18751       if (Constraints.size() >= 2 &&
18752           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18753           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18754         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18755         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18756             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18757             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18758           return IntrinsicLowering::LowerToByteSwap(CI);
18759       }
18760     }
18761     break;
18762   }
18763   return false;
18764 }
18765
18766 /// getConstraintType - Given a constraint letter, return the type of
18767 /// constraint it is for this target.
18768 X86TargetLowering::ConstraintType
18769 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18770   if (Constraint.size() == 1) {
18771     switch (Constraint[0]) {
18772     case 'R':
18773     case 'q':
18774     case 'Q':
18775     case 'f':
18776     case 't':
18777     case 'u':
18778     case 'y':
18779     case 'x':
18780     case 'Y':
18781     case 'l':
18782       return C_RegisterClass;
18783     case 'a':
18784     case 'b':
18785     case 'c':
18786     case 'd':
18787     case 'S':
18788     case 'D':
18789     case 'A':
18790       return C_Register;
18791     case 'I':
18792     case 'J':
18793     case 'K':
18794     case 'L':
18795     case 'M':
18796     case 'N':
18797     case 'G':
18798     case 'C':
18799     case 'e':
18800     case 'Z':
18801       return C_Other;
18802     default:
18803       break;
18804     }
18805   }
18806   return TargetLowering::getConstraintType(Constraint);
18807 }
18808
18809 /// Examine constraint type and operand type and determine a weight value.
18810 /// This object must already have been set up with the operand type
18811 /// and the current alternative constraint selected.
18812 TargetLowering::ConstraintWeight
18813   X86TargetLowering::getSingleConstraintMatchWeight(
18814     AsmOperandInfo &info, const char *constraint) const {
18815   ConstraintWeight weight = CW_Invalid;
18816   Value *CallOperandVal = info.CallOperandVal;
18817     // If we don't have a value, we can't do a match,
18818     // but allow it at the lowest weight.
18819   if (CallOperandVal == NULL)
18820     return CW_Default;
18821   Type *type = CallOperandVal->getType();
18822   // Look at the constraint type.
18823   switch (*constraint) {
18824   default:
18825     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18826   case 'R':
18827   case 'q':
18828   case 'Q':
18829   case 'a':
18830   case 'b':
18831   case 'c':
18832   case 'd':
18833   case 'S':
18834   case 'D':
18835   case 'A':
18836     if (CallOperandVal->getType()->isIntegerTy())
18837       weight = CW_SpecificReg;
18838     break;
18839   case 'f':
18840   case 't':
18841   case 'u':
18842     if (type->isFloatingPointTy())
18843       weight = CW_SpecificReg;
18844     break;
18845   case 'y':
18846     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18847       weight = CW_SpecificReg;
18848     break;
18849   case 'x':
18850   case 'Y':
18851     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18852         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18853       weight = CW_Register;
18854     break;
18855   case 'I':
18856     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18857       if (C->getZExtValue() <= 31)
18858         weight = CW_Constant;
18859     }
18860     break;
18861   case 'J':
18862     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18863       if (C->getZExtValue() <= 63)
18864         weight = CW_Constant;
18865     }
18866     break;
18867   case 'K':
18868     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18869       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18870         weight = CW_Constant;
18871     }
18872     break;
18873   case 'L':
18874     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18875       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18876         weight = CW_Constant;
18877     }
18878     break;
18879   case 'M':
18880     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18881       if (C->getZExtValue() <= 3)
18882         weight = CW_Constant;
18883     }
18884     break;
18885   case 'N':
18886     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18887       if (C->getZExtValue() <= 0xff)
18888         weight = CW_Constant;
18889     }
18890     break;
18891   case 'G':
18892   case 'C':
18893     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18894       weight = CW_Constant;
18895     }
18896     break;
18897   case 'e':
18898     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18899       if ((C->getSExtValue() >= -0x80000000LL) &&
18900           (C->getSExtValue() <= 0x7fffffffLL))
18901         weight = CW_Constant;
18902     }
18903     break;
18904   case 'Z':
18905     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18906       if (C->getZExtValue() <= 0xffffffff)
18907         weight = CW_Constant;
18908     }
18909     break;
18910   }
18911   return weight;
18912 }
18913
18914 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18915 /// with another that has more specific requirements based on the type of the
18916 /// corresponding operand.
18917 const char *X86TargetLowering::
18918 LowerXConstraint(EVT ConstraintVT) const {
18919   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18920   // 'f' like normal targets.
18921   if (ConstraintVT.isFloatingPoint()) {
18922     if (Subtarget->hasSSE2())
18923       return "Y";
18924     if (Subtarget->hasSSE1())
18925       return "x";
18926   }
18927
18928   return TargetLowering::LowerXConstraint(ConstraintVT);
18929 }
18930
18931 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18932 /// vector.  If it is invalid, don't add anything to Ops.
18933 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18934                                                      std::string &Constraint,
18935                                                      std::vector<SDValue>&Ops,
18936                                                      SelectionDAG &DAG) const {
18937   SDValue Result(0, 0);
18938
18939   // Only support length 1 constraints for now.
18940   if (Constraint.length() > 1) return;
18941
18942   char ConstraintLetter = Constraint[0];
18943   switch (ConstraintLetter) {
18944   default: break;
18945   case 'I':
18946     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18947       if (C->getZExtValue() <= 31) {
18948         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18949         break;
18950       }
18951     }
18952     return;
18953   case 'J':
18954     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18955       if (C->getZExtValue() <= 63) {
18956         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18957         break;
18958       }
18959     }
18960     return;
18961   case 'K':
18962     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18963       if (isInt<8>(C->getSExtValue())) {
18964         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18965         break;
18966       }
18967     }
18968     return;
18969   case 'N':
18970     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18971       if (C->getZExtValue() <= 255) {
18972         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18973         break;
18974       }
18975     }
18976     return;
18977   case 'e': {
18978     // 32-bit signed value
18979     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18980       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18981                                            C->getSExtValue())) {
18982         // Widen to 64 bits here to get it sign extended.
18983         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18984         break;
18985       }
18986     // FIXME gcc accepts some relocatable values here too, but only in certain
18987     // memory models; it's complicated.
18988     }
18989     return;
18990   }
18991   case 'Z': {
18992     // 32-bit unsigned value
18993     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18994       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18995                                            C->getZExtValue())) {
18996         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18997         break;
18998       }
18999     }
19000     // FIXME gcc accepts some relocatable values here too, but only in certain
19001     // memory models; it's complicated.
19002     return;
19003   }
19004   case 'i': {
19005     // Literal immediates are always ok.
19006     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
19007       // Widen to 64 bits here to get it sign extended.
19008       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
19009       break;
19010     }
19011
19012     // In any sort of PIC mode addresses need to be computed at runtime by
19013     // adding in a register or some sort of table lookup.  These can't
19014     // be used as immediates.
19015     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
19016       return;
19017
19018     // If we are in non-pic codegen mode, we allow the address of a global (with
19019     // an optional displacement) to be used with 'i'.
19020     GlobalAddressSDNode *GA = 0;
19021     int64_t Offset = 0;
19022
19023     // Match either (GA), (GA+C), (GA+C1+C2), etc.
19024     while (1) {
19025       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
19026         Offset += GA->getOffset();
19027         break;
19028       } else if (Op.getOpcode() == ISD::ADD) {
19029         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19030           Offset += C->getZExtValue();
19031           Op = Op.getOperand(0);
19032           continue;
19033         }
19034       } else if (Op.getOpcode() == ISD::SUB) {
19035         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
19036           Offset += -C->getZExtValue();
19037           Op = Op.getOperand(0);
19038           continue;
19039         }
19040       }
19041
19042       // Otherwise, this isn't something we can handle, reject it.
19043       return;
19044     }
19045
19046     const GlobalValue *GV = GA->getGlobal();
19047     // If we require an extra load to get this address, as in PIC mode, we
19048     // can't accept it.
19049     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
19050                                                         getTargetMachine())))
19051       return;
19052
19053     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
19054                                         GA->getValueType(0), Offset);
19055     break;
19056   }
19057   }
19058
19059   if (Result.getNode()) {
19060     Ops.push_back(Result);
19061     return;
19062   }
19063   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
19064 }
19065
19066 std::pair<unsigned, const TargetRegisterClass*>
19067 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
19068                                                 MVT VT) const {
19069   // First, see if this is a constraint that directly corresponds to an LLVM
19070   // register class.
19071   if (Constraint.size() == 1) {
19072     // GCC Constraint Letters
19073     switch (Constraint[0]) {
19074     default: break;
19075       // TODO: Slight differences here in allocation order and leaving
19076       // RIP in the class. Do they matter any more here than they do
19077       // in the normal allocation?
19078     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
19079       if (Subtarget->is64Bit()) {
19080         if (VT == MVT::i32 || VT == MVT::f32)
19081           return std::make_pair(0U, &X86::GR32RegClass);
19082         if (VT == MVT::i16)
19083           return std::make_pair(0U, &X86::GR16RegClass);
19084         if (VT == MVT::i8 || VT == MVT::i1)
19085           return std::make_pair(0U, &X86::GR8RegClass);
19086         if (VT == MVT::i64 || VT == MVT::f64)
19087           return std::make_pair(0U, &X86::GR64RegClass);
19088         break;
19089       }
19090       // 32-bit fallthrough
19091     case 'Q':   // Q_REGS
19092       if (VT == MVT::i32 || VT == MVT::f32)
19093         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
19094       if (VT == MVT::i16)
19095         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
19096       if (VT == MVT::i8 || VT == MVT::i1)
19097         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
19098       if (VT == MVT::i64)
19099         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
19100       break;
19101     case 'r':   // GENERAL_REGS
19102     case 'l':   // INDEX_REGS
19103       if (VT == MVT::i8 || VT == MVT::i1)
19104         return std::make_pair(0U, &X86::GR8RegClass);
19105       if (VT == MVT::i16)
19106         return std::make_pair(0U, &X86::GR16RegClass);
19107       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
19108         return std::make_pair(0U, &X86::GR32RegClass);
19109       return std::make_pair(0U, &X86::GR64RegClass);
19110     case 'R':   // LEGACY_REGS
19111       if (VT == MVT::i8 || VT == MVT::i1)
19112         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
19113       if (VT == MVT::i16)
19114         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
19115       if (VT == MVT::i32 || !Subtarget->is64Bit())
19116         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
19117       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
19118     case 'f':  // FP Stack registers.
19119       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
19120       // value to the correct fpstack register class.
19121       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
19122         return std::make_pair(0U, &X86::RFP32RegClass);
19123       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
19124         return std::make_pair(0U, &X86::RFP64RegClass);
19125       return std::make_pair(0U, &X86::RFP80RegClass);
19126     case 'y':   // MMX_REGS if MMX allowed.
19127       if (!Subtarget->hasMMX()) break;
19128       return std::make_pair(0U, &X86::VR64RegClass);
19129     case 'Y':   // SSE_REGS if SSE2 allowed
19130       if (!Subtarget->hasSSE2()) break;
19131       // FALL THROUGH.
19132     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
19133       if (!Subtarget->hasSSE1()) break;
19134
19135       switch (VT.SimpleTy) {
19136       default: break;
19137       // Scalar SSE types.
19138       case MVT::f32:
19139       case MVT::i32:
19140         return std::make_pair(0U, &X86::FR32RegClass);
19141       case MVT::f64:
19142       case MVT::i64:
19143         return std::make_pair(0U, &X86::FR64RegClass);
19144       // Vector types.
19145       case MVT::v16i8:
19146       case MVT::v8i16:
19147       case MVT::v4i32:
19148       case MVT::v2i64:
19149       case MVT::v4f32:
19150       case MVT::v2f64:
19151         return std::make_pair(0U, &X86::VR128RegClass);
19152       // AVX types.
19153       case MVT::v32i8:
19154       case MVT::v16i16:
19155       case MVT::v8i32:
19156       case MVT::v4i64:
19157       case MVT::v8f32:
19158       case MVT::v4f64:
19159         return std::make_pair(0U, &X86::VR256RegClass);
19160       case MVT::v8f64:
19161       case MVT::v16f32:
19162       case MVT::v16i32:
19163       case MVT::v8i64:
19164         return std::make_pair(0U, &X86::VR512RegClass);
19165       }
19166       break;
19167     }
19168   }
19169
19170   // Use the default implementation in TargetLowering to convert the register
19171   // constraint into a member of a register class.
19172   std::pair<unsigned, const TargetRegisterClass*> Res;
19173   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19174
19175   // Not found as a standard register?
19176   if (Res.second == 0) {
19177     // Map st(0) -> st(7) -> ST0
19178     if (Constraint.size() == 7 && Constraint[0] == '{' &&
19179         tolower(Constraint[1]) == 's' &&
19180         tolower(Constraint[2]) == 't' &&
19181         Constraint[3] == '(' &&
19182         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19183         Constraint[5] == ')' &&
19184         Constraint[6] == '}') {
19185
19186       Res.first = X86::ST0+Constraint[4]-'0';
19187       Res.second = &X86::RFP80RegClass;
19188       return Res;
19189     }
19190
19191     // GCC allows "st(0)" to be called just plain "st".
19192     if (StringRef("{st}").equals_lower(Constraint)) {
19193       Res.first = X86::ST0;
19194       Res.second = &X86::RFP80RegClass;
19195       return Res;
19196     }
19197
19198     // flags -> EFLAGS
19199     if (StringRef("{flags}").equals_lower(Constraint)) {
19200       Res.first = X86::EFLAGS;
19201       Res.second = &X86::CCRRegClass;
19202       return Res;
19203     }
19204
19205     // 'A' means EAX + EDX.
19206     if (Constraint == "A") {
19207       Res.first = X86::EAX;
19208       Res.second = &X86::GR32_ADRegClass;
19209       return Res;
19210     }
19211     return Res;
19212   }
19213
19214   // Otherwise, check to see if this is a register class of the wrong value
19215   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
19216   // turn into {ax},{dx}.
19217   if (Res.second->hasType(VT))
19218     return Res;   // Correct type already, nothing to do.
19219
19220   // All of the single-register GCC register classes map their values onto
19221   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
19222   // really want an 8-bit or 32-bit register, map to the appropriate register
19223   // class and return the appropriate register.
19224   if (Res.second == &X86::GR16RegClass) {
19225     if (VT == MVT::i8 || VT == MVT::i1) {
19226       unsigned DestReg = 0;
19227       switch (Res.first) {
19228       default: break;
19229       case X86::AX: DestReg = X86::AL; break;
19230       case X86::DX: DestReg = X86::DL; break;
19231       case X86::CX: DestReg = X86::CL; break;
19232       case X86::BX: DestReg = X86::BL; break;
19233       }
19234       if (DestReg) {
19235         Res.first = DestReg;
19236         Res.second = &X86::GR8RegClass;
19237       }
19238     } else if (VT == MVT::i32 || VT == MVT::f32) {
19239       unsigned DestReg = 0;
19240       switch (Res.first) {
19241       default: break;
19242       case X86::AX: DestReg = X86::EAX; break;
19243       case X86::DX: DestReg = X86::EDX; break;
19244       case X86::CX: DestReg = X86::ECX; break;
19245       case X86::BX: DestReg = X86::EBX; break;
19246       case X86::SI: DestReg = X86::ESI; break;
19247       case X86::DI: DestReg = X86::EDI; break;
19248       case X86::BP: DestReg = X86::EBP; break;
19249       case X86::SP: DestReg = X86::ESP; break;
19250       }
19251       if (DestReg) {
19252         Res.first = DestReg;
19253         Res.second = &X86::GR32RegClass;
19254       }
19255     } else if (VT == MVT::i64 || VT == MVT::f64) {
19256       unsigned DestReg = 0;
19257       switch (Res.first) {
19258       default: break;
19259       case X86::AX: DestReg = X86::RAX; break;
19260       case X86::DX: DestReg = X86::RDX; break;
19261       case X86::CX: DestReg = X86::RCX; break;
19262       case X86::BX: DestReg = X86::RBX; break;
19263       case X86::SI: DestReg = X86::RSI; break;
19264       case X86::DI: DestReg = X86::RDI; break;
19265       case X86::BP: DestReg = X86::RBP; break;
19266       case X86::SP: DestReg = X86::RSP; break;
19267       }
19268       if (DestReg) {
19269         Res.first = DestReg;
19270         Res.second = &X86::GR64RegClass;
19271       }
19272     }
19273   } else if (Res.second == &X86::FR32RegClass ||
19274              Res.second == &X86::FR64RegClass ||
19275              Res.second == &X86::VR128RegClass ||
19276              Res.second == &X86::VR256RegClass ||
19277              Res.second == &X86::FR32XRegClass ||
19278              Res.second == &X86::FR64XRegClass ||
19279              Res.second == &X86::VR128XRegClass ||
19280              Res.second == &X86::VR256XRegClass ||
19281              Res.second == &X86::VR512RegClass) {
19282     // Handle references to XMM physical registers that got mapped into the
19283     // wrong class.  This can happen with constraints like {xmm0} where the
19284     // target independent register mapper will just pick the first match it can
19285     // find, ignoring the required type.
19286
19287     if (VT == MVT::f32 || VT == MVT::i32)
19288       Res.second = &X86::FR32RegClass;
19289     else if (VT == MVT::f64 || VT == MVT::i64)
19290       Res.second = &X86::FR64RegClass;
19291     else if (X86::VR128RegClass.hasType(VT))
19292       Res.second = &X86::VR128RegClass;
19293     else if (X86::VR256RegClass.hasType(VT))
19294       Res.second = &X86::VR256RegClass;
19295     else if (X86::VR512RegClass.hasType(VT))
19296       Res.second = &X86::VR512RegClass;
19297   }
19298
19299   return Res;
19300 }