Refactor isInTailCallPosition handling
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
18 #include "X86.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
62                                 SelectionDAG &DAG, SDLoc dl,
63                                 unsigned vectorWidth) {
64   assert((vectorWidth == 128 || vectorWidth == 256) &&
65          "Unsupported vector width");
66   EVT VT = Vec.getValueType();
67   EVT ElVT = VT.getVectorElementType();
68   unsigned Factor = VT.getSizeInBits()/vectorWidth;
69   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
70                                   VT.getVectorNumElements()/Factor);
71
72   // Extract from UNDEF is UNDEF.
73   if (Vec.getOpcode() == ISD::UNDEF)
74     return DAG.getUNDEF(ResultVT);
75
76   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
77   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
78
79   // This is the index of the first element of the vectorWidth-bit chunk
80   // we want.
81   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
82                                * ElemsPerChunk);
83
84   // If the input is a buildvector just emit a smaller one.
85   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
86     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
87                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
88
89   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
90   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
91                                VecIdx);
92
93   return Result;
94   
95 }
96 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
97 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
98 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
99 /// instructions or a simple subregister reference. Idx is an index in the
100 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
101 /// lowering EXTRACT_VECTOR_ELT operations easier.
102 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
103                                    SelectionDAG &DAG, SDLoc dl) {
104   assert((Vec.getValueType().is256BitVector() ||
105           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
106   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
107 }
108
109 /// Generate a DAG to grab 256-bits from a 512-bit vector.
110 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
111                                    SelectionDAG &DAG, SDLoc dl) {
112   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
113   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
114 }
115
116 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
117                                unsigned IdxVal, SelectionDAG &DAG,
118                                SDLoc dl, unsigned vectorWidth) {
119   assert((vectorWidth == 128 || vectorWidth == 256) &&
120          "Unsupported vector width");
121   // Inserting UNDEF is Result
122   if (Vec.getOpcode() == ISD::UNDEF)
123     return Result;
124   EVT VT = Vec.getValueType();
125   EVT ElVT = VT.getVectorElementType();
126   EVT ResultVT = Result.getValueType();
127
128   // Insert the relevant vectorWidth bits.
129   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
130
131   // This is the index of the first element of the vectorWidth-bit chunk
132   // we want.
133   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
134                                * ElemsPerChunk);
135
136   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
137   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
138                      VecIdx);
139 }
140 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
141 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
142 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
143 /// simple superregister reference.  Idx is an index in the 128 bits
144 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
145 /// lowering INSERT_VECTOR_ELT operations easier.
146 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
147                                   unsigned IdxVal, SelectionDAG &DAG,
148                                   SDLoc dl) {
149   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
150   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
151 }
152
153 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
154                                   unsigned IdxVal, SelectionDAG &DAG,
155                                   SDLoc dl) {
156   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
157   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
158 }
159
160 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
161 /// instructions. This is used because creating CONCAT_VECTOR nodes of
162 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
163 /// large BUILD_VECTORS.
164 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
165                                    unsigned NumElems, SelectionDAG &DAG,
166                                    SDLoc dl) {
167   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
168   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
169 }
170
171 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
172                                    unsigned NumElems, SelectionDAG &DAG,
173                                    SDLoc dl) {
174   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
175   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
176 }
177
178 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
179   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
180   bool is64Bit = Subtarget->is64Bit();
181
182   if (Subtarget->isTargetEnvMacho()) {
183     if (is64Bit)
184       return new X86_64MachoTargetObjectFile();
185     return new TargetLoweringObjectFileMachO();
186   }
187
188   if (Subtarget->isTargetLinux())
189     return new X86LinuxTargetObjectFile();
190   if (Subtarget->isTargetELF())
191     return new TargetLoweringObjectFileELF();
192   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
193     return new TargetLoweringObjectFileCOFF();
194   llvm_unreachable("unknown subtarget type");
195 }
196
197 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
198   : TargetLowering(TM, createTLOF(TM)) {
199   Subtarget = &TM.getSubtarget<X86Subtarget>();
200   X86ScalarSSEf64 = Subtarget->hasSSE2();
201   X86ScalarSSEf32 = Subtarget->hasSSE1();
202   TD = getDataLayout();
203
204   resetOperationActions();
205 }
206
207 void X86TargetLowering::resetOperationActions() {
208   const TargetMachine &TM = getTargetMachine();
209   static bool FirstTimeThrough = true;
210
211   // If none of the target options have changed, then we don't need to reset the
212   // operation actions.
213   if (!FirstTimeThrough && TO == TM.Options) return;
214
215   if (!FirstTimeThrough) {
216     // Reinitialize the actions.
217     initActions();
218     FirstTimeThrough = false;
219   }
220
221   TO = TM.Options;
222
223   // Set up the TargetLowering object.
224   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
225
226   // X86 is weird, it always uses i8 for shift amounts and setcc results.
227   setBooleanContents(ZeroOrOneBooleanContent);
228   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
229   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
230
231   // For 64-bit since we have so many registers use the ILP scheduler, for
232   // 32-bit code use the register pressure specific scheduling.
233   // For Atom, always use ILP scheduling.
234   if (Subtarget->isAtom())
235     setSchedulingPreference(Sched::ILP);
236   else if (Subtarget->is64Bit())
237     setSchedulingPreference(Sched::ILP);
238   else
239     setSchedulingPreference(Sched::RegPressure);
240   const X86RegisterInfo *RegInfo =
241     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
242   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
243
244   // Bypass expensive divides on Atom when compiling with O2
245   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
246     addBypassSlowDiv(32, 8);
247     if (Subtarget->is64Bit())
248       addBypassSlowDiv(64, 16);
249   }
250
251   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
252     // Setup Windows compiler runtime calls.
253     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
254     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
255     setLibcallName(RTLIB::SREM_I64, "_allrem");
256     setLibcallName(RTLIB::UREM_I64, "_aullrem");
257     setLibcallName(RTLIB::MUL_I64, "_allmul");
258     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
259     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
260     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
263
264     // The _ftol2 runtime function has an unusual calling conv, which
265     // is modeled by a special pseudo-instruction.
266     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
267     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
268     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
269     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
270   }
271
272   if (Subtarget->isTargetDarwin()) {
273     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
274     setUseUnderscoreSetJmp(false);
275     setUseUnderscoreLongJmp(false);
276   } else if (Subtarget->isTargetMingw()) {
277     // MS runtime is weird: it exports _setjmp, but longjmp!
278     setUseUnderscoreSetJmp(true);
279     setUseUnderscoreLongJmp(false);
280   } else {
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(true);
283   }
284
285   // Set up the register classes.
286   addRegisterClass(MVT::i8, &X86::GR8RegClass);
287   addRegisterClass(MVT::i16, &X86::GR16RegClass);
288   addRegisterClass(MVT::i32, &X86::GR32RegClass);
289   if (Subtarget->is64Bit())
290     addRegisterClass(MVT::i64, &X86::GR64RegClass);
291
292   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
293
294   // We don't accept any truncstore of integer registers.
295   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
296   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
297   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
298   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
299   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
300   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
301
302   // SETOEQ and SETUNE require checking two conditions.
303   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
304   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
305   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
306   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
307   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
309
310   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
311   // operation.
312   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
313   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
315
316   if (Subtarget->is64Bit()) {
317     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
318     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
319   } else if (!TM.Options.UseSoftFloat) {
320     // We have an algorithm for SSE2->double, and we turn this into a
321     // 64-bit FILD followed by conditional FADD for other targets.
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
323     // We have an algorithm for SSE2, and we turn this into a 64-bit
324     // FILD for other targets.
325     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
326   }
327
328   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
329   // this operation.
330   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
331   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
332
333   if (!TM.Options.UseSoftFloat) {
334     // SSE has no i16 to fp conversion, only i32
335     if (X86ScalarSSEf32) {
336       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
337       // f32 and f64 cases are Legal, f80 case is not
338       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
339     } else {
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
342     }
343   } else {
344     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
345     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
346   }
347
348   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
349   // are Legal, f80 is custom lowered.
350   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
351   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
352
353   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
354   // this operation.
355   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
356   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
357
358   if (X86ScalarSSEf32) {
359     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
360     // f32 and f64 cases are Legal, f80 case is not
361     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
362   } else {
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
365   }
366
367   // Handle FP_TO_UINT by promoting the destination to a larger signed
368   // conversion.
369   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
370   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
372
373   if (Subtarget->is64Bit()) {
374     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
375     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
376   } else if (!TM.Options.UseSoftFloat) {
377     // Since AVX is a superset of SSE3, only check for SSE here.
378     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
379       // Expand FP_TO_UINT into a select.
380       // FIXME: We would like to use a Custom expander here eventually to do
381       // the optimal thing for SSE vs. the default expansion in the legalizer.
382       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
383     else
384       // With SSE3 we can use fisttpll to convert to a signed i64; without
385       // SSE, we're stuck with a fistpll.
386       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
387   }
388
389   if (isTargetFTOL()) {
390     // Use the _ftol2 runtime function, which has a pseudo-instruction
391     // to handle its weird calling convention.
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
393   }
394
395   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
396   if (!X86ScalarSSEf64) {
397     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
398     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
399     if (Subtarget->is64Bit()) {
400       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
401       // Without SSE, i64->f64 goes through memory.
402       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
403     }
404   }
405
406   // Scalar integer divide and remainder are lowered to use operations that
407   // produce two results, to match the available instructions. This exposes
408   // the two-result form to trivial CSE, which is able to combine x/y and x%y
409   // into a single instruction.
410   //
411   // Scalar integer multiply-high is also lowered to use two-result
412   // operations, to match the available instructions. However, plain multiply
413   // (low) operations are left as Legal, as there are single-result
414   // instructions for this in x86. Using the two-result multiply instructions
415   // when both high and low results are needed must be arranged by dagcombine.
416   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
417     MVT VT = IntVTs[i];
418     setOperationAction(ISD::MULHS, VT, Expand);
419     setOperationAction(ISD::MULHU, VT, Expand);
420     setOperationAction(ISD::SDIV, VT, Expand);
421     setOperationAction(ISD::UDIV, VT, Expand);
422     setOperationAction(ISD::SREM, VT, Expand);
423     setOperationAction(ISD::UREM, VT, Expand);
424
425     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
426     setOperationAction(ISD::ADDC, VT, Custom);
427     setOperationAction(ISD::ADDE, VT, Custom);
428     setOperationAction(ISD::SUBC, VT, Custom);
429     setOperationAction(ISD::SUBE, VT, Custom);
430   }
431
432   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
433   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
434   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
435   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
436   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
438   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
441   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
442   if (Subtarget->is64Bit())
443     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
444   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
445   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
447   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
448   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
449   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
450   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
451   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
452
453   // Promote the i8 variants and force them on up to i32 which has a shorter
454   // encoding.
455   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
456   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
457   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
458   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
459   if (Subtarget->hasBMI()) {
460     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
461     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
462     if (Subtarget->is64Bit())
463       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
464   } else {
465     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
466     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
467     if (Subtarget->is64Bit())
468       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
469   }
470
471   if (Subtarget->hasLZCNT()) {
472     // When promoting the i8 variants, force them to i32 for a shorter
473     // encoding.
474     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
475     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
476     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
477     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
478     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
479     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
480     if (Subtarget->is64Bit())
481       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
482   } else {
483     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
484     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
485     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
486     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
487     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
489     if (Subtarget->is64Bit()) {
490       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
491       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
492     }
493   }
494
495   if (Subtarget->hasPOPCNT()) {
496     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
497   } else {
498     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
499     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
500     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
501     if (Subtarget->is64Bit())
502       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
503   }
504
505   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
506   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
507
508   // These should be promoted to a larger select which is supported.
509   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
510   // X86 wants to expand cmov itself.
511   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
512   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
513   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
514   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
515   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
516   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
517   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
518   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
519   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
520   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
523   if (Subtarget->is64Bit()) {
524     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
525     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
526   }
527   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
528   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
529   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
530   // support continuation, user-level threading, and etc.. As a result, no
531   // other SjLj exception interfaces are implemented and please don't build
532   // your own exception handling based on them.
533   // LLVM/Clang supports zero-cost DWARF exception handling.
534   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
535   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
536
537   // Darwin ABI issue.
538   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
539   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
540   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
541   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
542   if (Subtarget->is64Bit())
543     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
544   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
545   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
546   if (Subtarget->is64Bit()) {
547     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
548     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
549     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
550     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
551     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
552   }
553   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
554   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
555   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
556   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
557   if (Subtarget->is64Bit()) {
558     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
559     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
560     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
561   }
562
563   if (Subtarget->hasSSE1())
564     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
565
566   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
567
568   // Expand certain atomics
569   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
570     MVT VT = IntVTs[i];
571     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
572     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
573     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
574   }
575
576   if (!Subtarget->is64Bit()) {
577     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
578     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
579     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
580     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
581     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
589   }
590
591   if (Subtarget->hasCmpxchg16b()) {
592     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
593   }
594
595   // FIXME - use subtarget debug flags
596   if (!Subtarget->isTargetDarwin() &&
597       !Subtarget->isTargetELF() &&
598       !Subtarget->isTargetCygMing()) {
599     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
600   }
601
602   if (Subtarget->is64Bit()) {
603     setExceptionPointerRegister(X86::RAX);
604     setExceptionSelectorRegister(X86::RDX);
605   } else {
606     setExceptionPointerRegister(X86::EAX);
607     setExceptionSelectorRegister(X86::EDX);
608   }
609   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
610   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
611
612   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
613   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
614
615   setOperationAction(ISD::TRAP, MVT::Other, Legal);
616   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
617
618   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
619   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
620   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
621   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
622     // TargetInfo::X86_64ABIBuiltinVaList
623     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
624     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
625   } else {
626     // TargetInfo::CharPtrBuiltinVaList
627     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
628     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
629   }
630
631   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
632   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
633
634   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
635     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
636                        MVT::i64 : MVT::i32, Custom);
637   else if (TM.Options.EnableSegmentedStacks)
638     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639                        MVT::i64 : MVT::i32, Custom);
640   else
641     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
642                        MVT::i64 : MVT::i32, Expand);
643
644   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
645     // f32 and f64 use SSE.
646     // Set up the FP register classes.
647     addRegisterClass(MVT::f32, &X86::FR32RegClass);
648     addRegisterClass(MVT::f64, &X86::FR64RegClass);
649
650     // Use ANDPD to simulate FABS.
651     setOperationAction(ISD::FABS , MVT::f64, Custom);
652     setOperationAction(ISD::FABS , MVT::f32, Custom);
653
654     // Use XORP to simulate FNEG.
655     setOperationAction(ISD::FNEG , MVT::f64, Custom);
656     setOperationAction(ISD::FNEG , MVT::f32, Custom);
657
658     // Use ANDPD and ORPD to simulate FCOPYSIGN.
659     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
660     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
661
662     // Lower this to FGETSIGNx86 plus an AND.
663     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
664     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
665
666     // We don't support sin/cos/fmod
667     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
668     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
669     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
670     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
671     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
672     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
673
674     // Expand FP immediates into loads from the stack, except for the special
675     // cases we handle.
676     addLegalFPImmediate(APFloat(+0.0)); // xorpd
677     addLegalFPImmediate(APFloat(+0.0f)); // xorps
678   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
679     // Use SSE for f32, x87 for f64.
680     // Set up the FP register classes.
681     addRegisterClass(MVT::f32, &X86::FR32RegClass);
682     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
683
684     // Use ANDPS to simulate FABS.
685     setOperationAction(ISD::FABS , MVT::f32, Custom);
686
687     // Use XORP to simulate FNEG.
688     setOperationAction(ISD::FNEG , MVT::f32, Custom);
689
690     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
691
692     // Use ANDPS and ORPS to simulate FCOPYSIGN.
693     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
694     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
695
696     // We don't support sin/cos/fmod
697     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
698     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
699     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
700
701     // Special cases we handle for FP constants.
702     addLegalFPImmediate(APFloat(+0.0f)); // xorps
703     addLegalFPImmediate(APFloat(+0.0)); // FLD0
704     addLegalFPImmediate(APFloat(+1.0)); // FLD1
705     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
706     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
707
708     if (!TM.Options.UnsafeFPMath) {
709       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
710       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
711       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
712     }
713   } else if (!TM.Options.UseSoftFloat) {
714     // f32 and f64 in x87.
715     // Set up the FP register classes.
716     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
717     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
718
719     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
720     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
721     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
722     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
723
724     if (!TM.Options.UnsafeFPMath) {
725       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
726       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
727       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
728       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
729       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
730       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
731     }
732     addLegalFPImmediate(APFloat(+0.0)); // FLD0
733     addLegalFPImmediate(APFloat(+1.0)); // FLD1
734     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
735     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
736     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
737     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
738     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
739     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
740   }
741
742   // We don't support FMA.
743   setOperationAction(ISD::FMA, MVT::f64, Expand);
744   setOperationAction(ISD::FMA, MVT::f32, Expand);
745
746   // Long double always uses X87.
747   if (!TM.Options.UseSoftFloat) {
748     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
749     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
750     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
751     {
752       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
753       addLegalFPImmediate(TmpFlt);  // FLD0
754       TmpFlt.changeSign();
755       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
756
757       bool ignored;
758       APFloat TmpFlt2(+1.0);
759       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
760                       &ignored);
761       addLegalFPImmediate(TmpFlt2);  // FLD1
762       TmpFlt2.changeSign();
763       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
764     }
765
766     if (!TM.Options.UnsafeFPMath) {
767       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
768       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
769       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
770     }
771
772     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
773     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
774     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
775     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
776     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
777     setOperationAction(ISD::FMA, MVT::f80, Expand);
778   }
779
780   // Always use a library call for pow.
781   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
782   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
783   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
784
785   setOperationAction(ISD::FLOG, MVT::f80, Expand);
786   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
787   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
788   setOperationAction(ISD::FEXP, MVT::f80, Expand);
789   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
790
791   // First set operation action for all vector types to either promote
792   // (for widening) or expand (for scalarization). Then we will selectively
793   // turn on ones that can be effectively codegen'd.
794   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
795            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
796     MVT VT = (MVT::SimpleValueType)i;
797     setOperationAction(ISD::ADD , VT, Expand);
798     setOperationAction(ISD::SUB , VT, Expand);
799     setOperationAction(ISD::FADD, VT, Expand);
800     setOperationAction(ISD::FNEG, VT, Expand);
801     setOperationAction(ISD::FSUB, VT, Expand);
802     setOperationAction(ISD::MUL , VT, Expand);
803     setOperationAction(ISD::FMUL, VT, Expand);
804     setOperationAction(ISD::SDIV, VT, Expand);
805     setOperationAction(ISD::UDIV, VT, Expand);
806     setOperationAction(ISD::FDIV, VT, Expand);
807     setOperationAction(ISD::SREM, VT, Expand);
808     setOperationAction(ISD::UREM, VT, Expand);
809     setOperationAction(ISD::LOAD, VT, Expand);
810     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
811     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
812     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
813     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
814     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
815     setOperationAction(ISD::FABS, VT, Expand);
816     setOperationAction(ISD::FSIN, VT, Expand);
817     setOperationAction(ISD::FSINCOS, VT, Expand);
818     setOperationAction(ISD::FCOS, VT, Expand);
819     setOperationAction(ISD::FSINCOS, VT, Expand);
820     setOperationAction(ISD::FREM, VT, Expand);
821     setOperationAction(ISD::FMA,  VT, Expand);
822     setOperationAction(ISD::FPOWI, VT, Expand);
823     setOperationAction(ISD::FSQRT, VT, Expand);
824     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
825     setOperationAction(ISD::FFLOOR, VT, Expand);
826     setOperationAction(ISD::FCEIL, VT, Expand);
827     setOperationAction(ISD::FTRUNC, VT, Expand);
828     setOperationAction(ISD::FRINT, VT, Expand);
829     setOperationAction(ISD::FNEARBYINT, VT, Expand);
830     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
831     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
832     setOperationAction(ISD::SDIVREM, VT, Expand);
833     setOperationAction(ISD::UDIVREM, VT, Expand);
834     setOperationAction(ISD::FPOW, VT, Expand);
835     setOperationAction(ISD::CTPOP, VT, Expand);
836     setOperationAction(ISD::CTTZ, VT, Expand);
837     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
838     setOperationAction(ISD::CTLZ, VT, Expand);
839     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
840     setOperationAction(ISD::SHL, VT, Expand);
841     setOperationAction(ISD::SRA, VT, Expand);
842     setOperationAction(ISD::SRL, VT, Expand);
843     setOperationAction(ISD::ROTL, VT, Expand);
844     setOperationAction(ISD::ROTR, VT, Expand);
845     setOperationAction(ISD::BSWAP, VT, Expand);
846     setOperationAction(ISD::SETCC, VT, Expand);
847     setOperationAction(ISD::FLOG, VT, Expand);
848     setOperationAction(ISD::FLOG2, VT, Expand);
849     setOperationAction(ISD::FLOG10, VT, Expand);
850     setOperationAction(ISD::FEXP, VT, Expand);
851     setOperationAction(ISD::FEXP2, VT, Expand);
852     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
853     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
854     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
855     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
856     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
857     setOperationAction(ISD::TRUNCATE, VT, Expand);
858     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
859     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
860     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
861     setOperationAction(ISD::VSELECT, VT, Expand);
862     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
863              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
864       setTruncStoreAction(VT,
865                           (MVT::SimpleValueType)InnerVT, Expand);
866     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
867     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
868     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
869   }
870
871   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
872   // with -msoft-float, disable use of MMX as well.
873   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
874     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
875     // No operations on x86mmx supported, everything uses intrinsics.
876   }
877
878   // MMX-sized vectors (other than x86mmx) are expected to be expanded
879   // into smaller operations.
880   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
881   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
882   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
883   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
884   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
885   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
886   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
887   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
888   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
889   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
890   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
891   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
892   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
893   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
894   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
895   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
899   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
900   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
901   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
902   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
904   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
908   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
909
910   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
911     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
912
913     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
917     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
918     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
919     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
920     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
921     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
922     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
923     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
924     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
925   }
926
927   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
928     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
929
930     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
931     // registers cannot be used even for integer operations.
932     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
933     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
934     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
935     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
936
937     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
938     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
939     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
940     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
941     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
942     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
943     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
944     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
945     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
946     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
947     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
948     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
949     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
950     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
951     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
953     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
954     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
955
956     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
957     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
958     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
959     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
960
961     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
962     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
966
967     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
968     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
969       MVT VT = (MVT::SimpleValueType)i;
970       // Do not attempt to custom lower non-power-of-2 vectors
971       if (!isPowerOf2_32(VT.getVectorNumElements()))
972         continue;
973       // Do not attempt to custom lower non-128-bit vectors
974       if (!VT.is128BitVector())
975         continue;
976       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
977       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
978       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
979     }
980
981     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
982     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
983     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
984     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
985     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
986     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
987
988     if (Subtarget->is64Bit()) {
989       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
990       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
991     }
992
993     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
994     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
995       MVT VT = (MVT::SimpleValueType)i;
996
997       // Do not attempt to promote non-128-bit vectors
998       if (!VT.is128BitVector())
999         continue;
1000
1001       setOperationAction(ISD::AND,    VT, Promote);
1002       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1003       setOperationAction(ISD::OR,     VT, Promote);
1004       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1005       setOperationAction(ISD::XOR,    VT, Promote);
1006       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1007       setOperationAction(ISD::LOAD,   VT, Promote);
1008       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1009       setOperationAction(ISD::SELECT, VT, Promote);
1010       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1011     }
1012
1013     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1014
1015     // Custom lower v2i64 and v2f64 selects.
1016     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1017     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1018     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1019     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1020
1021     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1022     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1023
1024     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1025     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1026     // As there is no 64-bit GPR available, we need build a special custom
1027     // sequence to convert from v2i32 to v2f32.
1028     if (!Subtarget->is64Bit())
1029       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1030
1031     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1032     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1033
1034     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1035   }
1036
1037   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1038     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1039     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1040     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1041     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1042     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1043     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1044     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1045     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1046     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1047     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1048
1049     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1050     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1051     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1052     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1053     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1054     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1055     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1056     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1057     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1058     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1059
1060     // FIXME: Do we need to handle scalar-to-vector here?
1061     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1062
1063     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1064     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1065     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1066     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1067     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1068
1069     // i8 and i16 vectors are custom , because the source register and source
1070     // source memory operand types are not the same width.  f32 vectors are
1071     // custom since the immediate controlling the insert encodes additional
1072     // information.
1073     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1074     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1075     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1076     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1077
1078     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1079     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1080     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1081     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1082
1083     // FIXME: these should be Legal but thats only for the case where
1084     // the index is constant.  For now custom expand to deal with that.
1085     if (Subtarget->is64Bit()) {
1086       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1087       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1088     }
1089   }
1090
1091   if (Subtarget->hasSSE2()) {
1092     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1093     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1094
1095     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1096     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1097
1098     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1099     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1100
1101     // In the customized shift lowering, the legal cases in AVX2 will be
1102     // recognized.
1103     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1104     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1105
1106     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1107     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1108
1109     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1110
1111     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1112     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1113   }
1114
1115   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1116     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1117     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1118     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1119     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1120     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1122
1123     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1124     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1125     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1126
1127     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1128     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1130     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1132     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1133     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1134     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1135     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1136     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1137     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1138     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1139
1140     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1141     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1142     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1143     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1144     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1145     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1146     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1147     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1148     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1149     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1150     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1151     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1152
1153     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1154     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1155
1156     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1157
1158     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1159     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1160     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1161     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1162
1163     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1164     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1165     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1166
1167     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1168
1169     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1170     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1171
1172     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1173     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1174
1175     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1176     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1177
1178     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1179
1180     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1181     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1182     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1183     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1184
1185     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1186     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1187     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1188
1189     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1190     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1191     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1192     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1193
1194     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1195     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1197     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1200
1201     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1202       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1203       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1204       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1205       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1206       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1207       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1208     }
1209
1210     if (Subtarget->hasInt256()) {
1211       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1212       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1213       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1214       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1215
1216       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1217       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1218       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1219       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1220
1221       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1222       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1223       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1224       // Don't lower v32i8 because there is no 128-bit byte mul
1225
1226       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1227
1228       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1229     } else {
1230       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1231       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1232       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1233       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1234
1235       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1236       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1237       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1238       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1239
1240       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1241       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1242       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1243       // Don't lower v32i8 because there is no 128-bit byte mul
1244     }
1245
1246     // In the customized shift lowering, the legal cases in AVX2 will be
1247     // recognized.
1248     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1249     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1250
1251     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1252     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1253
1254     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1255
1256     // Custom lower several nodes for 256-bit types.
1257     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1258              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1259       MVT VT = (MVT::SimpleValueType)i;
1260
1261       // Extract subvector is special because the value type
1262       // (result) is 128-bit but the source is 256-bit wide.
1263       if (VT.is128BitVector())
1264         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1265
1266       // Do not attempt to custom lower other non-256-bit vectors
1267       if (!VT.is256BitVector())
1268         continue;
1269
1270       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1271       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1272       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1273       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1274       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1275       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1276       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1277     }
1278
1279     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1280     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1281       MVT VT = (MVT::SimpleValueType)i;
1282
1283       // Do not attempt to promote non-256-bit vectors
1284       if (!VT.is256BitVector())
1285         continue;
1286
1287       setOperationAction(ISD::AND,    VT, Promote);
1288       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1289       setOperationAction(ISD::OR,     VT, Promote);
1290       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1291       setOperationAction(ISD::XOR,    VT, Promote);
1292       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1293       setOperationAction(ISD::LOAD,   VT, Promote);
1294       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1295       setOperationAction(ISD::SELECT, VT, Promote);
1296       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1297     }
1298   }
1299
1300   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1301     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1302     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1303     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1304     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1305
1306     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1307     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1308
1309     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1310     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1312     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1313     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1314     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1315
1316     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1317     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1318     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1319     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1320     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1321     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1322
1323     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1324     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1325     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1326     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1327     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1328     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1329     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1330     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1331     setOperationAction(ISD::SDIV,               MVT::v16i32, Custom);
1332
1333
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1338     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1340     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1341     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1342
1343     setOperationAction(ISD::TRUNCATE,           MVT::i1, Legal);
1344     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1345     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1346     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1347     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1348     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1349     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1350     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1351     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1352     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1353     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1354     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1355
1356     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1357     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1358     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1359     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1360     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1361
1362     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1363     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1364
1365     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1366
1367     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1368     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1369     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1370     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1371     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1372
1373     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1374     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1375
1376     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1377     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1378
1379     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1380
1381     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1382     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1383
1384     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1385     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1386
1387     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1388     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1389
1390     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1391     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1392     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1393
1394     // Custom lower several nodes.
1395     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1396              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1397       MVT VT = (MVT::SimpleValueType)i;
1398
1399       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1400       // Extract subvector is special because the value type
1401       // (result) is 256/128-bit but the source is 512-bit wide.
1402       if (VT.is128BitVector() || VT.is256BitVector())
1403         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1404
1405       if (VT.getVectorElementType() == MVT::i1)
1406         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1407
1408       // Do not attempt to custom lower other non-512-bit vectors
1409       if (!VT.is512BitVector())
1410         continue;
1411
1412       if (VT != MVT::v8i64) {
1413         setOperationAction(ISD::XOR,   VT, Promote);
1414         AddPromotedToType (ISD::XOR,   VT, MVT::v8i64);
1415         setOperationAction(ISD::OR,    VT, Promote);
1416         AddPromotedToType (ISD::OR,    VT, MVT::v8i64);
1417         setOperationAction(ISD::AND,   VT, Promote);
1418         AddPromotedToType (ISD::AND,   VT, MVT::v8i64);
1419       }
1420       if ( EltSize >= 32) {
1421         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1422         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1423         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1424         setOperationAction(ISD::VSELECT,             VT, Legal);
1425         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1426         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1427         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1428       }
1429     }
1430     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1431       MVT VT = (MVT::SimpleValueType)i;
1432
1433       // Do not attempt to promote non-256-bit vectors
1434       if (!VT.is512BitVector())
1435         continue;
1436
1437       setOperationAction(ISD::LOAD,   VT, Promote);
1438       AddPromotedToType (ISD::LOAD,   VT, MVT::v8i64);
1439       setOperationAction(ISD::SELECT, VT, Promote);
1440       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1441     }
1442   }// has  AVX-512
1443
1444   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1445   // of this type with custom code.
1446   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1447            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1448     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1449                        Custom);
1450   }
1451
1452   // We want to custom lower some of our intrinsics.
1453   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1454   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1455
1456   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1457   // handle type legalization for these operations here.
1458   //
1459   // FIXME: We really should do custom legalization for addition and
1460   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1461   // than generic legalization for 64-bit multiplication-with-overflow, though.
1462   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1463     // Add/Sub/Mul with overflow operations are custom lowered.
1464     MVT VT = IntVTs[i];
1465     setOperationAction(ISD::SADDO, VT, Custom);
1466     setOperationAction(ISD::UADDO, VT, Custom);
1467     setOperationAction(ISD::SSUBO, VT, Custom);
1468     setOperationAction(ISD::USUBO, VT, Custom);
1469     setOperationAction(ISD::SMULO, VT, Custom);
1470     setOperationAction(ISD::UMULO, VT, Custom);
1471   }
1472
1473   // There are no 8-bit 3-address imul/mul instructions
1474   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1475   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1476
1477   if (!Subtarget->is64Bit()) {
1478     // These libcalls are not available in 32-bit.
1479     setLibcallName(RTLIB::SHL_I128, 0);
1480     setLibcallName(RTLIB::SRL_I128, 0);
1481     setLibcallName(RTLIB::SRA_I128, 0);
1482   }
1483
1484   // Combine sin / cos into one node or libcall if possible.
1485   if (Subtarget->hasSinCos()) {
1486     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1487     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1488     if (Subtarget->isTargetDarwin()) {
1489       // For MacOSX, we don't want to the normal expansion of a libcall to
1490       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1491       // traffic.
1492       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1493       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1494     }
1495   }
1496
1497   // We have target-specific dag combine patterns for the following nodes:
1498   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1499   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1500   setTargetDAGCombine(ISD::VSELECT);
1501   setTargetDAGCombine(ISD::SELECT);
1502   setTargetDAGCombine(ISD::SHL);
1503   setTargetDAGCombine(ISD::SRA);
1504   setTargetDAGCombine(ISD::SRL);
1505   setTargetDAGCombine(ISD::OR);
1506   setTargetDAGCombine(ISD::AND);
1507   setTargetDAGCombine(ISD::ADD);
1508   setTargetDAGCombine(ISD::FADD);
1509   setTargetDAGCombine(ISD::FSUB);
1510   setTargetDAGCombine(ISD::FMA);
1511   setTargetDAGCombine(ISD::SUB);
1512   setTargetDAGCombine(ISD::LOAD);
1513   setTargetDAGCombine(ISD::STORE);
1514   setTargetDAGCombine(ISD::ZERO_EXTEND);
1515   setTargetDAGCombine(ISD::ANY_EXTEND);
1516   setTargetDAGCombine(ISD::SIGN_EXTEND);
1517   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1518   setTargetDAGCombine(ISD::TRUNCATE);
1519   setTargetDAGCombine(ISD::SINT_TO_FP);
1520   setTargetDAGCombine(ISD::SETCC);
1521   if (Subtarget->is64Bit())
1522     setTargetDAGCombine(ISD::MUL);
1523   setTargetDAGCombine(ISD::XOR);
1524
1525   computeRegisterProperties();
1526
1527   // On Darwin, -Os means optimize for size without hurting performance,
1528   // do not reduce the limit.
1529   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1530   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1531   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1532   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1533   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1534   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1535   setPrefLoopAlignment(4); // 2^4 bytes.
1536
1537   // Predictable cmov don't hurt on atom because it's in-order.
1538   PredictableSelectIsExpensive = !Subtarget->isAtom();
1539
1540   setPrefFunctionAlignment(4); // 2^4 bytes.
1541 }
1542
1543 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1544   if (!VT.isVector()) return MVT::i8;
1545   return VT.changeVectorElementTypeToInteger();
1546 }
1547
1548 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1549 /// the desired ByVal argument alignment.
1550 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1551   if (MaxAlign == 16)
1552     return;
1553   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1554     if (VTy->getBitWidth() == 128)
1555       MaxAlign = 16;
1556   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1557     unsigned EltAlign = 0;
1558     getMaxByValAlign(ATy->getElementType(), EltAlign);
1559     if (EltAlign > MaxAlign)
1560       MaxAlign = EltAlign;
1561   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1562     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1563       unsigned EltAlign = 0;
1564       getMaxByValAlign(STy->getElementType(i), EltAlign);
1565       if (EltAlign > MaxAlign)
1566         MaxAlign = EltAlign;
1567       if (MaxAlign == 16)
1568         break;
1569     }
1570   }
1571 }
1572
1573 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1574 /// function arguments in the caller parameter area. For X86, aggregates
1575 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1576 /// are at 4-byte boundaries.
1577 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1578   if (Subtarget->is64Bit()) {
1579     // Max of 8 and alignment of type.
1580     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1581     if (TyAlign > 8)
1582       return TyAlign;
1583     return 8;
1584   }
1585
1586   unsigned Align = 4;
1587   if (Subtarget->hasSSE1())
1588     getMaxByValAlign(Ty, Align);
1589   return Align;
1590 }
1591
1592 /// getOptimalMemOpType - Returns the target specific optimal type for load
1593 /// and store operations as a result of memset, memcpy, and memmove
1594 /// lowering. If DstAlign is zero that means it's safe to destination
1595 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1596 /// means there isn't a need to check it against alignment requirement,
1597 /// probably because the source does not need to be loaded. If 'IsMemset' is
1598 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1599 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1600 /// source is constant so it does not need to be loaded.
1601 /// It returns EVT::Other if the type should be determined using generic
1602 /// target-independent logic.
1603 EVT
1604 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1605                                        unsigned DstAlign, unsigned SrcAlign,
1606                                        bool IsMemset, bool ZeroMemset,
1607                                        bool MemcpyStrSrc,
1608                                        MachineFunction &MF) const {
1609   const Function *F = MF.getFunction();
1610   if ((!IsMemset || ZeroMemset) &&
1611       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1612                                        Attribute::NoImplicitFloat)) {
1613     if (Size >= 16 &&
1614         (Subtarget->isUnalignedMemAccessFast() ||
1615          ((DstAlign == 0 || DstAlign >= 16) &&
1616           (SrcAlign == 0 || SrcAlign >= 16)))) {
1617       if (Size >= 32) {
1618         if (Subtarget->hasInt256())
1619           return MVT::v8i32;
1620         if (Subtarget->hasFp256())
1621           return MVT::v8f32;
1622       }
1623       if (Subtarget->hasSSE2())
1624         return MVT::v4i32;
1625       if (Subtarget->hasSSE1())
1626         return MVT::v4f32;
1627     } else if (!MemcpyStrSrc && Size >= 8 &&
1628                !Subtarget->is64Bit() &&
1629                Subtarget->hasSSE2()) {
1630       // Do not use f64 to lower memcpy if source is string constant. It's
1631       // better to use i32 to avoid the loads.
1632       return MVT::f64;
1633     }
1634   }
1635   if (Subtarget->is64Bit() && Size >= 8)
1636     return MVT::i64;
1637   return MVT::i32;
1638 }
1639
1640 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1641   if (VT == MVT::f32)
1642     return X86ScalarSSEf32;
1643   else if (VT == MVT::f64)
1644     return X86ScalarSSEf64;
1645   return true;
1646 }
1647
1648 bool
1649 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1650   if (Fast)
1651     *Fast = Subtarget->isUnalignedMemAccessFast();
1652   return true;
1653 }
1654
1655 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1656 /// current function.  The returned value is a member of the
1657 /// MachineJumpTableInfo::JTEntryKind enum.
1658 unsigned X86TargetLowering::getJumpTableEncoding() const {
1659   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1660   // symbol.
1661   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1662       Subtarget->isPICStyleGOT())
1663     return MachineJumpTableInfo::EK_Custom32;
1664
1665   // Otherwise, use the normal jump table encoding heuristics.
1666   return TargetLowering::getJumpTableEncoding();
1667 }
1668
1669 const MCExpr *
1670 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1671                                              const MachineBasicBlock *MBB,
1672                                              unsigned uid,MCContext &Ctx) const{
1673   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1674          Subtarget->isPICStyleGOT());
1675   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1676   // entries.
1677   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1678                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1679 }
1680
1681 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1682 /// jumptable.
1683 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1684                                                     SelectionDAG &DAG) const {
1685   if (!Subtarget->is64Bit())
1686     // This doesn't have SDLoc associated with it, but is not really the
1687     // same as a Register.
1688     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1689   return Table;
1690 }
1691
1692 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1693 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1694 /// MCExpr.
1695 const MCExpr *X86TargetLowering::
1696 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1697                              MCContext &Ctx) const {
1698   // X86-64 uses RIP relative addressing based on the jump table label.
1699   if (Subtarget->isPICStyleRIPRel())
1700     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1701
1702   // Otherwise, the reference is relative to the PIC base.
1703   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1704 }
1705
1706 // FIXME: Why this routine is here? Move to RegInfo!
1707 std::pair<const TargetRegisterClass*, uint8_t>
1708 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1709   const TargetRegisterClass *RRC = 0;
1710   uint8_t Cost = 1;
1711   switch (VT.SimpleTy) {
1712   default:
1713     return TargetLowering::findRepresentativeClass(VT);
1714   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1715     RRC = Subtarget->is64Bit() ?
1716       (const TargetRegisterClass*)&X86::GR64RegClass :
1717       (const TargetRegisterClass*)&X86::GR32RegClass;
1718     break;
1719   case MVT::x86mmx:
1720     RRC = &X86::VR64RegClass;
1721     break;
1722   case MVT::f32: case MVT::f64:
1723   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1724   case MVT::v4f32: case MVT::v2f64:
1725   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1726   case MVT::v4f64:
1727     RRC = &X86::VR128RegClass;
1728     break;
1729   }
1730   return std::make_pair(RRC, Cost);
1731 }
1732
1733 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1734                                                unsigned &Offset) const {
1735   if (!Subtarget->isTargetLinux())
1736     return false;
1737
1738   if (Subtarget->is64Bit()) {
1739     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1740     Offset = 0x28;
1741     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1742       AddressSpace = 256;
1743     else
1744       AddressSpace = 257;
1745   } else {
1746     // %gs:0x14 on i386
1747     Offset = 0x14;
1748     AddressSpace = 256;
1749   }
1750   return true;
1751 }
1752
1753 //===----------------------------------------------------------------------===//
1754 //               Return Value Calling Convention Implementation
1755 //===----------------------------------------------------------------------===//
1756
1757 #include "X86GenCallingConv.inc"
1758
1759 bool
1760 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1761                                   MachineFunction &MF, bool isVarArg,
1762                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1763                         LLVMContext &Context) const {
1764   SmallVector<CCValAssign, 16> RVLocs;
1765   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1766                  RVLocs, Context);
1767   return CCInfo.CheckReturn(Outs, RetCC_X86);
1768 }
1769
1770 SDValue
1771 X86TargetLowering::LowerReturn(SDValue Chain,
1772                                CallingConv::ID CallConv, bool isVarArg,
1773                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1774                                const SmallVectorImpl<SDValue> &OutVals,
1775                                SDLoc dl, SelectionDAG &DAG) const {
1776   MachineFunction &MF = DAG.getMachineFunction();
1777   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1778
1779   SmallVector<CCValAssign, 16> RVLocs;
1780   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1781                  RVLocs, *DAG.getContext());
1782   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1783
1784   SDValue Flag;
1785   SmallVector<SDValue, 6> RetOps;
1786   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1787   // Operand #1 = Bytes To Pop
1788   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1789                    MVT::i16));
1790
1791   // Copy the result values into the output registers.
1792   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1793     CCValAssign &VA = RVLocs[i];
1794     assert(VA.isRegLoc() && "Can only return in registers!");
1795     SDValue ValToCopy = OutVals[i];
1796     EVT ValVT = ValToCopy.getValueType();
1797
1798     // Promote values to the appropriate types
1799     if (VA.getLocInfo() == CCValAssign::SExt)
1800       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1801     else if (VA.getLocInfo() == CCValAssign::ZExt)
1802       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1803     else if (VA.getLocInfo() == CCValAssign::AExt)
1804       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1805     else if (VA.getLocInfo() == CCValAssign::BCvt)
1806       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1807
1808     // If this is x86-64, and we disabled SSE, we can't return FP values,
1809     // or SSE or MMX vectors.
1810     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1811          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1812           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1813       report_fatal_error("SSE register return with SSE disabled");
1814     }
1815     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1816     // llvm-gcc has never done it right and no one has noticed, so this
1817     // should be OK for now.
1818     if (ValVT == MVT::f64 &&
1819         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1820       report_fatal_error("SSE2 register return with SSE2 disabled");
1821
1822     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1823     // the RET instruction and handled by the FP Stackifier.
1824     if (VA.getLocReg() == X86::ST0 ||
1825         VA.getLocReg() == X86::ST1) {
1826       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1827       // change the value to the FP stack register class.
1828       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1829         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1830       RetOps.push_back(ValToCopy);
1831       // Don't emit a copytoreg.
1832       continue;
1833     }
1834
1835     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1836     // which is returned in RAX / RDX.
1837     if (Subtarget->is64Bit()) {
1838       if (ValVT == MVT::x86mmx) {
1839         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1840           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1841           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1842                                   ValToCopy);
1843           // If we don't have SSE2 available, convert to v4f32 so the generated
1844           // register is legal.
1845           if (!Subtarget->hasSSE2())
1846             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1847         }
1848       }
1849     }
1850
1851     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1852     Flag = Chain.getValue(1);
1853     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1854   }
1855
1856   // The x86-64 ABIs require that for returning structs by value we copy
1857   // the sret argument into %rax/%eax (depending on ABI) for the return.
1858   // Win32 requires us to put the sret argument to %eax as well.
1859   // We saved the argument into a virtual register in the entry block,
1860   // so now we copy the value out and into %rax/%eax.
1861   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1862       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1863     MachineFunction &MF = DAG.getMachineFunction();
1864     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865     unsigned Reg = FuncInfo->getSRetReturnReg();
1866     assert(Reg &&
1867            "SRetReturnReg should have been set in LowerFormalArguments().");
1868     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1869
1870     unsigned RetValReg
1871         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1872           X86::RAX : X86::EAX;
1873     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1874     Flag = Chain.getValue(1);
1875
1876     // RAX/EAX now acts like a return value.
1877     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1878   }
1879
1880   RetOps[0] = Chain;  // Update chain.
1881
1882   // Add the flag if we have it.
1883   if (Flag.getNode())
1884     RetOps.push_back(Flag);
1885
1886   return DAG.getNode(X86ISD::RET_FLAG, dl,
1887                      MVT::Other, &RetOps[0], RetOps.size());
1888 }
1889
1890 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1891   if (N->getNumValues() != 1)
1892     return false;
1893   if (!N->hasNUsesOfValue(1, 0))
1894     return false;
1895
1896   SDValue TCChain = Chain;
1897   SDNode *Copy = *N->use_begin();
1898   if (Copy->getOpcode() == ISD::CopyToReg) {
1899     // If the copy has a glue operand, we conservatively assume it isn't safe to
1900     // perform a tail call.
1901     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1902       return false;
1903     TCChain = Copy->getOperand(0);
1904   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1905     return false;
1906
1907   bool HasRet = false;
1908   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1909        UI != UE; ++UI) {
1910     if (UI->getOpcode() != X86ISD::RET_FLAG)
1911       return false;
1912     HasRet = true;
1913   }
1914
1915   if (!HasRet)
1916     return false;
1917
1918   Chain = TCChain;
1919   return true;
1920 }
1921
1922 MVT
1923 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1924                                             ISD::NodeType ExtendKind) const {
1925   MVT ReturnMVT;
1926   // TODO: Is this also valid on 32-bit?
1927   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1928     ReturnMVT = MVT::i8;
1929   else
1930     ReturnMVT = MVT::i32;
1931
1932   MVT MinVT = getRegisterType(ReturnMVT);
1933   return VT.bitsLT(MinVT) ? MinVT : VT;
1934 }
1935
1936 /// LowerCallResult - Lower the result values of a call into the
1937 /// appropriate copies out of appropriate physical registers.
1938 ///
1939 SDValue
1940 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1941                                    CallingConv::ID CallConv, bool isVarArg,
1942                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1943                                    SDLoc dl, SelectionDAG &DAG,
1944                                    SmallVectorImpl<SDValue> &InVals) const {
1945
1946   // Assign locations to each value returned by this call.
1947   SmallVector<CCValAssign, 16> RVLocs;
1948   bool Is64Bit = Subtarget->is64Bit();
1949   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1950                  getTargetMachine(), RVLocs, *DAG.getContext());
1951   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1952
1953   // Copy all of the result registers out of their specified physreg.
1954   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1955     CCValAssign &VA = RVLocs[i];
1956     EVT CopyVT = VA.getValVT();
1957
1958     // If this is x86-64, and we disabled SSE, we can't return FP values
1959     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1960         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1961       report_fatal_error("SSE register return with SSE disabled");
1962     }
1963
1964     SDValue Val;
1965
1966     // If this is a call to a function that returns an fp value on the floating
1967     // point stack, we must guarantee the value is popped from the stack, so
1968     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1969     // if the return value is not used. We use the FpPOP_RETVAL instruction
1970     // instead.
1971     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1972       // If we prefer to use the value in xmm registers, copy it out as f80 and
1973       // use a truncate to move it from fp stack reg to xmm reg.
1974       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1975       SDValue Ops[] = { Chain, InFlag };
1976       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1977                                          MVT::Other, MVT::Glue, Ops), 1);
1978       Val = Chain.getValue(0);
1979
1980       // Round the f80 to the right size, which also moves it to the appropriate
1981       // xmm register.
1982       if (CopyVT != VA.getValVT())
1983         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1984                           // This truncation won't change the value.
1985                           DAG.getIntPtrConstant(1));
1986     } else {
1987       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1988                                  CopyVT, InFlag).getValue(1);
1989       Val = Chain.getValue(0);
1990     }
1991     InFlag = Chain.getValue(2);
1992     InVals.push_back(Val);
1993   }
1994
1995   return Chain;
1996 }
1997
1998 //===----------------------------------------------------------------------===//
1999 //                C & StdCall & Fast Calling Convention implementation
2000 //===----------------------------------------------------------------------===//
2001 //  StdCall calling convention seems to be standard for many Windows' API
2002 //  routines and around. It differs from C calling convention just a little:
2003 //  callee should clean up the stack, not caller. Symbols should be also
2004 //  decorated in some fancy way :) It doesn't support any vector arguments.
2005 //  For info on fast calling convention see Fast Calling Convention (tail call)
2006 //  implementation LowerX86_32FastCCCallTo.
2007
2008 /// CallIsStructReturn - Determines whether a call uses struct return
2009 /// semantics.
2010 enum StructReturnType {
2011   NotStructReturn,
2012   RegStructReturn,
2013   StackStructReturn
2014 };
2015 static StructReturnType
2016 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2017   if (Outs.empty())
2018     return NotStructReturn;
2019
2020   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2021   if (!Flags.isSRet())
2022     return NotStructReturn;
2023   if (Flags.isInReg())
2024     return RegStructReturn;
2025   return StackStructReturn;
2026 }
2027
2028 /// ArgsAreStructReturn - Determines whether a function uses struct
2029 /// return semantics.
2030 static StructReturnType
2031 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2032   if (Ins.empty())
2033     return NotStructReturn;
2034
2035   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2036   if (!Flags.isSRet())
2037     return NotStructReturn;
2038   if (Flags.isInReg())
2039     return RegStructReturn;
2040   return StackStructReturn;
2041 }
2042
2043 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2044 /// by "Src" to address "Dst" with size and alignment information specified by
2045 /// the specific parameter attribute. The copy will be passed as a byval
2046 /// function parameter.
2047 static SDValue
2048 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2049                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2050                           SDLoc dl) {
2051   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2052
2053   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2054                        /*isVolatile*/false, /*AlwaysInline=*/true,
2055                        MachinePointerInfo(), MachinePointerInfo());
2056 }
2057
2058 /// IsTailCallConvention - Return true if the calling convention is one that
2059 /// supports tail call optimization.
2060 static bool IsTailCallConvention(CallingConv::ID CC) {
2061   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2062           CC == CallingConv::HiPE);
2063 }
2064
2065 /// \brief Return true if the calling convention is a C calling convention.
2066 static bool IsCCallConvention(CallingConv::ID CC) {
2067   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2068           CC == CallingConv::X86_64_SysV);
2069 }
2070
2071 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2072   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2073     return false;
2074
2075   CallSite CS(CI);
2076   CallingConv::ID CalleeCC = CS.getCallingConv();
2077   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2078     return false;
2079
2080   return true;
2081 }
2082
2083 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2084 /// a tailcall target by changing its ABI.
2085 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2086                                    bool GuaranteedTailCallOpt) {
2087   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2088 }
2089
2090 SDValue
2091 X86TargetLowering::LowerMemArgument(SDValue Chain,
2092                                     CallingConv::ID CallConv,
2093                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2094                                     SDLoc dl, SelectionDAG &DAG,
2095                                     const CCValAssign &VA,
2096                                     MachineFrameInfo *MFI,
2097                                     unsigned i) const {
2098   // Create the nodes corresponding to a load from this parameter slot.
2099   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2100   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2101                               getTargetMachine().Options.GuaranteedTailCallOpt);
2102   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2103   EVT ValVT;
2104
2105   // If value is passed by pointer we have address passed instead of the value
2106   // itself.
2107   if (VA.getLocInfo() == CCValAssign::Indirect)
2108     ValVT = VA.getLocVT();
2109   else
2110     ValVT = VA.getValVT();
2111
2112   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2113   // changed with more analysis.
2114   // In case of tail call optimization mark all arguments mutable. Since they
2115   // could be overwritten by lowering of arguments in case of a tail call.
2116   if (Flags.isByVal()) {
2117     unsigned Bytes = Flags.getByValSize();
2118     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2119     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2120     return DAG.getFrameIndex(FI, getPointerTy());
2121   } else {
2122     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2123                                     VA.getLocMemOffset(), isImmutable);
2124     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2125     return DAG.getLoad(ValVT, dl, Chain, FIN,
2126                        MachinePointerInfo::getFixedStack(FI),
2127                        false, false, false, 0);
2128   }
2129 }
2130
2131 SDValue
2132 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2133                                         CallingConv::ID CallConv,
2134                                         bool isVarArg,
2135                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2136                                         SDLoc dl,
2137                                         SelectionDAG &DAG,
2138                                         SmallVectorImpl<SDValue> &InVals)
2139                                           const {
2140   MachineFunction &MF = DAG.getMachineFunction();
2141   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2142
2143   const Function* Fn = MF.getFunction();
2144   if (Fn->hasExternalLinkage() &&
2145       Subtarget->isTargetCygMing() &&
2146       Fn->getName() == "main")
2147     FuncInfo->setForceFramePointer(true);
2148
2149   MachineFrameInfo *MFI = MF.getFrameInfo();
2150   bool Is64Bit = Subtarget->is64Bit();
2151   bool IsWindows = Subtarget->isTargetWindows();
2152   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2153
2154   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2155          "Var args not supported with calling convention fastcc, ghc or hipe");
2156
2157   // Assign locations to all of the incoming arguments.
2158   SmallVector<CCValAssign, 16> ArgLocs;
2159   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2160                  ArgLocs, *DAG.getContext());
2161
2162   // Allocate shadow area for Win64
2163   if (IsWin64)
2164     CCInfo.AllocateStack(32, 8);
2165
2166   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2167
2168   unsigned LastVal = ~0U;
2169   SDValue ArgValue;
2170   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2171     CCValAssign &VA = ArgLocs[i];
2172     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2173     // places.
2174     assert(VA.getValNo() != LastVal &&
2175            "Don't support value assigned to multiple locs yet");
2176     (void)LastVal;
2177     LastVal = VA.getValNo();
2178
2179     if (VA.isRegLoc()) {
2180       EVT RegVT = VA.getLocVT();
2181       const TargetRegisterClass *RC;
2182       if (RegVT == MVT::i32)
2183         RC = &X86::GR32RegClass;
2184       else if (Is64Bit && RegVT == MVT::i64)
2185         RC = &X86::GR64RegClass;
2186       else if (RegVT == MVT::f32)
2187         RC = &X86::FR32RegClass;
2188       else if (RegVT == MVT::f64)
2189         RC = &X86::FR64RegClass;
2190       else if (RegVT.is512BitVector())
2191         RC = &X86::VR512RegClass;
2192       else if (RegVT.is256BitVector())
2193         RC = &X86::VR256RegClass;
2194       else if (RegVT.is128BitVector())
2195         RC = &X86::VR128RegClass;
2196       else if (RegVT == MVT::x86mmx)
2197         RC = &X86::VR64RegClass;
2198       else if (RegVT == MVT::v8i1)
2199         RC = &X86::VK8RegClass;
2200       else if (RegVT == MVT::v16i1)
2201         RC = &X86::VK16RegClass;
2202       else
2203         llvm_unreachable("Unknown argument type!");
2204
2205       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2206       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2207
2208       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2209       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2210       // right size.
2211       if (VA.getLocInfo() == CCValAssign::SExt)
2212         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2213                                DAG.getValueType(VA.getValVT()));
2214       else if (VA.getLocInfo() == CCValAssign::ZExt)
2215         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2216                                DAG.getValueType(VA.getValVT()));
2217       else if (VA.getLocInfo() == CCValAssign::BCvt)
2218         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2219
2220       if (VA.isExtInLoc()) {
2221         // Handle MMX values passed in XMM regs.
2222         if (RegVT.isVector())
2223           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2224         else
2225           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2226       }
2227     } else {
2228       assert(VA.isMemLoc());
2229       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2230     }
2231
2232     // If value is passed via pointer - do a load.
2233     if (VA.getLocInfo() == CCValAssign::Indirect)
2234       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2235                              MachinePointerInfo(), false, false, false, 0);
2236
2237     InVals.push_back(ArgValue);
2238   }
2239
2240   // The x86-64 ABIs require that for returning structs by value we copy
2241   // the sret argument into %rax/%eax (depending on ABI) for the return.
2242   // Win32 requires us to put the sret argument to %eax as well.
2243   // Save the argument into a virtual register so that we can access it
2244   // from the return points.
2245   if (MF.getFunction()->hasStructRetAttr() &&
2246       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2247     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2248     unsigned Reg = FuncInfo->getSRetReturnReg();
2249     if (!Reg) {
2250       MVT PtrTy = getPointerTy();
2251       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2252       FuncInfo->setSRetReturnReg(Reg);
2253     }
2254     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2255     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2256   }
2257
2258   unsigned StackSize = CCInfo.getNextStackOffset();
2259   // Align stack specially for tail calls.
2260   if (FuncIsMadeTailCallSafe(CallConv,
2261                              MF.getTarget().Options.GuaranteedTailCallOpt))
2262     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2263
2264   // If the function takes variable number of arguments, make a frame index for
2265   // the start of the first vararg value... for expansion of llvm.va_start.
2266   if (isVarArg) {
2267     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2268                     CallConv != CallingConv::X86_ThisCall)) {
2269       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2270     }
2271     if (Is64Bit) {
2272       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2273
2274       // FIXME: We should really autogenerate these arrays
2275       static const uint16_t GPR64ArgRegsWin64[] = {
2276         X86::RCX, X86::RDX, X86::R8,  X86::R9
2277       };
2278       static const uint16_t GPR64ArgRegs64Bit[] = {
2279         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2280       };
2281       static const uint16_t XMMArgRegs64Bit[] = {
2282         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2283         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2284       };
2285       const uint16_t *GPR64ArgRegs;
2286       unsigned NumXMMRegs = 0;
2287
2288       if (IsWin64) {
2289         // The XMM registers which might contain var arg parameters are shadowed
2290         // in their paired GPR.  So we only need to save the GPR to their home
2291         // slots.
2292         TotalNumIntRegs = 4;
2293         GPR64ArgRegs = GPR64ArgRegsWin64;
2294       } else {
2295         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2296         GPR64ArgRegs = GPR64ArgRegs64Bit;
2297
2298         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2299                                                 TotalNumXMMRegs);
2300       }
2301       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2302                                                        TotalNumIntRegs);
2303
2304       bool NoImplicitFloatOps = Fn->getAttributes().
2305         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2306       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2307              "SSE register cannot be used when SSE is disabled!");
2308       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2309                NoImplicitFloatOps) &&
2310              "SSE register cannot be used when SSE is disabled!");
2311       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2312           !Subtarget->hasSSE1())
2313         // Kernel mode asks for SSE to be disabled, so don't push them
2314         // on the stack.
2315         TotalNumXMMRegs = 0;
2316
2317       if (IsWin64) {
2318         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2319         // Get to the caller-allocated home save location.  Add 8 to account
2320         // for the return address.
2321         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2322         FuncInfo->setRegSaveFrameIndex(
2323           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2324         // Fixup to set vararg frame on shadow area (4 x i64).
2325         if (NumIntRegs < 4)
2326           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2327       } else {
2328         // For X86-64, if there are vararg parameters that are passed via
2329         // registers, then we must store them to their spots on the stack so
2330         // they may be loaded by deferencing the result of va_next.
2331         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2332         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2333         FuncInfo->setRegSaveFrameIndex(
2334           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2335                                false));
2336       }
2337
2338       // Store the integer parameter registers.
2339       SmallVector<SDValue, 8> MemOps;
2340       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2341                                         getPointerTy());
2342       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2343       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2344         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2345                                   DAG.getIntPtrConstant(Offset));
2346         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2347                                      &X86::GR64RegClass);
2348         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2349         SDValue Store =
2350           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2351                        MachinePointerInfo::getFixedStack(
2352                          FuncInfo->getRegSaveFrameIndex(), Offset),
2353                        false, false, 0);
2354         MemOps.push_back(Store);
2355         Offset += 8;
2356       }
2357
2358       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2359         // Now store the XMM (fp + vector) parameter registers.
2360         SmallVector<SDValue, 11> SaveXMMOps;
2361         SaveXMMOps.push_back(Chain);
2362
2363         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2364         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2365         SaveXMMOps.push_back(ALVal);
2366
2367         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2368                                FuncInfo->getRegSaveFrameIndex()));
2369         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2370                                FuncInfo->getVarArgsFPOffset()));
2371
2372         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2373           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2374                                        &X86::VR128RegClass);
2375           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2376           SaveXMMOps.push_back(Val);
2377         }
2378         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2379                                      MVT::Other,
2380                                      &SaveXMMOps[0], SaveXMMOps.size()));
2381       }
2382
2383       if (!MemOps.empty())
2384         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2385                             &MemOps[0], MemOps.size());
2386     }
2387   }
2388
2389   // Some CCs need callee pop.
2390   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2391                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2392     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2393   } else {
2394     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2395     // If this is an sret function, the return should pop the hidden pointer.
2396     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2397         argsAreStructReturn(Ins) == StackStructReturn)
2398       FuncInfo->setBytesToPopOnReturn(4);
2399   }
2400
2401   if (!Is64Bit) {
2402     // RegSaveFrameIndex is X86-64 only.
2403     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2404     if (CallConv == CallingConv::X86_FastCall ||
2405         CallConv == CallingConv::X86_ThisCall)
2406       // fastcc functions can't have varargs.
2407       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2408   }
2409
2410   FuncInfo->setArgumentStackSize(StackSize);
2411
2412   return Chain;
2413 }
2414
2415 SDValue
2416 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2417                                     SDValue StackPtr, SDValue Arg,
2418                                     SDLoc dl, SelectionDAG &DAG,
2419                                     const CCValAssign &VA,
2420                                     ISD::ArgFlagsTy Flags) const {
2421   unsigned LocMemOffset = VA.getLocMemOffset();
2422   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2423   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2424   if (Flags.isByVal())
2425     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2426
2427   return DAG.getStore(Chain, dl, Arg, PtrOff,
2428                       MachinePointerInfo::getStack(LocMemOffset),
2429                       false, false, 0);
2430 }
2431
2432 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2433 /// optimization is performed and it is required.
2434 SDValue
2435 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2436                                            SDValue &OutRetAddr, SDValue Chain,
2437                                            bool IsTailCall, bool Is64Bit,
2438                                            int FPDiff, SDLoc dl) const {
2439   // Adjust the Return address stack slot.
2440   EVT VT = getPointerTy();
2441   OutRetAddr = getReturnAddressFrameIndex(DAG);
2442
2443   // Load the "old" Return address.
2444   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2445                            false, false, false, 0);
2446   return SDValue(OutRetAddr.getNode(), 1);
2447 }
2448
2449 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2450 /// optimization is performed and it is required (FPDiff!=0).
2451 static SDValue
2452 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2453                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2454                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2455   // Store the return address to the appropriate stack slot.
2456   if (!FPDiff) return Chain;
2457   // Calculate the new stack slot for the return address.
2458   int NewReturnAddrFI =
2459     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2460                                          false);
2461   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2462   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2463                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2464                        false, false, 0);
2465   return Chain;
2466 }
2467
2468 SDValue
2469 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2470                              SmallVectorImpl<SDValue> &InVals) const {
2471   SelectionDAG &DAG                     = CLI.DAG;
2472   SDLoc &dl                             = CLI.DL;
2473   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2474   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2475   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2476   SDValue Chain                         = CLI.Chain;
2477   SDValue Callee                        = CLI.Callee;
2478   CallingConv::ID CallConv              = CLI.CallConv;
2479   bool &isTailCall                      = CLI.IsTailCall;
2480   bool isVarArg                         = CLI.IsVarArg;
2481
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   bool Is64Bit        = Subtarget->is64Bit();
2484   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2485   bool IsWindows      = Subtarget->isTargetWindows();
2486   StructReturnType SR = callIsStructReturn(Outs);
2487   bool IsSibcall      = false;
2488
2489   if (MF.getTarget().Options.DisableTailCalls)
2490     isTailCall = false;
2491
2492   if (isTailCall) {
2493     // Check if it's really possible to do a tail call.
2494     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2495                     isVarArg, SR != NotStructReturn,
2496                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2497                     Outs, OutVals, Ins, DAG);
2498
2499     // Sibcalls are automatically detected tailcalls which do not require
2500     // ABI changes.
2501     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2502       IsSibcall = true;
2503
2504     if (isTailCall)
2505       ++NumTailCalls;
2506   }
2507
2508   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2509          "Var args not supported with calling convention fastcc, ghc or hipe");
2510
2511   // Analyze operands of the call, assigning locations to each operand.
2512   SmallVector<CCValAssign, 16> ArgLocs;
2513   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2514                  ArgLocs, *DAG.getContext());
2515
2516   // Allocate shadow area for Win64
2517   if (IsWin64)
2518     CCInfo.AllocateStack(32, 8);
2519
2520   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2521
2522   // Get a count of how many bytes are to be pushed on the stack.
2523   unsigned NumBytes = CCInfo.getNextStackOffset();
2524   if (IsSibcall)
2525     // This is a sibcall. The memory operands are available in caller's
2526     // own caller's stack.
2527     NumBytes = 0;
2528   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2529            IsTailCallConvention(CallConv))
2530     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2531
2532   int FPDiff = 0;
2533   if (isTailCall && !IsSibcall) {
2534     // Lower arguments at fp - stackoffset + fpdiff.
2535     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2536     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2537
2538     FPDiff = NumBytesCallerPushed - NumBytes;
2539
2540     // Set the delta of movement of the returnaddr stackslot.
2541     // But only set if delta is greater than previous delta.
2542     if (FPDiff < X86Info->getTCReturnAddrDelta())
2543       X86Info->setTCReturnAddrDelta(FPDiff);
2544   }
2545
2546   if (!IsSibcall)
2547     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2548                                  dl);
2549
2550   SDValue RetAddrFrIdx;
2551   // Load return address for tail calls.
2552   if (isTailCall && FPDiff)
2553     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2554                                     Is64Bit, FPDiff, dl);
2555
2556   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2557   SmallVector<SDValue, 8> MemOpChains;
2558   SDValue StackPtr;
2559
2560   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2561   // of tail call optimization arguments are handle later.
2562   const X86RegisterInfo *RegInfo =
2563     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2564   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2565     CCValAssign &VA = ArgLocs[i];
2566     EVT RegVT = VA.getLocVT();
2567     SDValue Arg = OutVals[i];
2568     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2569     bool isByVal = Flags.isByVal();
2570
2571     // Promote the value if needed.
2572     switch (VA.getLocInfo()) {
2573     default: llvm_unreachable("Unknown loc info!");
2574     case CCValAssign::Full: break;
2575     case CCValAssign::SExt:
2576       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2577       break;
2578     case CCValAssign::ZExt:
2579       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2580       break;
2581     case CCValAssign::AExt:
2582       if (RegVT.is128BitVector()) {
2583         // Special case: passing MMX values in XMM registers.
2584         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2585         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2586         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2587       } else
2588         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2589       break;
2590     case CCValAssign::BCvt:
2591       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2592       break;
2593     case CCValAssign::Indirect: {
2594       // Store the argument.
2595       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2596       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2597       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2598                            MachinePointerInfo::getFixedStack(FI),
2599                            false, false, 0);
2600       Arg = SpillSlot;
2601       break;
2602     }
2603     }
2604
2605     if (VA.isRegLoc()) {
2606       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2607       if (isVarArg && IsWin64) {
2608         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2609         // shadow reg if callee is a varargs function.
2610         unsigned ShadowReg = 0;
2611         switch (VA.getLocReg()) {
2612         case X86::XMM0: ShadowReg = X86::RCX; break;
2613         case X86::XMM1: ShadowReg = X86::RDX; break;
2614         case X86::XMM2: ShadowReg = X86::R8; break;
2615         case X86::XMM3: ShadowReg = X86::R9; break;
2616         }
2617         if (ShadowReg)
2618           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2619       }
2620     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2621       assert(VA.isMemLoc());
2622       if (StackPtr.getNode() == 0)
2623         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2624                                       getPointerTy());
2625       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2626                                              dl, DAG, VA, Flags));
2627     }
2628   }
2629
2630   if (!MemOpChains.empty())
2631     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2632                         &MemOpChains[0], MemOpChains.size());
2633
2634   if (Subtarget->isPICStyleGOT()) {
2635     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2636     // GOT pointer.
2637     if (!isTailCall) {
2638       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2639                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2640     } else {
2641       // If we are tail calling and generating PIC/GOT style code load the
2642       // address of the callee into ECX. The value in ecx is used as target of
2643       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2644       // for tail calls on PIC/GOT architectures. Normally we would just put the
2645       // address of GOT into ebx and then call target@PLT. But for tail calls
2646       // ebx would be restored (since ebx is callee saved) before jumping to the
2647       // target@PLT.
2648
2649       // Note: The actual moving to ECX is done further down.
2650       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2651       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2652           !G->getGlobal()->hasProtectedVisibility())
2653         Callee = LowerGlobalAddress(Callee, DAG);
2654       else if (isa<ExternalSymbolSDNode>(Callee))
2655         Callee = LowerExternalSymbol(Callee, DAG);
2656     }
2657   }
2658
2659   if (Is64Bit && isVarArg && !IsWin64) {
2660     // From AMD64 ABI document:
2661     // For calls that may call functions that use varargs or stdargs
2662     // (prototype-less calls or calls to functions containing ellipsis (...) in
2663     // the declaration) %al is used as hidden argument to specify the number
2664     // of SSE registers used. The contents of %al do not need to match exactly
2665     // the number of registers, but must be an ubound on the number of SSE
2666     // registers used and is in the range 0 - 8 inclusive.
2667
2668     // Count the number of XMM registers allocated.
2669     static const uint16_t XMMArgRegs[] = {
2670       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2671       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2672     };
2673     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2674     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2675            && "SSE registers cannot be used when SSE is disabled");
2676
2677     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2678                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2679   }
2680
2681   // For tail calls lower the arguments to the 'real' stack slot.
2682   if (isTailCall) {
2683     // Force all the incoming stack arguments to be loaded from the stack
2684     // before any new outgoing arguments are stored to the stack, because the
2685     // outgoing stack slots may alias the incoming argument stack slots, and
2686     // the alias isn't otherwise explicit. This is slightly more conservative
2687     // than necessary, because it means that each store effectively depends
2688     // on every argument instead of just those arguments it would clobber.
2689     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2690
2691     SmallVector<SDValue, 8> MemOpChains2;
2692     SDValue FIN;
2693     int FI = 0;
2694     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2695       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696         CCValAssign &VA = ArgLocs[i];
2697         if (VA.isRegLoc())
2698           continue;
2699         assert(VA.isMemLoc());
2700         SDValue Arg = OutVals[i];
2701         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2702         // Create frame index.
2703         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2704         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2705         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2706         FIN = DAG.getFrameIndex(FI, getPointerTy());
2707
2708         if (Flags.isByVal()) {
2709           // Copy relative to framepointer.
2710           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2711           if (StackPtr.getNode() == 0)
2712             StackPtr = DAG.getCopyFromReg(Chain, dl,
2713                                           RegInfo->getStackRegister(),
2714                                           getPointerTy());
2715           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2716
2717           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2718                                                            ArgChain,
2719                                                            Flags, DAG, dl));
2720         } else {
2721           // Store relative to framepointer.
2722           MemOpChains2.push_back(
2723             DAG.getStore(ArgChain, dl, Arg, FIN,
2724                          MachinePointerInfo::getFixedStack(FI),
2725                          false, false, 0));
2726         }
2727       }
2728     }
2729
2730     if (!MemOpChains2.empty())
2731       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2732                           &MemOpChains2[0], MemOpChains2.size());
2733
2734     // Store the return address to the appropriate stack slot.
2735     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2736                                      getPointerTy(), RegInfo->getSlotSize(),
2737                                      FPDiff, dl);
2738   }
2739
2740   // Build a sequence of copy-to-reg nodes chained together with token chain
2741   // and flag operands which copy the outgoing args into registers.
2742   SDValue InFlag;
2743   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2744     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2745                              RegsToPass[i].second, InFlag);
2746     InFlag = Chain.getValue(1);
2747   }
2748
2749   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2750     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2751     // In the 64-bit large code model, we have to make all calls
2752     // through a register, since the call instruction's 32-bit
2753     // pc-relative offset may not be large enough to hold the whole
2754     // address.
2755   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2756     // If the callee is a GlobalAddress node (quite common, every direct call
2757     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2758     // it.
2759
2760     // We should use extra load for direct calls to dllimported functions in
2761     // non-JIT mode.
2762     const GlobalValue *GV = G->getGlobal();
2763     if (!GV->hasDLLImportLinkage()) {
2764       unsigned char OpFlags = 0;
2765       bool ExtraLoad = false;
2766       unsigned WrapperKind = ISD::DELETED_NODE;
2767
2768       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2769       // external symbols most go through the PLT in PIC mode.  If the symbol
2770       // has hidden or protected visibility, or if it is static or local, then
2771       // we don't need to use the PLT - we can directly call it.
2772       if (Subtarget->isTargetELF() &&
2773           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2774           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2775         OpFlags = X86II::MO_PLT;
2776       } else if (Subtarget->isPICStyleStubAny() &&
2777                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2778                  (!Subtarget->getTargetTriple().isMacOSX() ||
2779                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2780         // PC-relative references to external symbols should go through $stub,
2781         // unless we're building with the leopard linker or later, which
2782         // automatically synthesizes these stubs.
2783         OpFlags = X86II::MO_DARWIN_STUB;
2784       } else if (Subtarget->isPICStyleRIPRel() &&
2785                  isa<Function>(GV) &&
2786                  cast<Function>(GV)->getAttributes().
2787                    hasAttribute(AttributeSet::FunctionIndex,
2788                                 Attribute::NonLazyBind)) {
2789         // If the function is marked as non-lazy, generate an indirect call
2790         // which loads from the GOT directly. This avoids runtime overhead
2791         // at the cost of eager binding (and one extra byte of encoding).
2792         OpFlags = X86II::MO_GOTPCREL;
2793         WrapperKind = X86ISD::WrapperRIP;
2794         ExtraLoad = true;
2795       }
2796
2797       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2798                                           G->getOffset(), OpFlags);
2799
2800       // Add a wrapper if needed.
2801       if (WrapperKind != ISD::DELETED_NODE)
2802         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2803       // Add extra indirection if needed.
2804       if (ExtraLoad)
2805         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2806                              MachinePointerInfo::getGOT(),
2807                              false, false, false, 0);
2808     }
2809   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2810     unsigned char OpFlags = 0;
2811
2812     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2813     // external symbols should go through the PLT.
2814     if (Subtarget->isTargetELF() &&
2815         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2816       OpFlags = X86II::MO_PLT;
2817     } else if (Subtarget->isPICStyleStubAny() &&
2818                (!Subtarget->getTargetTriple().isMacOSX() ||
2819                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2820       // PC-relative references to external symbols should go through $stub,
2821       // unless we're building with the leopard linker or later, which
2822       // automatically synthesizes these stubs.
2823       OpFlags = X86II::MO_DARWIN_STUB;
2824     }
2825
2826     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2827                                          OpFlags);
2828   }
2829
2830   // Returns a chain & a flag for retval copy to use.
2831   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2832   SmallVector<SDValue, 8> Ops;
2833
2834   if (!IsSibcall && isTailCall) {
2835     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2836                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2837     InFlag = Chain.getValue(1);
2838   }
2839
2840   Ops.push_back(Chain);
2841   Ops.push_back(Callee);
2842
2843   if (isTailCall)
2844     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2845
2846   // Add argument registers to the end of the list so that they are known live
2847   // into the call.
2848   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2849     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2850                                   RegsToPass[i].second.getValueType()));
2851
2852   // Add a register mask operand representing the call-preserved registers.
2853   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2854   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2855   assert(Mask && "Missing call preserved mask for calling convention");
2856   Ops.push_back(DAG.getRegisterMask(Mask));
2857
2858   if (InFlag.getNode())
2859     Ops.push_back(InFlag);
2860
2861   if (isTailCall) {
2862     // We used to do:
2863     //// If this is the first return lowered for this function, add the regs
2864     //// to the liveout set for the function.
2865     // This isn't right, although it's probably harmless on x86; liveouts
2866     // should be computed from returns not tail calls.  Consider a void
2867     // function making a tail call to a function returning int.
2868     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2869   }
2870
2871   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2872   InFlag = Chain.getValue(1);
2873
2874   // Create the CALLSEQ_END node.
2875   unsigned NumBytesForCalleeToPush;
2876   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2877                        getTargetMachine().Options.GuaranteedTailCallOpt))
2878     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2879   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2880            SR == StackStructReturn)
2881     // If this is a call to a struct-return function, the callee
2882     // pops the hidden struct pointer, so we have to push it back.
2883     // This is common for Darwin/X86, Linux & Mingw32 targets.
2884     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2885     NumBytesForCalleeToPush = 4;
2886   else
2887     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2888
2889   // Returns a flag for retval copy to use.
2890   if (!IsSibcall) {
2891     Chain = DAG.getCALLSEQ_END(Chain,
2892                                DAG.getIntPtrConstant(NumBytes, true),
2893                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2894                                                      true),
2895                                InFlag, dl);
2896     InFlag = Chain.getValue(1);
2897   }
2898
2899   // Handle result values, copying them out of physregs into vregs that we
2900   // return.
2901   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2902                          Ins, dl, DAG, InVals);
2903 }
2904
2905 //===----------------------------------------------------------------------===//
2906 //                Fast Calling Convention (tail call) implementation
2907 //===----------------------------------------------------------------------===//
2908
2909 //  Like std call, callee cleans arguments, convention except that ECX is
2910 //  reserved for storing the tail called function address. Only 2 registers are
2911 //  free for argument passing (inreg). Tail call optimization is performed
2912 //  provided:
2913 //                * tailcallopt is enabled
2914 //                * caller/callee are fastcc
2915 //  On X86_64 architecture with GOT-style position independent code only local
2916 //  (within module) calls are supported at the moment.
2917 //  To keep the stack aligned according to platform abi the function
2918 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2919 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2920 //  If a tail called function callee has more arguments than the caller the
2921 //  caller needs to make sure that there is room to move the RETADDR to. This is
2922 //  achieved by reserving an area the size of the argument delta right after the
2923 //  original REtADDR, but before the saved framepointer or the spilled registers
2924 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2925 //  stack layout:
2926 //    arg1
2927 //    arg2
2928 //    RETADDR
2929 //    [ new RETADDR
2930 //      move area ]
2931 //    (possible EBP)
2932 //    ESI
2933 //    EDI
2934 //    local1 ..
2935
2936 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2937 /// for a 16 byte align requirement.
2938 unsigned
2939 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2940                                                SelectionDAG& DAG) const {
2941   MachineFunction &MF = DAG.getMachineFunction();
2942   const TargetMachine &TM = MF.getTarget();
2943   const X86RegisterInfo *RegInfo =
2944     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2945   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2946   unsigned StackAlignment = TFI.getStackAlignment();
2947   uint64_t AlignMask = StackAlignment - 1;
2948   int64_t Offset = StackSize;
2949   unsigned SlotSize = RegInfo->getSlotSize();
2950   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2951     // Number smaller than 12 so just add the difference.
2952     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2953   } else {
2954     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2955     Offset = ((~AlignMask) & Offset) + StackAlignment +
2956       (StackAlignment-SlotSize);
2957   }
2958   return Offset;
2959 }
2960
2961 /// MatchingStackOffset - Return true if the given stack call argument is
2962 /// already available in the same position (relatively) of the caller's
2963 /// incoming argument stack.
2964 static
2965 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2966                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2967                          const X86InstrInfo *TII) {
2968   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2969   int FI = INT_MAX;
2970   if (Arg.getOpcode() == ISD::CopyFromReg) {
2971     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2972     if (!TargetRegisterInfo::isVirtualRegister(VR))
2973       return false;
2974     MachineInstr *Def = MRI->getVRegDef(VR);
2975     if (!Def)
2976       return false;
2977     if (!Flags.isByVal()) {
2978       if (!TII->isLoadFromStackSlot(Def, FI))
2979         return false;
2980     } else {
2981       unsigned Opcode = Def->getOpcode();
2982       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2983           Def->getOperand(1).isFI()) {
2984         FI = Def->getOperand(1).getIndex();
2985         Bytes = Flags.getByValSize();
2986       } else
2987         return false;
2988     }
2989   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2990     if (Flags.isByVal())
2991       // ByVal argument is passed in as a pointer but it's now being
2992       // dereferenced. e.g.
2993       // define @foo(%struct.X* %A) {
2994       //   tail call @bar(%struct.X* byval %A)
2995       // }
2996       return false;
2997     SDValue Ptr = Ld->getBasePtr();
2998     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2999     if (!FINode)
3000       return false;
3001     FI = FINode->getIndex();
3002   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3003     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3004     FI = FINode->getIndex();
3005     Bytes = Flags.getByValSize();
3006   } else
3007     return false;
3008
3009   assert(FI != INT_MAX);
3010   if (!MFI->isFixedObjectIndex(FI))
3011     return false;
3012   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3013 }
3014
3015 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3016 /// for tail call optimization. Targets which want to do tail call
3017 /// optimization should implement this function.
3018 bool
3019 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3020                                                      CallingConv::ID CalleeCC,
3021                                                      bool isVarArg,
3022                                                      bool isCalleeStructRet,
3023                                                      bool isCallerStructRet,
3024                                                      Type *RetTy,
3025                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3026                                     const SmallVectorImpl<SDValue> &OutVals,
3027                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3028                                                      SelectionDAG &DAG) const {
3029   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3030     return false;
3031
3032   // If -tailcallopt is specified, make fastcc functions tail-callable.
3033   const MachineFunction &MF = DAG.getMachineFunction();
3034   const Function *CallerF = MF.getFunction();
3035
3036   // If the function return type is x86_fp80 and the callee return type is not,
3037   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3038   // perform a tailcall optimization here.
3039   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3040     return false;
3041
3042   CallingConv::ID CallerCC = CallerF->getCallingConv();
3043   bool CCMatch = CallerCC == CalleeCC;
3044   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3045   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3046
3047   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3048     if (IsTailCallConvention(CalleeCC) && CCMatch)
3049       return true;
3050     return false;
3051   }
3052
3053   // Look for obvious safe cases to perform tail call optimization that do not
3054   // require ABI changes. This is what gcc calls sibcall.
3055
3056   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3057   // emit a special epilogue.
3058   const X86RegisterInfo *RegInfo =
3059     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3060   if (RegInfo->needsStackRealignment(MF))
3061     return false;
3062
3063   // Also avoid sibcall optimization if either caller or callee uses struct
3064   // return semantics.
3065   if (isCalleeStructRet || isCallerStructRet)
3066     return false;
3067
3068   // An stdcall caller is expected to clean up its arguments; the callee
3069   // isn't going to do that.
3070   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
3071     return false;
3072
3073   // Do not sibcall optimize vararg calls unless all arguments are passed via
3074   // registers.
3075   if (isVarArg && !Outs.empty()) {
3076
3077     // Optimizing for varargs on Win64 is unlikely to be safe without
3078     // additional testing.
3079     if (IsCalleeWin64 || IsCallerWin64)
3080       return false;
3081
3082     SmallVector<CCValAssign, 16> ArgLocs;
3083     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3084                    getTargetMachine(), ArgLocs, *DAG.getContext());
3085
3086     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3087     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3088       if (!ArgLocs[i].isRegLoc())
3089         return false;
3090   }
3091
3092   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3093   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3094   // this into a sibcall.
3095   bool Unused = false;
3096   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3097     if (!Ins[i].Used) {
3098       Unused = true;
3099       break;
3100     }
3101   }
3102   if (Unused) {
3103     SmallVector<CCValAssign, 16> RVLocs;
3104     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3105                    getTargetMachine(), RVLocs, *DAG.getContext());
3106     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3107     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3108       CCValAssign &VA = RVLocs[i];
3109       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3110         return false;
3111     }
3112   }
3113
3114   // If the calling conventions do not match, then we'd better make sure the
3115   // results are returned in the same way as what the caller expects.
3116   if (!CCMatch) {
3117     SmallVector<CCValAssign, 16> RVLocs1;
3118     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3119                     getTargetMachine(), RVLocs1, *DAG.getContext());
3120     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3121
3122     SmallVector<CCValAssign, 16> RVLocs2;
3123     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3124                     getTargetMachine(), RVLocs2, *DAG.getContext());
3125     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3126
3127     if (RVLocs1.size() != RVLocs2.size())
3128       return false;
3129     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3130       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3131         return false;
3132       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3133         return false;
3134       if (RVLocs1[i].isRegLoc()) {
3135         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3136           return false;
3137       } else {
3138         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3139           return false;
3140       }
3141     }
3142   }
3143
3144   // If the callee takes no arguments then go on to check the results of the
3145   // call.
3146   if (!Outs.empty()) {
3147     // Check if stack adjustment is needed. For now, do not do this if any
3148     // argument is passed on the stack.
3149     SmallVector<CCValAssign, 16> ArgLocs;
3150     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3151                    getTargetMachine(), ArgLocs, *DAG.getContext());
3152
3153     // Allocate shadow area for Win64
3154     if (IsCalleeWin64)
3155       CCInfo.AllocateStack(32, 8);
3156
3157     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3158     if (CCInfo.getNextStackOffset()) {
3159       MachineFunction &MF = DAG.getMachineFunction();
3160       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3161         return false;
3162
3163       // Check if the arguments are already laid out in the right way as
3164       // the caller's fixed stack objects.
3165       MachineFrameInfo *MFI = MF.getFrameInfo();
3166       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3167       const X86InstrInfo *TII =
3168         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3169       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3170         CCValAssign &VA = ArgLocs[i];
3171         SDValue Arg = OutVals[i];
3172         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3173         if (VA.getLocInfo() == CCValAssign::Indirect)
3174           return false;
3175         if (!VA.isRegLoc()) {
3176           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3177                                    MFI, MRI, TII))
3178             return false;
3179         }
3180       }
3181     }
3182
3183     // If the tailcall address may be in a register, then make sure it's
3184     // possible to register allocate for it. In 32-bit, the call address can
3185     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3186     // callee-saved registers are restored. These happen to be the same
3187     // registers used to pass 'inreg' arguments so watch out for those.
3188     if (!Subtarget->is64Bit() &&
3189         ((!isa<GlobalAddressSDNode>(Callee) &&
3190           !isa<ExternalSymbolSDNode>(Callee)) ||
3191          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3192       unsigned NumInRegs = 0;
3193       // In PIC we need an extra register to formulate the address computation
3194       // for the callee.
3195       unsigned MaxInRegs =
3196           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3197
3198       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3199         CCValAssign &VA = ArgLocs[i];
3200         if (!VA.isRegLoc())
3201           continue;
3202         unsigned Reg = VA.getLocReg();
3203         switch (Reg) {
3204         default: break;
3205         case X86::EAX: case X86::EDX: case X86::ECX:
3206           if (++NumInRegs == MaxInRegs)
3207             return false;
3208           break;
3209         }
3210       }
3211     }
3212   }
3213
3214   return true;
3215 }
3216
3217 FastISel *
3218 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3219                                   const TargetLibraryInfo *libInfo) const {
3220   return X86::createFastISel(funcInfo, libInfo);
3221 }
3222
3223 //===----------------------------------------------------------------------===//
3224 //                           Other Lowering Hooks
3225 //===----------------------------------------------------------------------===//
3226
3227 static bool MayFoldLoad(SDValue Op) {
3228   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3229 }
3230
3231 static bool MayFoldIntoStore(SDValue Op) {
3232   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3233 }
3234
3235 static bool isTargetShuffle(unsigned Opcode) {
3236   switch(Opcode) {
3237   default: return false;
3238   case X86ISD::PSHUFD:
3239   case X86ISD::PSHUFHW:
3240   case X86ISD::PSHUFLW:
3241   case X86ISD::SHUFP:
3242   case X86ISD::PALIGNR:
3243   case X86ISD::MOVLHPS:
3244   case X86ISD::MOVLHPD:
3245   case X86ISD::MOVHLPS:
3246   case X86ISD::MOVLPS:
3247   case X86ISD::MOVLPD:
3248   case X86ISD::MOVSHDUP:
3249   case X86ISD::MOVSLDUP:
3250   case X86ISD::MOVDDUP:
3251   case X86ISD::MOVSS:
3252   case X86ISD::MOVSD:
3253   case X86ISD::UNPCKL:
3254   case X86ISD::UNPCKH:
3255   case X86ISD::VPERMILP:
3256   case X86ISD::VPERM2X128:
3257   case X86ISD::VPERMI:
3258     return true;
3259   }
3260 }
3261
3262 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3263                                     SDValue V1, SelectionDAG &DAG) {
3264   switch(Opc) {
3265   default: llvm_unreachable("Unknown x86 shuffle node");
3266   case X86ISD::MOVSHDUP:
3267   case X86ISD::MOVSLDUP:
3268   case X86ISD::MOVDDUP:
3269     return DAG.getNode(Opc, dl, VT, V1);
3270   }
3271 }
3272
3273 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3274                                     SDValue V1, unsigned TargetMask,
3275                                     SelectionDAG &DAG) {
3276   switch(Opc) {
3277   default: llvm_unreachable("Unknown x86 shuffle node");
3278   case X86ISD::PSHUFD:
3279   case X86ISD::PSHUFHW:
3280   case X86ISD::PSHUFLW:
3281   case X86ISD::VPERMILP:
3282   case X86ISD::VPERMI:
3283     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3284   }
3285 }
3286
3287 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3288                                     SDValue V1, SDValue V2, unsigned TargetMask,
3289                                     SelectionDAG &DAG) {
3290   switch(Opc) {
3291   default: llvm_unreachable("Unknown x86 shuffle node");
3292   case X86ISD::PALIGNR:
3293   case X86ISD::SHUFP:
3294   case X86ISD::VPERM2X128:
3295     return DAG.getNode(Opc, dl, VT, V1, V2,
3296                        DAG.getConstant(TargetMask, MVT::i8));
3297   }
3298 }
3299
3300 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3301                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3302   switch(Opc) {
3303   default: llvm_unreachable("Unknown x86 shuffle node");
3304   case X86ISD::MOVLHPS:
3305   case X86ISD::MOVLHPD:
3306   case X86ISD::MOVHLPS:
3307   case X86ISD::MOVLPS:
3308   case X86ISD::MOVLPD:
3309   case X86ISD::MOVSS:
3310   case X86ISD::MOVSD:
3311   case X86ISD::UNPCKL:
3312   case X86ISD::UNPCKH:
3313     return DAG.getNode(Opc, dl, VT, V1, V2);
3314   }
3315 }
3316
3317 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3318   MachineFunction &MF = DAG.getMachineFunction();
3319   const X86RegisterInfo *RegInfo =
3320     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3321   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3322   int ReturnAddrIndex = FuncInfo->getRAIndex();
3323
3324   if (ReturnAddrIndex == 0) {
3325     // Set up a frame object for the return address.
3326     unsigned SlotSize = RegInfo->getSlotSize();
3327     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3328                                                            -(int64_t)SlotSize,
3329                                                            false);
3330     FuncInfo->setRAIndex(ReturnAddrIndex);
3331   }
3332
3333   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3334 }
3335
3336 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3337                                        bool hasSymbolicDisplacement) {
3338   // Offset should fit into 32 bit immediate field.
3339   if (!isInt<32>(Offset))
3340     return false;
3341
3342   // If we don't have a symbolic displacement - we don't have any extra
3343   // restrictions.
3344   if (!hasSymbolicDisplacement)
3345     return true;
3346
3347   // FIXME: Some tweaks might be needed for medium code model.
3348   if (M != CodeModel::Small && M != CodeModel::Kernel)
3349     return false;
3350
3351   // For small code model we assume that latest object is 16MB before end of 31
3352   // bits boundary. We may also accept pretty large negative constants knowing
3353   // that all objects are in the positive half of address space.
3354   if (M == CodeModel::Small && Offset < 16*1024*1024)
3355     return true;
3356
3357   // For kernel code model we know that all object resist in the negative half
3358   // of 32bits address space. We may not accept negative offsets, since they may
3359   // be just off and we may accept pretty large positive ones.
3360   if (M == CodeModel::Kernel && Offset > 0)
3361     return true;
3362
3363   return false;
3364 }
3365
3366 /// isCalleePop - Determines whether the callee is required to pop its
3367 /// own arguments. Callee pop is necessary to support tail calls.
3368 bool X86::isCalleePop(CallingConv::ID CallingConv,
3369                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3370   if (IsVarArg)
3371     return false;
3372
3373   switch (CallingConv) {
3374   default:
3375     return false;
3376   case CallingConv::X86_StdCall:
3377     return !is64Bit;
3378   case CallingConv::X86_FastCall:
3379     return !is64Bit;
3380   case CallingConv::X86_ThisCall:
3381     return !is64Bit;
3382   case CallingConv::Fast:
3383     return TailCallOpt;
3384   case CallingConv::GHC:
3385     return TailCallOpt;
3386   case CallingConv::HiPE:
3387     return TailCallOpt;
3388   }
3389 }
3390
3391 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3392 /// specific condition code, returning the condition code and the LHS/RHS of the
3393 /// comparison to make.
3394 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3395                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3396   if (!isFP) {
3397     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3398       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3399         // X > -1   -> X == 0, jump !sign.
3400         RHS = DAG.getConstant(0, RHS.getValueType());
3401         return X86::COND_NS;
3402       }
3403       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3404         // X < 0   -> X == 0, jump on sign.
3405         return X86::COND_S;
3406       }
3407       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3408         // X < 1   -> X <= 0
3409         RHS = DAG.getConstant(0, RHS.getValueType());
3410         return X86::COND_LE;
3411       }
3412     }
3413
3414     switch (SetCCOpcode) {
3415     default: llvm_unreachable("Invalid integer condition!");
3416     case ISD::SETEQ:  return X86::COND_E;
3417     case ISD::SETGT:  return X86::COND_G;
3418     case ISD::SETGE:  return X86::COND_GE;
3419     case ISD::SETLT:  return X86::COND_L;
3420     case ISD::SETLE:  return X86::COND_LE;
3421     case ISD::SETNE:  return X86::COND_NE;
3422     case ISD::SETULT: return X86::COND_B;
3423     case ISD::SETUGT: return X86::COND_A;
3424     case ISD::SETULE: return X86::COND_BE;
3425     case ISD::SETUGE: return X86::COND_AE;
3426     }
3427   }
3428
3429   // First determine if it is required or is profitable to flip the operands.
3430
3431   // If LHS is a foldable load, but RHS is not, flip the condition.
3432   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3433       !ISD::isNON_EXTLoad(RHS.getNode())) {
3434     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3435     std::swap(LHS, RHS);
3436   }
3437
3438   switch (SetCCOpcode) {
3439   default: break;
3440   case ISD::SETOLT:
3441   case ISD::SETOLE:
3442   case ISD::SETUGT:
3443   case ISD::SETUGE:
3444     std::swap(LHS, RHS);
3445     break;
3446   }
3447
3448   // On a floating point condition, the flags are set as follows:
3449   // ZF  PF  CF   op
3450   //  0 | 0 | 0 | X > Y
3451   //  0 | 0 | 1 | X < Y
3452   //  1 | 0 | 0 | X == Y
3453   //  1 | 1 | 1 | unordered
3454   switch (SetCCOpcode) {
3455   default: llvm_unreachable("Condcode should be pre-legalized away");
3456   case ISD::SETUEQ:
3457   case ISD::SETEQ:   return X86::COND_E;
3458   case ISD::SETOLT:              // flipped
3459   case ISD::SETOGT:
3460   case ISD::SETGT:   return X86::COND_A;
3461   case ISD::SETOLE:              // flipped
3462   case ISD::SETOGE:
3463   case ISD::SETGE:   return X86::COND_AE;
3464   case ISD::SETUGT:              // flipped
3465   case ISD::SETULT:
3466   case ISD::SETLT:   return X86::COND_B;
3467   case ISD::SETUGE:              // flipped
3468   case ISD::SETULE:
3469   case ISD::SETLE:   return X86::COND_BE;
3470   case ISD::SETONE:
3471   case ISD::SETNE:   return X86::COND_NE;
3472   case ISD::SETUO:   return X86::COND_P;
3473   case ISD::SETO:    return X86::COND_NP;
3474   case ISD::SETOEQ:
3475   case ISD::SETUNE:  return X86::COND_INVALID;
3476   }
3477 }
3478
3479 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3480 /// code. Current x86 isa includes the following FP cmov instructions:
3481 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3482 static bool hasFPCMov(unsigned X86CC) {
3483   switch (X86CC) {
3484   default:
3485     return false;
3486   case X86::COND_B:
3487   case X86::COND_BE:
3488   case X86::COND_E:
3489   case X86::COND_P:
3490   case X86::COND_A:
3491   case X86::COND_AE:
3492   case X86::COND_NE:
3493   case X86::COND_NP:
3494     return true;
3495   }
3496 }
3497
3498 /// isFPImmLegal - Returns true if the target can instruction select the
3499 /// specified FP immediate natively. If false, the legalizer will
3500 /// materialize the FP immediate as a load from a constant pool.
3501 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3502   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3503     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3504       return true;
3505   }
3506   return false;
3507 }
3508
3509 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3510 /// the specified range (L, H].
3511 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3512   return (Val < 0) || (Val >= Low && Val < Hi);
3513 }
3514
3515 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3516 /// specified value.
3517 static bool isUndefOrEqual(int Val, int CmpVal) {
3518   return (Val < 0 || Val == CmpVal);
3519 }
3520
3521 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3522 /// from position Pos and ending in Pos+Size, falls within the specified
3523 /// sequential range (L, L+Pos]. or is undef.
3524 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3525                                        unsigned Pos, unsigned Size, int Low) {
3526   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3527     if (!isUndefOrEqual(Mask[i], Low))
3528       return false;
3529   return true;
3530 }
3531
3532 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3533 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3534 /// the second operand.
3535 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3536   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3537     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3538   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3539     return (Mask[0] < 2 && Mask[1] < 2);
3540   return false;
3541 }
3542
3543 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3544 /// is suitable for input to PSHUFHW.
3545 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3546   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3547     return false;
3548
3549   // Lower quadword copied in order or undef.
3550   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3551     return false;
3552
3553   // Upper quadword shuffled.
3554   for (unsigned i = 4; i != 8; ++i)
3555     if (!isUndefOrInRange(Mask[i], 4, 8))
3556       return false;
3557
3558   if (VT == MVT::v16i16) {
3559     // Lower quadword copied in order or undef.
3560     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3561       return false;
3562
3563     // Upper quadword shuffled.
3564     for (unsigned i = 12; i != 16; ++i)
3565       if (!isUndefOrInRange(Mask[i], 12, 16))
3566         return false;
3567   }
3568
3569   return true;
3570 }
3571
3572 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3573 /// is suitable for input to PSHUFLW.
3574 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3575   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3576     return false;
3577
3578   // Upper quadword copied in order.
3579   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3580     return false;
3581
3582   // Lower quadword shuffled.
3583   for (unsigned i = 0; i != 4; ++i)
3584     if (!isUndefOrInRange(Mask[i], 0, 4))
3585       return false;
3586
3587   if (VT == MVT::v16i16) {
3588     // Upper quadword copied in order.
3589     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3590       return false;
3591
3592     // Lower quadword shuffled.
3593     for (unsigned i = 8; i != 12; ++i)
3594       if (!isUndefOrInRange(Mask[i], 8, 12))
3595         return false;
3596   }
3597
3598   return true;
3599 }
3600
3601 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3602 /// is suitable for input to PALIGNR.
3603 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3604                           const X86Subtarget *Subtarget) {
3605   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3606       (VT.is256BitVector() && !Subtarget->hasInt256()))
3607     return false;
3608
3609   unsigned NumElts = VT.getVectorNumElements();
3610   unsigned NumLanes = VT.getSizeInBits()/128;
3611   unsigned NumLaneElts = NumElts/NumLanes;
3612
3613   // Do not handle 64-bit element shuffles with palignr.
3614   if (NumLaneElts == 2)
3615     return false;
3616
3617   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3618     unsigned i;
3619     for (i = 0; i != NumLaneElts; ++i) {
3620       if (Mask[i+l] >= 0)
3621         break;
3622     }
3623
3624     // Lane is all undef, go to next lane
3625     if (i == NumLaneElts)
3626       continue;
3627
3628     int Start = Mask[i+l];
3629
3630     // Make sure its in this lane in one of the sources
3631     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3632         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3633       return false;
3634
3635     // If not lane 0, then we must match lane 0
3636     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3637       return false;
3638
3639     // Correct second source to be contiguous with first source
3640     if (Start >= (int)NumElts)
3641       Start -= NumElts - NumLaneElts;
3642
3643     // Make sure we're shifting in the right direction.
3644     if (Start <= (int)(i+l))
3645       return false;
3646
3647     Start -= i;
3648
3649     // Check the rest of the elements to see if they are consecutive.
3650     for (++i; i != NumLaneElts; ++i) {
3651       int Idx = Mask[i+l];
3652
3653       // Make sure its in this lane
3654       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3655           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3656         return false;
3657
3658       // If not lane 0, then we must match lane 0
3659       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3660         return false;
3661
3662       if (Idx >= (int)NumElts)
3663         Idx -= NumElts - NumLaneElts;
3664
3665       if (!isUndefOrEqual(Idx, Start+i))
3666         return false;
3667
3668     }
3669   }
3670
3671   return true;
3672 }
3673
3674 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3675 /// the two vector operands have swapped position.
3676 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3677                                      unsigned NumElems) {
3678   for (unsigned i = 0; i != NumElems; ++i) {
3679     int idx = Mask[i];
3680     if (idx < 0)
3681       continue;
3682     else if (idx < (int)NumElems)
3683       Mask[i] = idx + NumElems;
3684     else
3685       Mask[i] = idx - NumElems;
3686   }
3687 }
3688
3689 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3690 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3691 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3692 /// reverse of what x86 shuffles want.
3693 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3694                         bool Commuted = false) {
3695   if (!HasFp256 && VT.is256BitVector())
3696     return false;
3697
3698   unsigned NumElems = VT.getVectorNumElements();
3699   unsigned NumLanes = VT.getSizeInBits()/128;
3700   unsigned NumLaneElems = NumElems/NumLanes;
3701
3702   if (NumLaneElems != 2 && NumLaneElems != 4)
3703     return false;
3704
3705   // VSHUFPSY divides the resulting vector into 4 chunks.
3706   // The sources are also splitted into 4 chunks, and each destination
3707   // chunk must come from a different source chunk.
3708   //
3709   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3710   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3711   //
3712   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3713   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3714   //
3715   // VSHUFPDY divides the resulting vector into 4 chunks.
3716   // The sources are also splitted into 4 chunks, and each destination
3717   // chunk must come from a different source chunk.
3718   //
3719   //  SRC1 =>      X3       X2       X1       X0
3720   //  SRC2 =>      Y3       Y2       Y1       Y0
3721   //
3722   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3723   //
3724   unsigned HalfLaneElems = NumLaneElems/2;
3725   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3726     for (unsigned i = 0; i != NumLaneElems; ++i) {
3727       int Idx = Mask[i+l];
3728       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3729       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3730         return false;
3731       // For VSHUFPSY, the mask of the second half must be the same as the
3732       // first but with the appropriate offsets. This works in the same way as
3733       // VPERMILPS works with masks.
3734       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3735         continue;
3736       if (!isUndefOrEqual(Idx, Mask[i]+l))
3737         return false;
3738     }
3739   }
3740
3741   return true;
3742 }
3743
3744 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3745 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3746 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3747   if (!VT.is128BitVector())
3748     return false;
3749
3750   unsigned NumElems = VT.getVectorNumElements();
3751
3752   if (NumElems != 4)
3753     return false;
3754
3755   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3756   return isUndefOrEqual(Mask[0], 6) &&
3757          isUndefOrEqual(Mask[1], 7) &&
3758          isUndefOrEqual(Mask[2], 2) &&
3759          isUndefOrEqual(Mask[3], 3);
3760 }
3761
3762 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3763 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3764 /// <2, 3, 2, 3>
3765 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3766   if (!VT.is128BitVector())
3767     return false;
3768
3769   unsigned NumElems = VT.getVectorNumElements();
3770
3771   if (NumElems != 4)
3772     return false;
3773
3774   return isUndefOrEqual(Mask[0], 2) &&
3775          isUndefOrEqual(Mask[1], 3) &&
3776          isUndefOrEqual(Mask[2], 2) &&
3777          isUndefOrEqual(Mask[3], 3);
3778 }
3779
3780 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3781 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3782 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3783   if (!VT.is128BitVector())
3784     return false;
3785
3786   unsigned NumElems = VT.getVectorNumElements();
3787
3788   if (NumElems != 2 && NumElems != 4)
3789     return false;
3790
3791   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3792     if (!isUndefOrEqual(Mask[i], i + NumElems))
3793       return false;
3794
3795   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3796     if (!isUndefOrEqual(Mask[i], i))
3797       return false;
3798
3799   return true;
3800 }
3801
3802 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3803 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3804 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3805   if (!VT.is128BitVector())
3806     return false;
3807
3808   unsigned NumElems = VT.getVectorNumElements();
3809
3810   if (NumElems != 2 && NumElems != 4)
3811     return false;
3812
3813   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3814     if (!isUndefOrEqual(Mask[i], i))
3815       return false;
3816
3817   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3818     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3819       return false;
3820
3821   return true;
3822 }
3823
3824 //
3825 // Some special combinations that can be optimized.
3826 //
3827 static
3828 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3829                                SelectionDAG &DAG) {
3830   MVT VT = SVOp->getValueType(0).getSimpleVT();
3831   SDLoc dl(SVOp);
3832
3833   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3834     return SDValue();
3835
3836   ArrayRef<int> Mask = SVOp->getMask();
3837
3838   // These are the special masks that may be optimized.
3839   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3840   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3841   bool MatchEvenMask = true;
3842   bool MatchOddMask  = true;
3843   for (int i=0; i<8; ++i) {
3844     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3845       MatchEvenMask = false;
3846     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3847       MatchOddMask = false;
3848   }
3849
3850   if (!MatchEvenMask && !MatchOddMask)
3851     return SDValue();
3852
3853   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3854
3855   SDValue Op0 = SVOp->getOperand(0);
3856   SDValue Op1 = SVOp->getOperand(1);
3857
3858   if (MatchEvenMask) {
3859     // Shift the second operand right to 32 bits.
3860     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3861     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3862   } else {
3863     // Shift the first operand left to 32 bits.
3864     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3865     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3866   }
3867   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3868   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3869 }
3870
3871 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3872 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3873 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3874                          bool HasInt256, bool V2IsSplat = false) {
3875   unsigned NumElts = VT.getVectorNumElements();
3876
3877   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3878          "Unsupported vector type for unpckh");
3879
3880   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3881       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3882     return false;
3883
3884   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3885   // independently on 128-bit lanes.
3886   unsigned NumLanes = VT.getSizeInBits()/128;
3887   unsigned NumLaneElts = NumElts/NumLanes;
3888
3889   for (unsigned l = 0; l != 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, EVT VT,
3911                          bool HasInt256, bool V2IsSplat = false) {
3912   unsigned NumElts = VT.getVectorNumElements();
3913
3914   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3915          "Unsupported vector type for unpckh");
3916
3917   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3918       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3919     return false;
3920
3921   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3922   // independently on 128-bit lanes.
3923   unsigned NumLanes = VT.getSizeInBits()/128;
3924   unsigned NumLaneElts = NumElts/NumLanes;
3925
3926   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3927     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
3928       int BitI  = Mask[l+i];
3929       int BitI1 = Mask[l+i+1];
3930       if (!isUndefOrEqual(BitI, j))
3931         return false;
3932       if (V2IsSplat) {
3933         if (isUndefOrEqual(BitI1, NumElts))
3934           return false;
3935       } else {
3936         if (!isUndefOrEqual(BitI1, j+NumElts))
3937           return false;
3938       }
3939     }
3940   }
3941   return true;
3942 }
3943
3944 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3945 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3946 /// <0, 0, 1, 1>
3947 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3948   unsigned NumElts = VT.getVectorNumElements();
3949   bool Is256BitVec = VT.is256BitVector();
3950
3951   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3952          "Unsupported vector type for unpckh");
3953
3954   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3955       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3956     return false;
3957
3958   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3959   // FIXME: Need a better way to get rid of this, there's no latency difference
3960   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3961   // the former later. We should also remove the "_undef" special mask.
3962   if (NumElts == 4 && Is256BitVec)
3963     return false;
3964
3965   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3966   // independently on 128-bit lanes.
3967   unsigned NumLanes = VT.getSizeInBits()/128;
3968   unsigned NumLaneElts = NumElts/NumLanes;
3969
3970   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
3971     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
3972       int BitI  = Mask[l+i];
3973       int BitI1 = Mask[l+i+1];
3974
3975       if (!isUndefOrEqual(BitI, j))
3976         return false;
3977       if (!isUndefOrEqual(BitI1, j))
3978         return false;
3979     }
3980   }
3981
3982   return true;
3983 }
3984
3985 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3986 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3987 /// <2, 2, 3, 3>
3988 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3989   unsigned NumElts = VT.getVectorNumElements();
3990
3991   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3992          "Unsupported vector type for unpckh");
3993
3994   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3995       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3996     return false;
3997
3998   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3999   // independently on 128-bit lanes.
4000   unsigned NumLanes = VT.getSizeInBits()/128;
4001   unsigned NumLaneElts = NumElts/NumLanes;
4002
4003   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4004     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4005       int BitI  = Mask[l+i];
4006       int BitI1 = Mask[l+i+1];
4007       if (!isUndefOrEqual(BitI, j))
4008         return false;
4009       if (!isUndefOrEqual(BitI1, j))
4010         return false;
4011     }
4012   }
4013   return true;
4014 }
4015
4016 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4017 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4018 /// MOVSD, and MOVD, i.e. setting the lowest element.
4019 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4020   if (VT.getVectorElementType().getSizeInBits() < 32)
4021     return false;
4022   if (!VT.is128BitVector())
4023     return false;
4024
4025   unsigned NumElts = VT.getVectorNumElements();
4026
4027   if (!isUndefOrEqual(Mask[0], NumElts))
4028     return false;
4029
4030   for (unsigned i = 1; i != NumElts; ++i)
4031     if (!isUndefOrEqual(Mask[i], i))
4032       return false;
4033
4034   return true;
4035 }
4036
4037 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4038 /// as permutations between 128-bit chunks or halves. As an example: this
4039 /// shuffle bellow:
4040 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4041 /// The first half comes from the second half of V1 and the second half from the
4042 /// the second half of V2.
4043 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4044   if (!HasFp256 || !VT.is256BitVector())
4045     return false;
4046
4047   // The shuffle result is divided into half A and half B. In total the two
4048   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4049   // B must come from C, D, E or F.
4050   unsigned HalfSize = VT.getVectorNumElements()/2;
4051   bool MatchA = false, MatchB = false;
4052
4053   // Check if A comes from one of C, D, E, F.
4054   for (unsigned Half = 0; Half != 4; ++Half) {
4055     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4056       MatchA = true;
4057       break;
4058     }
4059   }
4060
4061   // Check if B comes from one of C, D, E, F.
4062   for (unsigned Half = 0; Half != 4; ++Half) {
4063     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4064       MatchB = true;
4065       break;
4066     }
4067   }
4068
4069   return MatchA && MatchB;
4070 }
4071
4072 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4073 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4074 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4075   MVT VT = SVOp->getValueType(0).getSimpleVT();
4076
4077   unsigned HalfSize = VT.getVectorNumElements()/2;
4078
4079   unsigned FstHalf = 0, SndHalf = 0;
4080   for (unsigned i = 0; i < HalfSize; ++i) {
4081     if (SVOp->getMaskElt(i) > 0) {
4082       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4083       break;
4084     }
4085   }
4086   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4087     if (SVOp->getMaskElt(i) > 0) {
4088       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4089       break;
4090     }
4091   }
4092
4093   return (FstHalf | (SndHalf << 4));
4094 }
4095
4096 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4097 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4098 /// Note that VPERMIL mask matching is different depending whether theunderlying
4099 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4100 /// to the same elements of the low, but to the higher half of the source.
4101 /// In VPERMILPD the two lanes could be shuffled independently of each other
4102 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4103 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4104   if (!HasFp256)
4105     return false;
4106
4107   unsigned NumElts = VT.getVectorNumElements();
4108   // Only match 256-bit with 32/64-bit types
4109   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
4110     return false;
4111
4112   unsigned NumLanes = VT.getSizeInBits()/128;
4113   unsigned LaneSize = NumElts/NumLanes;
4114   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4115     for (unsigned i = 0; i != LaneSize; ++i) {
4116       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4117         return false;
4118       if (NumElts != 8 || l == 0)
4119         continue;
4120       // VPERMILPS handling
4121       if (Mask[i] < 0)
4122         continue;
4123       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
4124         return false;
4125     }
4126   }
4127
4128   return true;
4129 }
4130
4131 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4132 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4133 /// element of vector 2 and the other elements to come from vector 1 in order.
4134 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
4135                                bool V2IsSplat = false, bool V2IsUndef = false) {
4136   if (!VT.is128BitVector())
4137     return false;
4138
4139   unsigned NumOps = VT.getVectorNumElements();
4140   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4141     return false;
4142
4143   if (!isUndefOrEqual(Mask[0], 0))
4144     return false;
4145
4146   for (unsigned i = 1; i != NumOps; ++i)
4147     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4148           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4149           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4150       return false;
4151
4152   return true;
4153 }
4154
4155 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4156 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4157 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4158 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
4159                            const X86Subtarget *Subtarget) {
4160   if (!Subtarget->hasSSE3())
4161     return false;
4162
4163   unsigned NumElems = VT.getVectorNumElements();
4164
4165   if ((VT.is128BitVector() && NumElems != 4) ||
4166       (VT.is256BitVector() && NumElems != 8))
4167     return false;
4168
4169   // "i+1" is the value the indexed mask element must have
4170   for (unsigned i = 0; i != NumElems; i += 2)
4171     if (!isUndefOrEqual(Mask[i], i+1) ||
4172         !isUndefOrEqual(Mask[i+1], i+1))
4173       return false;
4174
4175   return true;
4176 }
4177
4178 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4179 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4180 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4181 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
4182                            const X86Subtarget *Subtarget) {
4183   if (!Subtarget->hasSSE3())
4184     return false;
4185
4186   unsigned NumElems = VT.getVectorNumElements();
4187
4188   if ((VT.is128BitVector() && NumElems != 4) ||
4189       (VT.is256BitVector() && NumElems != 8))
4190     return false;
4191
4192   // "i" is the value the indexed mask element must have
4193   for (unsigned i = 0; i != NumElems; i += 2)
4194     if (!isUndefOrEqual(Mask[i], i) ||
4195         !isUndefOrEqual(Mask[i+1], i))
4196       return false;
4197
4198   return true;
4199 }
4200
4201 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4202 /// specifies a shuffle of elements that is suitable for input to 256-bit
4203 /// version of MOVDDUP.
4204 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4205   if (!HasFp256 || !VT.is256BitVector())
4206     return false;
4207
4208   unsigned NumElts = VT.getVectorNumElements();
4209   if (NumElts != 4)
4210     return false;
4211
4212   for (unsigned i = 0; i != NumElts/2; ++i)
4213     if (!isUndefOrEqual(Mask[i], 0))
4214       return false;
4215   for (unsigned i = NumElts/2; i != NumElts; ++i)
4216     if (!isUndefOrEqual(Mask[i], NumElts/2))
4217       return false;
4218   return true;
4219 }
4220
4221 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4222 /// specifies a shuffle of elements that is suitable for input to 128-bit
4223 /// version of MOVDDUP.
4224 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4225   if (!VT.is128BitVector())
4226     return false;
4227
4228   unsigned e = VT.getVectorNumElements() / 2;
4229   for (unsigned i = 0; i != e; ++i)
4230     if (!isUndefOrEqual(Mask[i], i))
4231       return false;
4232   for (unsigned i = 0; i != e; ++i)
4233     if (!isUndefOrEqual(Mask[e+i], i))
4234       return false;
4235   return true;
4236 }
4237
4238 /// isVEXTRACTIndex - Return true if the specified
4239 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4240 /// suitable for instruction that extract 128 or 256 bit vectors
4241 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4242   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4243   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4244     return false;
4245
4246   // The index should be aligned on a vecWidth-bit boundary.
4247   uint64_t Index =
4248     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4249
4250   MVT VT = N->getValueType(0).getSimpleVT();
4251   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4252   bool Result = (Index * ElSize) % vecWidth == 0;
4253
4254   return Result;
4255 }
4256
4257 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4258 /// operand specifies a subvector insert that is suitable for input to
4259 /// insertion of 128 or 256-bit subvectors
4260 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4261   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4262   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4263     return false;
4264   // The index should be aligned on a vecWidth-bit boundary.
4265   uint64_t Index =
4266     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4267
4268   MVT VT = N->getValueType(0).getSimpleVT();
4269   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4270   bool Result = (Index * ElSize) % vecWidth == 0;
4271
4272   return Result;
4273 }
4274
4275 bool X86::isVINSERT128Index(SDNode *N) {
4276   return isVINSERTIndex(N, 128);
4277 }
4278
4279 bool X86::isVINSERT256Index(SDNode *N) {
4280   return isVINSERTIndex(N, 256);
4281 }
4282
4283 bool X86::isVEXTRACT128Index(SDNode *N) {
4284   return isVEXTRACTIndex(N, 128);
4285 }
4286
4287 bool X86::isVEXTRACT256Index(SDNode *N) {
4288   return isVEXTRACTIndex(N, 256);
4289 }
4290
4291 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4292 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4293 /// Handles 128-bit and 256-bit.
4294 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4295   MVT VT = N->getValueType(0).getSimpleVT();
4296
4297   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4298          "Unsupported vector type for PSHUF/SHUFP");
4299
4300   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4301   // independently on 128-bit lanes.
4302   unsigned NumElts = VT.getVectorNumElements();
4303   unsigned NumLanes = VT.getSizeInBits()/128;
4304   unsigned NumLaneElts = NumElts/NumLanes;
4305
4306   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4307          "Only supports 2 or 4 elements per lane");
4308
4309   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4310   unsigned Mask = 0;
4311   for (unsigned i = 0; i != NumElts; ++i) {
4312     int Elt = N->getMaskElt(i);
4313     if (Elt < 0) continue;
4314     Elt &= NumLaneElts - 1;
4315     unsigned ShAmt = (i << Shift) % 8;
4316     Mask |= Elt << ShAmt;
4317   }
4318
4319   return Mask;
4320 }
4321
4322 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4323 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4324 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4325   MVT VT = N->getValueType(0).getSimpleVT();
4326
4327   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4328          "Unsupported vector type for PSHUFHW");
4329
4330   unsigned NumElts = VT.getVectorNumElements();
4331
4332   unsigned Mask = 0;
4333   for (unsigned l = 0; l != NumElts; l += 8) {
4334     // 8 nodes per lane, but we only care about the last 4.
4335     for (unsigned i = 0; i < 4; ++i) {
4336       int Elt = N->getMaskElt(l+i+4);
4337       if (Elt < 0) continue;
4338       Elt &= 0x3; // only 2-bits.
4339       Mask |= Elt << (i * 2);
4340     }
4341   }
4342
4343   return Mask;
4344 }
4345
4346 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4347 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4348 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4349   MVT VT = N->getValueType(0).getSimpleVT();
4350
4351   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4352          "Unsupported vector type for PSHUFHW");
4353
4354   unsigned NumElts = VT.getVectorNumElements();
4355
4356   unsigned Mask = 0;
4357   for (unsigned l = 0; l != NumElts; l += 8) {
4358     // 8 nodes per lane, but we only care about the first 4.
4359     for (unsigned i = 0; i < 4; ++i) {
4360       int Elt = N->getMaskElt(l+i);
4361       if (Elt < 0) continue;
4362       Elt &= 0x3; // only 2-bits
4363       Mask |= Elt << (i * 2);
4364     }
4365   }
4366
4367   return Mask;
4368 }
4369
4370 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4371 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4372 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4373   MVT VT = SVOp->getValueType(0).getSimpleVT();
4374   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4375
4376   unsigned NumElts = VT.getVectorNumElements();
4377   unsigned NumLanes = VT.getSizeInBits()/128;
4378   unsigned NumLaneElts = NumElts/NumLanes;
4379
4380   int Val = 0;
4381   unsigned i;
4382   for (i = 0; i != NumElts; ++i) {
4383     Val = SVOp->getMaskElt(i);
4384     if (Val >= 0)
4385       break;
4386   }
4387   if (Val >= (int)NumElts)
4388     Val -= NumElts - NumLaneElts;
4389
4390   assert(Val - i > 0 && "PALIGNR imm should be positive");
4391   return (Val - i) * EltSize;
4392 }
4393
4394 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4395   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4396   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4397     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4398
4399   uint64_t Index =
4400     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4401
4402   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4403   MVT ElVT = VecVT.getVectorElementType();
4404
4405   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4406   return Index / NumElemsPerChunk;
4407 }
4408
4409 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4410   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4411   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4412     llvm_unreachable("Illegal insert subvector for VINSERT");
4413
4414   uint64_t Index =
4415     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4416
4417   MVT VecVT = N->getValueType(0).getSimpleVT();
4418   MVT ElVT = VecVT.getVectorElementType();
4419
4420   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4421   return Index / NumElemsPerChunk;
4422 }
4423
4424 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4425 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4426 /// and VINSERTI128 instructions.
4427 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4428   return getExtractVEXTRACTImmediate(N, 128);
4429 }
4430
4431 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4432 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4433 /// and VINSERTI64x4 instructions.
4434 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4435   return getExtractVEXTRACTImmediate(N, 256);
4436 }
4437
4438 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4439 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4440 /// and VINSERTI128 instructions.
4441 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4442   return getInsertVINSERTImmediate(N, 128);
4443 }
4444
4445 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4446 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4447 /// and VINSERTI64x4 instructions.
4448 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4449   return getInsertVINSERTImmediate(N, 256);
4450 }
4451
4452 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4453 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4454 /// Handles 256-bit.
4455 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4456   MVT VT = N->getValueType(0).getSimpleVT();
4457
4458   unsigned NumElts = VT.getVectorNumElements();
4459
4460   assert((VT.is256BitVector() && NumElts == 4) &&
4461          "Unsupported vector type for VPERMQ/VPERMPD");
4462
4463   unsigned Mask = 0;
4464   for (unsigned i = 0; i != NumElts; ++i) {
4465     int Elt = N->getMaskElt(i);
4466     if (Elt < 0)
4467       continue;
4468     Mask |= Elt << (i*2);
4469   }
4470
4471   return Mask;
4472 }
4473 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4474 /// constant +0.0.
4475 bool X86::isZeroNode(SDValue Elt) {
4476   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4477     return CN->isNullValue();
4478   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4479     return CFP->getValueAPF().isPosZero();
4480   return false;
4481 }
4482
4483 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4484 /// their permute mask.
4485 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4486                                     SelectionDAG &DAG) {
4487   MVT VT = SVOp->getValueType(0).getSimpleVT();
4488   unsigned NumElems = VT.getVectorNumElements();
4489   SmallVector<int, 8> MaskVec;
4490
4491   for (unsigned i = 0; i != NumElems; ++i) {
4492     int Idx = SVOp->getMaskElt(i);
4493     if (Idx >= 0) {
4494       if (Idx < (int)NumElems)
4495         Idx += NumElems;
4496       else
4497         Idx -= NumElems;
4498     }
4499     MaskVec.push_back(Idx);
4500   }
4501   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4502                               SVOp->getOperand(0), &MaskVec[0]);
4503 }
4504
4505 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4506 /// match movhlps. The lower half elements should come from upper half of
4507 /// V1 (and in order), and the upper half elements should come from the upper
4508 /// half of V2 (and in order).
4509 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4510   if (!VT.is128BitVector())
4511     return false;
4512   if (VT.getVectorNumElements() != 4)
4513     return false;
4514   for (unsigned i = 0, e = 2; i != e; ++i)
4515     if (!isUndefOrEqual(Mask[i], i+2))
4516       return false;
4517   for (unsigned i = 2; i != 4; ++i)
4518     if (!isUndefOrEqual(Mask[i], i+4))
4519       return false;
4520   return true;
4521 }
4522
4523 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4524 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4525 /// required.
4526 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4527   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4528     return false;
4529   N = N->getOperand(0).getNode();
4530   if (!ISD::isNON_EXTLoad(N))
4531     return false;
4532   if (LD)
4533     *LD = cast<LoadSDNode>(N);
4534   return true;
4535 }
4536
4537 // Test whether the given value is a vector value which will be legalized
4538 // into a load.
4539 static bool WillBeConstantPoolLoad(SDNode *N) {
4540   if (N->getOpcode() != ISD::BUILD_VECTOR)
4541     return false;
4542
4543   // Check for any non-constant elements.
4544   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4545     switch (N->getOperand(i).getNode()->getOpcode()) {
4546     case ISD::UNDEF:
4547     case ISD::ConstantFP:
4548     case ISD::Constant:
4549       break;
4550     default:
4551       return false;
4552     }
4553
4554   // Vectors of all-zeros and all-ones are materialized with special
4555   // instructions rather than being loaded.
4556   return !ISD::isBuildVectorAllZeros(N) &&
4557          !ISD::isBuildVectorAllOnes(N);
4558 }
4559
4560 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4561 /// match movlp{s|d}. The lower half elements should come from lower half of
4562 /// V1 (and in order), and the upper half elements should come from the upper
4563 /// half of V2 (and in order). And since V1 will become the source of the
4564 /// MOVLP, it must be either a vector load or a scalar load to vector.
4565 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4566                                ArrayRef<int> Mask, EVT VT) {
4567   if (!VT.is128BitVector())
4568     return false;
4569
4570   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4571     return false;
4572   // Is V2 is a vector load, don't do this transformation. We will try to use
4573   // load folding shufps op.
4574   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4575     return false;
4576
4577   unsigned NumElems = VT.getVectorNumElements();
4578
4579   if (NumElems != 2 && NumElems != 4)
4580     return false;
4581   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4582     if (!isUndefOrEqual(Mask[i], i))
4583       return false;
4584   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4585     if (!isUndefOrEqual(Mask[i], i+NumElems))
4586       return false;
4587   return true;
4588 }
4589
4590 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4591 /// all the same.
4592 static bool isSplatVector(SDNode *N) {
4593   if (N->getOpcode() != ISD::BUILD_VECTOR)
4594     return false;
4595
4596   SDValue SplatValue = N->getOperand(0);
4597   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4598     if (N->getOperand(i) != SplatValue)
4599       return false;
4600   return true;
4601 }
4602
4603 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4604 /// to an zero vector.
4605 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4606 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4607   SDValue V1 = N->getOperand(0);
4608   SDValue V2 = N->getOperand(1);
4609   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4610   for (unsigned i = 0; i != NumElems; ++i) {
4611     int Idx = N->getMaskElt(i);
4612     if (Idx >= (int)NumElems) {
4613       unsigned Opc = V2.getOpcode();
4614       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4615         continue;
4616       if (Opc != ISD::BUILD_VECTOR ||
4617           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4618         return false;
4619     } else if (Idx >= 0) {
4620       unsigned Opc = V1.getOpcode();
4621       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4622         continue;
4623       if (Opc != ISD::BUILD_VECTOR ||
4624           !X86::isZeroNode(V1.getOperand(Idx)))
4625         return false;
4626     }
4627   }
4628   return true;
4629 }
4630
4631 /// getZeroVector - Returns a vector of specified type with all zero elements.
4632 ///
4633 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4634                              SelectionDAG &DAG, SDLoc dl) {
4635   assert(VT.isVector() && "Expected a vector type");
4636
4637   // Always build SSE zero vectors as <4 x i32> bitcasted
4638   // to their dest type. This ensures they get CSE'd.
4639   SDValue Vec;
4640   if (VT.is128BitVector()) {  // SSE
4641     if (Subtarget->hasSSE2()) {  // SSE2
4642       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4643       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4644     } else { // SSE1
4645       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4646       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4647     }
4648   } else if (VT.is256BitVector()) { // AVX
4649     if (Subtarget->hasInt256()) { // AVX2
4650       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4651       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4652       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4653                         array_lengthof(Ops));
4654     } else {
4655       // 256-bit logic and arithmetic instructions in AVX are all
4656       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4657       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4658       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4659       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4660                         array_lengthof(Ops));
4661     }
4662   } else
4663     llvm_unreachable("Unexpected vector type");
4664
4665   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4666 }
4667
4668 /// getOnesVector - Returns a vector of specified type with all bits set.
4669 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4670 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4671 /// Then bitcast to their original type, ensuring they get CSE'd.
4672 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4673                              SDLoc dl) {
4674   assert(VT.isVector() && "Expected a vector type");
4675
4676   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4677   SDValue Vec;
4678   if (VT.is256BitVector()) {
4679     if (HasInt256) { // AVX2
4680       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4681       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4682                         array_lengthof(Ops));
4683     } else { // AVX
4684       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4685       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4686     }
4687   } else if (VT.is128BitVector()) {
4688     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4689   } else
4690     llvm_unreachable("Unexpected vector type");
4691
4692   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4693 }
4694
4695 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4696 /// that point to V2 points to its first element.
4697 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4698   for (unsigned i = 0; i != NumElems; ++i) {
4699     if (Mask[i] > (int)NumElems) {
4700       Mask[i] = NumElems;
4701     }
4702   }
4703 }
4704
4705 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4706 /// operation of specified width.
4707 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4708                        SDValue V2) {
4709   unsigned NumElems = VT.getVectorNumElements();
4710   SmallVector<int, 8> Mask;
4711   Mask.push_back(NumElems);
4712   for (unsigned i = 1; i != NumElems; ++i)
4713     Mask.push_back(i);
4714   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4715 }
4716
4717 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4718 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4719                           SDValue V2) {
4720   unsigned NumElems = VT.getVectorNumElements();
4721   SmallVector<int, 8> Mask;
4722   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4723     Mask.push_back(i);
4724     Mask.push_back(i + NumElems);
4725   }
4726   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4727 }
4728
4729 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4730 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4731                           SDValue V2) {
4732   unsigned NumElems = VT.getVectorNumElements();
4733   SmallVector<int, 8> Mask;
4734   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4735     Mask.push_back(i + Half);
4736     Mask.push_back(i + NumElems + Half);
4737   }
4738   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4739 }
4740
4741 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4742 // a generic shuffle instruction because the target has no such instructions.
4743 // Generate shuffles which repeat i16 and i8 several times until they can be
4744 // represented by v4f32 and then be manipulated by target suported shuffles.
4745 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4746   EVT VT = V.getValueType();
4747   int NumElems = VT.getVectorNumElements();
4748   SDLoc dl(V);
4749
4750   while (NumElems > 4) {
4751     if (EltNo < NumElems/2) {
4752       V = getUnpackl(DAG, dl, VT, V, V);
4753     } else {
4754       V = getUnpackh(DAG, dl, VT, V, V);
4755       EltNo -= NumElems/2;
4756     }
4757     NumElems >>= 1;
4758   }
4759   return V;
4760 }
4761
4762 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4763 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4764   EVT VT = V.getValueType();
4765   SDLoc dl(V);
4766
4767   if (VT.is128BitVector()) {
4768     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4769     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4770     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4771                              &SplatMask[0]);
4772   } else if (VT.is256BitVector()) {
4773     // To use VPERMILPS to splat scalars, the second half of indicies must
4774     // refer to the higher part, which is a duplication of the lower one,
4775     // because VPERMILPS can only handle in-lane permutations.
4776     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4777                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4778
4779     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4780     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4781                              &SplatMask[0]);
4782   } else
4783     llvm_unreachable("Vector size not supported");
4784
4785   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4786 }
4787
4788 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4789 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4790   EVT SrcVT = SV->getValueType(0);
4791   SDValue V1 = SV->getOperand(0);
4792   SDLoc dl(SV);
4793
4794   int EltNo = SV->getSplatIndex();
4795   int NumElems = SrcVT.getVectorNumElements();
4796   bool Is256BitVec = SrcVT.is256BitVector();
4797
4798   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4799          "Unknown how to promote splat for type");
4800
4801   // Extract the 128-bit part containing the splat element and update
4802   // the splat element index when it refers to the higher register.
4803   if (Is256BitVec) {
4804     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4805     if (EltNo >= NumElems/2)
4806       EltNo -= NumElems/2;
4807   }
4808
4809   // All i16 and i8 vector types can't be used directly by a generic shuffle
4810   // instruction because the target has no such instruction. Generate shuffles
4811   // which repeat i16 and i8 several times until they fit in i32, and then can
4812   // be manipulated by target suported shuffles.
4813   EVT EltVT = SrcVT.getVectorElementType();
4814   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4815     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4816
4817   // Recreate the 256-bit vector and place the same 128-bit vector
4818   // into the low and high part. This is necessary because we want
4819   // to use VPERM* to shuffle the vectors
4820   if (Is256BitVec) {
4821     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4822   }
4823
4824   return getLegalSplat(DAG, V1, EltNo);
4825 }
4826
4827 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4828 /// vector of zero or undef vector.  This produces a shuffle where the low
4829 /// element of V2 is swizzled into the zero/undef vector, landing at element
4830 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4831 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4832                                            bool IsZero,
4833                                            const X86Subtarget *Subtarget,
4834                                            SelectionDAG &DAG) {
4835   EVT VT = V2.getValueType();
4836   SDValue V1 = IsZero
4837     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4838   unsigned NumElems = VT.getVectorNumElements();
4839   SmallVector<int, 16> MaskVec;
4840   for (unsigned i = 0; i != NumElems; ++i)
4841     // If this is the insertion idx, put the low elt of V2 here.
4842     MaskVec.push_back(i == Idx ? NumElems : i);
4843   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4844 }
4845
4846 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4847 /// target specific opcode. Returns true if the Mask could be calculated.
4848 /// Sets IsUnary to true if only uses one source.
4849 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4850                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4851   unsigned NumElems = VT.getVectorNumElements();
4852   SDValue ImmN;
4853
4854   IsUnary = false;
4855   switch(N->getOpcode()) {
4856   case X86ISD::SHUFP:
4857     ImmN = N->getOperand(N->getNumOperands()-1);
4858     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4859     break;
4860   case X86ISD::UNPCKH:
4861     DecodeUNPCKHMask(VT, Mask);
4862     break;
4863   case X86ISD::UNPCKL:
4864     DecodeUNPCKLMask(VT, Mask);
4865     break;
4866   case X86ISD::MOVHLPS:
4867     DecodeMOVHLPSMask(NumElems, Mask);
4868     break;
4869   case X86ISD::MOVLHPS:
4870     DecodeMOVLHPSMask(NumElems, Mask);
4871     break;
4872   case X86ISD::PALIGNR:
4873     ImmN = N->getOperand(N->getNumOperands()-1);
4874     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4875     break;
4876   case X86ISD::PSHUFD:
4877   case X86ISD::VPERMILP:
4878     ImmN = N->getOperand(N->getNumOperands()-1);
4879     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4880     IsUnary = true;
4881     break;
4882   case X86ISD::PSHUFHW:
4883     ImmN = N->getOperand(N->getNumOperands()-1);
4884     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4885     IsUnary = true;
4886     break;
4887   case X86ISD::PSHUFLW:
4888     ImmN = N->getOperand(N->getNumOperands()-1);
4889     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4890     IsUnary = true;
4891     break;
4892   case X86ISD::VPERMI:
4893     ImmN = N->getOperand(N->getNumOperands()-1);
4894     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4895     IsUnary = true;
4896     break;
4897   case X86ISD::MOVSS:
4898   case X86ISD::MOVSD: {
4899     // The index 0 always comes from the first element of the second source,
4900     // this is why MOVSS and MOVSD are used in the first place. The other
4901     // elements come from the other positions of the first source vector
4902     Mask.push_back(NumElems);
4903     for (unsigned i = 1; i != NumElems; ++i) {
4904       Mask.push_back(i);
4905     }
4906     break;
4907   }
4908   case X86ISD::VPERM2X128:
4909     ImmN = N->getOperand(N->getNumOperands()-1);
4910     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4911     if (Mask.empty()) return false;
4912     break;
4913   case X86ISD::MOVDDUP:
4914   case X86ISD::MOVLHPD:
4915   case X86ISD::MOVLPD:
4916   case X86ISD::MOVLPS:
4917   case X86ISD::MOVSHDUP:
4918   case X86ISD::MOVSLDUP:
4919     // Not yet implemented
4920     return false;
4921   default: llvm_unreachable("unknown target shuffle node");
4922   }
4923
4924   return true;
4925 }
4926
4927 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4928 /// element of the result of the vector shuffle.
4929 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4930                                    unsigned Depth) {
4931   if (Depth == 6)
4932     return SDValue();  // Limit search depth.
4933
4934   SDValue V = SDValue(N, 0);
4935   EVT VT = V.getValueType();
4936   unsigned Opcode = V.getOpcode();
4937
4938   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4939   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4940     int Elt = SV->getMaskElt(Index);
4941
4942     if (Elt < 0)
4943       return DAG.getUNDEF(VT.getVectorElementType());
4944
4945     unsigned NumElems = VT.getVectorNumElements();
4946     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4947                                          : SV->getOperand(1);
4948     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4949   }
4950
4951   // Recurse into target specific vector shuffles to find scalars.
4952   if (isTargetShuffle(Opcode)) {
4953     MVT ShufVT = V.getValueType().getSimpleVT();
4954     unsigned NumElems = ShufVT.getVectorNumElements();
4955     SmallVector<int, 16> ShuffleMask;
4956     bool IsUnary;
4957
4958     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4959       return SDValue();
4960
4961     int Elt = ShuffleMask[Index];
4962     if (Elt < 0)
4963       return DAG.getUNDEF(ShufVT.getVectorElementType());
4964
4965     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4966                                          : N->getOperand(1);
4967     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4968                                Depth+1);
4969   }
4970
4971   // Actual nodes that may contain scalar elements
4972   if (Opcode == ISD::BITCAST) {
4973     V = V.getOperand(0);
4974     EVT SrcVT = V.getValueType();
4975     unsigned NumElems = VT.getVectorNumElements();
4976
4977     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4978       return SDValue();
4979   }
4980
4981   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4982     return (Index == 0) ? V.getOperand(0)
4983                         : DAG.getUNDEF(VT.getVectorElementType());
4984
4985   if (V.getOpcode() == ISD::BUILD_VECTOR)
4986     return V.getOperand(Index);
4987
4988   return SDValue();
4989 }
4990
4991 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4992 /// shuffle operation which come from a consecutively from a zero. The
4993 /// search can start in two different directions, from left or right.
4994 /// We count undefs as zeros until PreferredNum is reached.
4995 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
4996                                          unsigned NumElems, bool ZerosFromLeft,
4997                                          SelectionDAG &DAG,
4998                                          unsigned PreferredNum = -1U) {
4999   unsigned NumZeros = 0;
5000   for (unsigned i = 0; i != NumElems; ++i) {
5001     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5002     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5003     if (!Elt.getNode())
5004       break;
5005
5006     if (X86::isZeroNode(Elt))
5007       ++NumZeros;
5008     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5009       NumZeros = std::min(NumZeros + 1, PreferredNum);
5010     else
5011       break;
5012   }
5013
5014   return NumZeros;
5015 }
5016
5017 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5018 /// correspond consecutively to elements from one of the vector operands,
5019 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5020 static
5021 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5022                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5023                               unsigned NumElems, unsigned &OpNum) {
5024   bool SeenV1 = false;
5025   bool SeenV2 = false;
5026
5027   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5028     int Idx = SVOp->getMaskElt(i);
5029     // Ignore undef indicies
5030     if (Idx < 0)
5031       continue;
5032
5033     if (Idx < (int)NumElems)
5034       SeenV1 = true;
5035     else
5036       SeenV2 = true;
5037
5038     // Only accept consecutive elements from the same vector
5039     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5040       return false;
5041   }
5042
5043   OpNum = SeenV1 ? 0 : 1;
5044   return true;
5045 }
5046
5047 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5048 /// logical left shift of a vector.
5049 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5050                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5051   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5052   unsigned NumZeros = getNumOfConsecutiveZeros(
5053       SVOp, NumElems, false /* check zeros from right */, DAG,
5054       SVOp->getMaskElt(0));
5055   unsigned OpSrc;
5056
5057   if (!NumZeros)
5058     return false;
5059
5060   // Considering the elements in the mask that are not consecutive zeros,
5061   // check if they consecutively come from only one of the source vectors.
5062   //
5063   //               V1 = {X, A, B, C}     0
5064   //                         \  \  \    /
5065   //   vector_shuffle V1, V2 <1, 2, 3, X>
5066   //
5067   if (!isShuffleMaskConsecutive(SVOp,
5068             0,                   // Mask Start Index
5069             NumElems-NumZeros,   // Mask End Index(exclusive)
5070             NumZeros,            // Where to start looking in the src vector
5071             NumElems,            // Number of elements in vector
5072             OpSrc))              // Which source operand ?
5073     return false;
5074
5075   isLeft = false;
5076   ShAmt = NumZeros;
5077   ShVal = SVOp->getOperand(OpSrc);
5078   return true;
5079 }
5080
5081 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5082 /// logical left shift of a vector.
5083 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5084                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5085   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
5086   unsigned NumZeros = getNumOfConsecutiveZeros(
5087       SVOp, NumElems, true /* check zeros from left */, DAG,
5088       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5089   unsigned OpSrc;
5090
5091   if (!NumZeros)
5092     return false;
5093
5094   // Considering the elements in the mask that are not consecutive zeros,
5095   // check if they consecutively come from only one of the source vectors.
5096   //
5097   //                           0    { A, B, X, X } = V2
5098   //                          / \    /  /
5099   //   vector_shuffle V1, V2 <X, X, 4, 5>
5100   //
5101   if (!isShuffleMaskConsecutive(SVOp,
5102             NumZeros,     // Mask Start Index
5103             NumElems,     // Mask End Index(exclusive)
5104             0,            // Where to start looking in the src vector
5105             NumElems,     // Number of elements in vector
5106             OpSrc))       // Which source operand ?
5107     return false;
5108
5109   isLeft = true;
5110   ShAmt = NumZeros;
5111   ShVal = SVOp->getOperand(OpSrc);
5112   return true;
5113 }
5114
5115 /// isVectorShift - Returns true if the shuffle can be implemented as a
5116 /// logical left or right shift of a vector.
5117 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5118                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5119   // Although the logic below support any bitwidth size, there are no
5120   // shift instructions which handle more than 128-bit vectors.
5121   if (!SVOp->getValueType(0).is128BitVector())
5122     return false;
5123
5124   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5125       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5126     return true;
5127
5128   return false;
5129 }
5130
5131 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5132 ///
5133 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5134                                        unsigned NumNonZero, unsigned NumZero,
5135                                        SelectionDAG &DAG,
5136                                        const X86Subtarget* Subtarget,
5137                                        const TargetLowering &TLI) {
5138   if (NumNonZero > 8)
5139     return SDValue();
5140
5141   SDLoc dl(Op);
5142   SDValue V(0, 0);
5143   bool First = true;
5144   for (unsigned i = 0; i < 16; ++i) {
5145     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5146     if (ThisIsNonZero && First) {
5147       if (NumZero)
5148         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5149       else
5150         V = DAG.getUNDEF(MVT::v8i16);
5151       First = false;
5152     }
5153
5154     if ((i & 1) != 0) {
5155       SDValue ThisElt(0, 0), LastElt(0, 0);
5156       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5157       if (LastIsNonZero) {
5158         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5159                               MVT::i16, Op.getOperand(i-1));
5160       }
5161       if (ThisIsNonZero) {
5162         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5163         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5164                               ThisElt, DAG.getConstant(8, MVT::i8));
5165         if (LastIsNonZero)
5166           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5167       } else
5168         ThisElt = LastElt;
5169
5170       if (ThisElt.getNode())
5171         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5172                         DAG.getIntPtrConstant(i/2));
5173     }
5174   }
5175
5176   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5177 }
5178
5179 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5180 ///
5181 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5182                                      unsigned NumNonZero, unsigned NumZero,
5183                                      SelectionDAG &DAG,
5184                                      const X86Subtarget* Subtarget,
5185                                      const TargetLowering &TLI) {
5186   if (NumNonZero > 4)
5187     return SDValue();
5188
5189   SDLoc dl(Op);
5190   SDValue V(0, 0);
5191   bool First = true;
5192   for (unsigned i = 0; i < 8; ++i) {
5193     bool isNonZero = (NonZeros & (1 << i)) != 0;
5194     if (isNonZero) {
5195       if (First) {
5196         if (NumZero)
5197           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5198         else
5199           V = DAG.getUNDEF(MVT::v8i16);
5200         First = false;
5201       }
5202       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5203                       MVT::v8i16, V, Op.getOperand(i),
5204                       DAG.getIntPtrConstant(i));
5205     }
5206   }
5207
5208   return V;
5209 }
5210
5211 /// getVShift - Return a vector logical shift node.
5212 ///
5213 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5214                          unsigned NumBits, SelectionDAG &DAG,
5215                          const TargetLowering &TLI, SDLoc dl) {
5216   assert(VT.is128BitVector() && "Unknown type for VShift");
5217   EVT ShVT = MVT::v2i64;
5218   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5219   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5220   return DAG.getNode(ISD::BITCAST, dl, VT,
5221                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5222                              DAG.getConstant(NumBits,
5223                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5224 }
5225
5226 SDValue
5227 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5228                                           SelectionDAG &DAG) const {
5229
5230   // Check if the scalar load can be widened into a vector load. And if
5231   // the address is "base + cst" see if the cst can be "absorbed" into
5232   // the shuffle mask.
5233   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5234     SDValue Ptr = LD->getBasePtr();
5235     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5236       return SDValue();
5237     EVT PVT = LD->getValueType(0);
5238     if (PVT != MVT::i32 && PVT != MVT::f32)
5239       return SDValue();
5240
5241     int FI = -1;
5242     int64_t Offset = 0;
5243     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5244       FI = FINode->getIndex();
5245       Offset = 0;
5246     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5247                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5248       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5249       Offset = Ptr.getConstantOperandVal(1);
5250       Ptr = Ptr.getOperand(0);
5251     } else {
5252       return SDValue();
5253     }
5254
5255     // FIXME: 256-bit vector instructions don't require a strict alignment,
5256     // improve this code to support it better.
5257     unsigned RequiredAlign = VT.getSizeInBits()/8;
5258     SDValue Chain = LD->getChain();
5259     // Make sure the stack object alignment is at least 16 or 32.
5260     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5261     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5262       if (MFI->isFixedObjectIndex(FI)) {
5263         // Can't change the alignment. FIXME: It's possible to compute
5264         // the exact stack offset and reference FI + adjust offset instead.
5265         // If someone *really* cares about this. That's the way to implement it.
5266         return SDValue();
5267       } else {
5268         MFI->setObjectAlignment(FI, RequiredAlign);
5269       }
5270     }
5271
5272     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5273     // Ptr + (Offset & ~15).
5274     if (Offset < 0)
5275       return SDValue();
5276     if ((Offset % RequiredAlign) & 3)
5277       return SDValue();
5278     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5279     if (StartOffset)
5280       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5281                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5282
5283     int EltNo = (Offset - StartOffset) >> 2;
5284     unsigned NumElems = VT.getVectorNumElements();
5285
5286     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5287     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5288                              LD->getPointerInfo().getWithOffset(StartOffset),
5289                              false, false, false, 0);
5290
5291     SmallVector<int, 8> Mask;
5292     for (unsigned i = 0; i != NumElems; ++i)
5293       Mask.push_back(EltNo);
5294
5295     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5296   }
5297
5298   return SDValue();
5299 }
5300
5301 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5302 /// vector of type 'VT', see if the elements can be replaced by a single large
5303 /// load which has the same value as a build_vector whose operands are 'elts'.
5304 ///
5305 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5306 ///
5307 /// FIXME: we'd also like to handle the case where the last elements are zero
5308 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5309 /// There's even a handy isZeroNode for that purpose.
5310 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5311                                         SDLoc &DL, SelectionDAG &DAG) {
5312   EVT EltVT = VT.getVectorElementType();
5313   unsigned NumElems = Elts.size();
5314
5315   LoadSDNode *LDBase = NULL;
5316   unsigned LastLoadedElt = -1U;
5317
5318   // For each element in the initializer, see if we've found a load or an undef.
5319   // If we don't find an initial load element, or later load elements are
5320   // non-consecutive, bail out.
5321   for (unsigned i = 0; i < NumElems; ++i) {
5322     SDValue Elt = Elts[i];
5323
5324     if (!Elt.getNode() ||
5325         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5326       return SDValue();
5327     if (!LDBase) {
5328       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5329         return SDValue();
5330       LDBase = cast<LoadSDNode>(Elt.getNode());
5331       LastLoadedElt = i;
5332       continue;
5333     }
5334     if (Elt.getOpcode() == ISD::UNDEF)
5335       continue;
5336
5337     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5338     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5339       return SDValue();
5340     LastLoadedElt = i;
5341   }
5342
5343   // If we have found an entire vector of loads and undefs, then return a large
5344   // load of the entire vector width starting at the base pointer.  If we found
5345   // consecutive loads for the low half, generate a vzext_load node.
5346   if (LastLoadedElt == NumElems - 1) {
5347     SDValue NewLd = SDValue();
5348     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5349       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5350                           LDBase->getPointerInfo(),
5351                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5352                           LDBase->isInvariant(), 0);
5353     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5354                         LDBase->getPointerInfo(),
5355                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5356                         LDBase->isInvariant(), LDBase->getAlignment());
5357
5358     if (LDBase->hasAnyUseOfValue(1)) {
5359       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5360                                      SDValue(LDBase, 1),
5361                                      SDValue(NewLd.getNode(), 1));
5362       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5363       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5364                              SDValue(NewLd.getNode(), 1));
5365     }
5366
5367     return NewLd;
5368   }
5369   if (NumElems == 4 && LastLoadedElt == 1 &&
5370       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5371     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5372     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5373     SDValue ResNode =
5374         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5375                                 array_lengthof(Ops), MVT::i64,
5376                                 LDBase->getPointerInfo(),
5377                                 LDBase->getAlignment(),
5378                                 false/*isVolatile*/, true/*ReadMem*/,
5379                                 false/*WriteMem*/);
5380
5381     // Make sure the newly-created LOAD is in the same position as LDBase in
5382     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5383     // update uses of LDBase's output chain to use the TokenFactor.
5384     if (LDBase->hasAnyUseOfValue(1)) {
5385       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5386                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5387       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5388       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5389                              SDValue(ResNode.getNode(), 1));
5390     }
5391
5392     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5393   }
5394   return SDValue();
5395 }
5396
5397 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5398 /// to generate a splat value for the following cases:
5399 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5400 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5401 /// a scalar load, or a constant.
5402 /// The VBROADCAST node is returned when a pattern is found,
5403 /// or SDValue() otherwise.
5404 SDValue
5405 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5406   if (!Subtarget->hasFp256())
5407     return SDValue();
5408
5409   MVT VT = Op.getValueType().getSimpleVT();
5410   SDLoc dl(Op);
5411
5412   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5413          "Unsupported vector type for broadcast.");
5414
5415   SDValue Ld;
5416   bool ConstSplatVal;
5417
5418   switch (Op.getOpcode()) {
5419     default:
5420       // Unknown pattern found.
5421       return SDValue();
5422
5423     case ISD::BUILD_VECTOR: {
5424       // The BUILD_VECTOR node must be a splat.
5425       if (!isSplatVector(Op.getNode()))
5426         return SDValue();
5427
5428       Ld = Op.getOperand(0);
5429       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5430                      Ld.getOpcode() == ISD::ConstantFP);
5431
5432       // The suspected load node has several users. Make sure that all
5433       // of its users are from the BUILD_VECTOR node.
5434       // Constants may have multiple users.
5435       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5436         return SDValue();
5437       break;
5438     }
5439
5440     case ISD::VECTOR_SHUFFLE: {
5441       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5442
5443       // Shuffles must have a splat mask where the first element is
5444       // broadcasted.
5445       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5446         return SDValue();
5447
5448       SDValue Sc = Op.getOperand(0);
5449       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5450           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5451
5452         if (!Subtarget->hasInt256())
5453           return SDValue();
5454
5455         // Use the register form of the broadcast instruction available on AVX2.
5456         if (VT.is256BitVector())
5457           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5458         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5459       }
5460
5461       Ld = Sc.getOperand(0);
5462       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5463                        Ld.getOpcode() == ISD::ConstantFP);
5464
5465       // The scalar_to_vector node and the suspected
5466       // load node must have exactly one user.
5467       // Constants may have multiple users.
5468       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5469         return SDValue();
5470       break;
5471     }
5472   }
5473
5474   bool Is256 = VT.is256BitVector();
5475
5476   // Handle the broadcasting a single constant scalar from the constant pool
5477   // into a vector. On Sandybridge it is still better to load a constant vector
5478   // from the constant pool and not to broadcast it from a scalar.
5479   if (ConstSplatVal && Subtarget->hasInt256()) {
5480     EVT CVT = Ld.getValueType();
5481     assert(!CVT.isVector() && "Must not broadcast a vector type");
5482     unsigned ScalarSize = CVT.getSizeInBits();
5483
5484     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5485       const Constant *C = 0;
5486       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5487         C = CI->getConstantIntValue();
5488       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5489         C = CF->getConstantFPValue();
5490
5491       assert(C && "Invalid constant type");
5492
5493       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5494       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5495       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5496                        MachinePointerInfo::getConstantPool(),
5497                        false, false, false, Alignment);
5498
5499       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5500     }
5501   }
5502
5503   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5504   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5505
5506   // Handle AVX2 in-register broadcasts.
5507   if (!IsLoad && Subtarget->hasInt256() &&
5508       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5509     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5510
5511   // The scalar source must be a normal load.
5512   if (!IsLoad)
5513     return SDValue();
5514
5515   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5516     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5517
5518   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5519   // double since there is no vbroadcastsd xmm
5520   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5521     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5522       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5523   }
5524
5525   // Unsupported broadcast.
5526   return SDValue();
5527 }
5528
5529 SDValue
5530 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5531   EVT VT = Op.getValueType();
5532
5533   // Skip if insert_vec_elt is not supported.
5534   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5535     return SDValue();
5536
5537   SDLoc DL(Op);
5538   unsigned NumElems = Op.getNumOperands();
5539
5540   SDValue VecIn1;
5541   SDValue VecIn2;
5542   SmallVector<unsigned, 4> InsertIndices;
5543   SmallVector<int, 8> Mask(NumElems, -1);
5544
5545   for (unsigned i = 0; i != NumElems; ++i) {
5546     unsigned Opc = Op.getOperand(i).getOpcode();
5547
5548     if (Opc == ISD::UNDEF)
5549       continue;
5550
5551     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5552       // Quit if more than 1 elements need inserting.
5553       if (InsertIndices.size() > 1)
5554         return SDValue();
5555
5556       InsertIndices.push_back(i);
5557       continue;
5558     }
5559
5560     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5561     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5562
5563     // Quit if extracted from vector of different type.
5564     if (ExtractedFromVec.getValueType() != VT)
5565       return SDValue();
5566
5567     // Quit if non-constant index.
5568     if (!isa<ConstantSDNode>(ExtIdx))
5569       return SDValue();
5570
5571     if (VecIn1.getNode() == 0)
5572       VecIn1 = ExtractedFromVec;
5573     else if (VecIn1 != ExtractedFromVec) {
5574       if (VecIn2.getNode() == 0)
5575         VecIn2 = ExtractedFromVec;
5576       else if (VecIn2 != ExtractedFromVec)
5577         // Quit if more than 2 vectors to shuffle
5578         return SDValue();
5579     }
5580
5581     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5582
5583     if (ExtractedFromVec == VecIn1)
5584       Mask[i] = Idx;
5585     else if (ExtractedFromVec == VecIn2)
5586       Mask[i] = Idx + NumElems;
5587   }
5588
5589   if (VecIn1.getNode() == 0)
5590     return SDValue();
5591
5592   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5593   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5594   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5595     unsigned Idx = InsertIndices[i];
5596     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5597                      DAG.getIntPtrConstant(Idx));
5598   }
5599
5600   return NV;
5601 }
5602
5603 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5604 SDValue
5605 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5606
5607   EVT VT = Op.getValueType();
5608   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5609          "Unexpected type in LowerBUILD_VECTORvXi1!");
5610
5611   SDLoc dl(Op);
5612   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5613     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5614     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5615                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5616     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5617                        Ops, VT.getVectorNumElements());
5618   }
5619
5620   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5621     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5622     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5623                       Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5624     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
5625                        Ops, VT.getVectorNumElements());
5626   }
5627
5628   bool AllContants = true;
5629   uint64_t Immediate = 0;
5630   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5631     SDValue In = Op.getOperand(idx);
5632     if (In.getOpcode() == ISD::UNDEF)
5633       continue;
5634     if (!isa<ConstantSDNode>(In)) {
5635       AllContants = false;
5636       break;
5637     }
5638     if (cast<ConstantSDNode>(In)->getZExtValue())
5639       Immediate |= (1ULL << idx);
5640   }
5641
5642   if (AllContants) {
5643     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5644       DAG.getConstant(Immediate, MVT::i16));
5645     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5646                        DAG.getIntPtrConstant(0));
5647   }
5648
5649   if (!isSplatVector(Op.getNode()))
5650     llvm_unreachable("Unsupported predicate operation");
5651
5652   SDValue In = Op.getOperand(0);
5653   SDValue EFLAGS, X86CC;
5654   if (In.getOpcode() == ISD::SETCC) {
5655     SDValue Op0 = In.getOperand(0);
5656     SDValue Op1 = In.getOperand(1);
5657     ISD::CondCode CC = cast<CondCodeSDNode>(In.getOperand(2))->get();
5658     bool isFP = Op1.getValueType().isFloatingPoint();
5659     unsigned X86CCVal = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5660
5661     assert(X86CCVal != X86::COND_INVALID && "Unsupported predicate operation");
5662
5663     X86CC = DAG.getConstant(X86CCVal, MVT::i8);
5664     EFLAGS = EmitCmp(Op0, Op1, X86CCVal, DAG);
5665     EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
5666   } else if (In.getOpcode() == X86ISD::SETCC) {
5667     X86CC = In.getOperand(0);
5668     EFLAGS = In.getOperand(1);
5669   } else {
5670     // The algorithm:
5671     //   Bit1 = In & 0x1
5672     //   if (Bit1 != 0)
5673     //     ZF = 0
5674     //   else
5675     //     ZF = 1
5676     //   if (ZF == 0)
5677     //     res = allOnes ### CMOVNE -1, %res
5678     //   else
5679     //     res = allZero
5680     MVT InVT = In.getValueType().getSimpleVT();
5681     SDValue Bit1 = DAG.getNode(ISD::AND, dl, InVT, In, DAG.getConstant(1, InVT));
5682     EFLAGS = EmitTest(Bit1, X86::COND_NE, DAG);
5683     X86CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5684   }
5685
5686   if (VT == MVT::v16i1) {
5687     SDValue Cst1 = DAG.getConstant(-1, MVT::i16);
5688     SDValue Cst0 = DAG.getConstant(0, MVT::i16);
5689     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i16,
5690           Cst0, Cst1, X86CC, EFLAGS);
5691     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5692   }
5693
5694   if (VT == MVT::v8i1) {
5695     SDValue Cst1 = DAG.getConstant(-1, MVT::i32);
5696     SDValue Cst0 = DAG.getConstant(0, MVT::i32);
5697     SDValue CmovOp = DAG.getNode(X86ISD::CMOV, dl, MVT::i32,
5698           Cst0, Cst1, X86CC, EFLAGS);
5699     CmovOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CmovOp);
5700     return DAG.getNode(ISD::BITCAST, dl, VT, CmovOp);
5701   }
5702   llvm_unreachable("Unsupported predicate operation");
5703 }
5704
5705 SDValue
5706 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5707   SDLoc dl(Op);
5708
5709   MVT VT = Op.getValueType().getSimpleVT();
5710   MVT ExtVT = VT.getVectorElementType();
5711   unsigned NumElems = Op.getNumOperands();
5712
5713   // Generate vectors for predicate vectors.
5714   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5715     return LowerBUILD_VECTORvXi1(Op, DAG);
5716
5717   // Vectors containing all zeros can be matched by pxor and xorps later
5718   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5719     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5720     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5721     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5722       return Op;
5723
5724     return getZeroVector(VT, Subtarget, DAG, dl);
5725   }
5726
5727   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5728   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5729   // vpcmpeqd on 256-bit vectors.
5730   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5731     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5732       return Op;
5733
5734     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5735   }
5736
5737   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5738   if (Broadcast.getNode())
5739     return Broadcast;
5740
5741   unsigned EVTBits = ExtVT.getSizeInBits();
5742
5743   unsigned NumZero  = 0;
5744   unsigned NumNonZero = 0;
5745   unsigned NonZeros = 0;
5746   bool IsAllConstants = true;
5747   SmallSet<SDValue, 8> Values;
5748   for (unsigned i = 0; i < NumElems; ++i) {
5749     SDValue Elt = Op.getOperand(i);
5750     if (Elt.getOpcode() == ISD::UNDEF)
5751       continue;
5752     Values.insert(Elt);
5753     if (Elt.getOpcode() != ISD::Constant &&
5754         Elt.getOpcode() != ISD::ConstantFP)
5755       IsAllConstants = false;
5756     if (X86::isZeroNode(Elt))
5757       NumZero++;
5758     else {
5759       NonZeros |= (1 << i);
5760       NumNonZero++;
5761     }
5762   }
5763
5764   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5765   if (NumNonZero == 0)
5766     return DAG.getUNDEF(VT);
5767
5768   // Special case for single non-zero, non-undef, element.
5769   if (NumNonZero == 1) {
5770     unsigned Idx = countTrailingZeros(NonZeros);
5771     SDValue Item = Op.getOperand(Idx);
5772
5773     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5774     // the value are obviously zero, truncate the value to i32 and do the
5775     // insertion that way.  Only do this if the value is non-constant or if the
5776     // value is a constant being inserted into element 0.  It is cheaper to do
5777     // a constant pool load than it is to do a movd + shuffle.
5778     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5779         (!IsAllConstants || Idx == 0)) {
5780       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5781         // Handle SSE only.
5782         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5783         EVT VecVT = MVT::v4i32;
5784         unsigned VecElts = 4;
5785
5786         // Truncate the value (which may itself be a constant) to i32, and
5787         // convert it to a vector with movd (S2V+shuffle to zero extend).
5788         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5789         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5790         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5791
5792         // Now we have our 32-bit value zero extended in the low element of
5793         // a vector.  If Idx != 0, swizzle it into place.
5794         if (Idx != 0) {
5795           SmallVector<int, 4> Mask;
5796           Mask.push_back(Idx);
5797           for (unsigned i = 1; i != VecElts; ++i)
5798             Mask.push_back(i);
5799           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5800                                       &Mask[0]);
5801         }
5802         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5803       }
5804     }
5805
5806     // If we have a constant or non-constant insertion into the low element of
5807     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5808     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5809     // depending on what the source datatype is.
5810     if (Idx == 0) {
5811       if (NumZero == 0)
5812         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5813
5814       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5815           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5816         if (VT.is256BitVector()) {
5817           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5818           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5819                              Item, DAG.getIntPtrConstant(0));
5820         }
5821         assert(VT.is128BitVector() && "Expected an SSE value type!");
5822         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5823         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5824         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5825       }
5826
5827       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5828         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5829         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5830         if (VT.is256BitVector()) {
5831           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5832           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5833         } else {
5834           assert(VT.is128BitVector() && "Expected an SSE value type!");
5835           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5836         }
5837         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5838       }
5839     }
5840
5841     // Is it a vector logical left shift?
5842     if (NumElems == 2 && Idx == 1 &&
5843         X86::isZeroNode(Op.getOperand(0)) &&
5844         !X86::isZeroNode(Op.getOperand(1))) {
5845       unsigned NumBits = VT.getSizeInBits();
5846       return getVShift(true, VT,
5847                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5848                                    VT, Op.getOperand(1)),
5849                        NumBits/2, DAG, *this, dl);
5850     }
5851
5852     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5853       return SDValue();
5854
5855     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5856     // is a non-constant being inserted into an element other than the low one,
5857     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5858     // movd/movss) to move this into the low element, then shuffle it into
5859     // place.
5860     if (EVTBits == 32) {
5861       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5862
5863       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5864       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5865       SmallVector<int, 8> MaskVec;
5866       for (unsigned i = 0; i != NumElems; ++i)
5867         MaskVec.push_back(i == Idx ? 0 : 1);
5868       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5869     }
5870   }
5871
5872   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5873   if (Values.size() == 1) {
5874     if (EVTBits == 32) {
5875       // Instead of a shuffle like this:
5876       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5877       // Check if it's possible to issue this instead.
5878       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5879       unsigned Idx = countTrailingZeros(NonZeros);
5880       SDValue Item = Op.getOperand(Idx);
5881       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5882         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5883     }
5884     return SDValue();
5885   }
5886
5887   // A vector full of immediates; various special cases are already
5888   // handled, so this is best done with a single constant-pool load.
5889   if (IsAllConstants)
5890     return SDValue();
5891
5892   // For AVX-length vectors, build the individual 128-bit pieces and use
5893   // shuffles to put them in place.
5894   if (VT.is256BitVector()) {
5895     SmallVector<SDValue, 32> V;
5896     for (unsigned i = 0; i != NumElems; ++i)
5897       V.push_back(Op.getOperand(i));
5898
5899     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5900
5901     // Build both the lower and upper subvector.
5902     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5903     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5904                                 NumElems/2);
5905
5906     // Recreate the wider vector with the lower and upper part.
5907     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5908   }
5909
5910   // Let legalizer expand 2-wide build_vectors.
5911   if (EVTBits == 64) {
5912     if (NumNonZero == 1) {
5913       // One half is zero or undef.
5914       unsigned Idx = countTrailingZeros(NonZeros);
5915       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5916                                  Op.getOperand(Idx));
5917       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5918     }
5919     return SDValue();
5920   }
5921
5922   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5923   if (EVTBits == 8 && NumElems == 16) {
5924     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5925                                         Subtarget, *this);
5926     if (V.getNode()) return V;
5927   }
5928
5929   if (EVTBits == 16 && NumElems == 8) {
5930     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5931                                       Subtarget, *this);
5932     if (V.getNode()) return V;
5933   }
5934
5935   // If element VT is == 32 bits, turn it into a number of shuffles.
5936   SmallVector<SDValue, 8> V(NumElems);
5937   if (NumElems == 4 && NumZero > 0) {
5938     for (unsigned i = 0; i < 4; ++i) {
5939       bool isZero = !(NonZeros & (1 << i));
5940       if (isZero)
5941         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5942       else
5943         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5944     }
5945
5946     for (unsigned i = 0; i < 2; ++i) {
5947       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5948         default: break;
5949         case 0:
5950           V[i] = V[i*2];  // Must be a zero vector.
5951           break;
5952         case 1:
5953           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5954           break;
5955         case 2:
5956           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5957           break;
5958         case 3:
5959           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5960           break;
5961       }
5962     }
5963
5964     bool Reverse1 = (NonZeros & 0x3) == 2;
5965     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5966     int MaskVec[] = {
5967       Reverse1 ? 1 : 0,
5968       Reverse1 ? 0 : 1,
5969       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5970       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5971     };
5972     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5973   }
5974
5975   if (Values.size() > 1 && VT.is128BitVector()) {
5976     // Check for a build vector of consecutive loads.
5977     for (unsigned i = 0; i < NumElems; ++i)
5978       V[i] = Op.getOperand(i);
5979
5980     // Check for elements which are consecutive loads.
5981     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5982     if (LD.getNode())
5983       return LD;
5984
5985     // Check for a build vector from mostly shuffle plus few inserting.
5986     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5987     if (Sh.getNode())
5988       return Sh;
5989
5990     // For SSE 4.1, use insertps to put the high elements into the low element.
5991     if (getSubtarget()->hasSSE41()) {
5992       SDValue Result;
5993       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5994         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5995       else
5996         Result = DAG.getUNDEF(VT);
5997
5998       for (unsigned i = 1; i < NumElems; ++i) {
5999         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6000         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6001                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6002       }
6003       return Result;
6004     }
6005
6006     // Otherwise, expand into a number of unpckl*, start by extending each of
6007     // our (non-undef) elements to the full vector width with the element in the
6008     // bottom slot of the vector (which generates no code for SSE).
6009     for (unsigned i = 0; i < NumElems; ++i) {
6010       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6011         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6012       else
6013         V[i] = DAG.getUNDEF(VT);
6014     }
6015
6016     // Next, we iteratively mix elements, e.g. for v4f32:
6017     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6018     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6019     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6020     unsigned EltStride = NumElems >> 1;
6021     while (EltStride != 0) {
6022       for (unsigned i = 0; i < EltStride; ++i) {
6023         // If V[i+EltStride] is undef and this is the first round of mixing,
6024         // then it is safe to just drop this shuffle: V[i] is already in the
6025         // right place, the one element (since it's the first round) being
6026         // inserted as undef can be dropped.  This isn't safe for successive
6027         // rounds because they will permute elements within both vectors.
6028         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6029             EltStride == NumElems/2)
6030           continue;
6031
6032         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6033       }
6034       EltStride >>= 1;
6035     }
6036     return V[0];
6037   }
6038   return SDValue();
6039 }
6040
6041 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6042 // to create 256-bit vectors from two other 128-bit ones.
6043 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6044   SDLoc dl(Op);
6045   MVT ResVT = Op.getValueType().getSimpleVT();
6046
6047   assert((ResVT.is256BitVector() ||
6048           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6049
6050   SDValue V1 = Op.getOperand(0);
6051   SDValue V2 = Op.getOperand(1);
6052   unsigned NumElems = ResVT.getVectorNumElements();
6053   if(ResVT.is256BitVector())
6054     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6055
6056   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6057 }
6058
6059 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6060   assert(Op.getNumOperands() == 2);
6061
6062   // AVX/AVX-512 can use the vinsertf128 instruction to create 256-bit vectors
6063   // from two other 128-bit ones.
6064   return LowerAVXCONCAT_VECTORS(Op, DAG);
6065 }
6066
6067 // Try to lower a shuffle node into a simple blend instruction.
6068 static SDValue
6069 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6070                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6071   SDValue V1 = SVOp->getOperand(0);
6072   SDValue V2 = SVOp->getOperand(1);
6073   SDLoc dl(SVOp);
6074   MVT VT = SVOp->getValueType(0).getSimpleVT();
6075   MVT EltVT = VT.getVectorElementType();
6076   unsigned NumElems = VT.getVectorNumElements();
6077
6078   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6079     return SDValue();
6080   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6081     return SDValue();
6082
6083   // Check the mask for BLEND and build the value.
6084   unsigned MaskValue = 0;
6085   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6086   unsigned NumLanes = (NumElems-1)/8 + 1;
6087   unsigned NumElemsInLane = NumElems / NumLanes;
6088
6089   // Blend for v16i16 should be symetric for the both lanes.
6090   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6091
6092     int SndLaneEltIdx = (NumLanes == 2) ?
6093       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6094     int EltIdx = SVOp->getMaskElt(i);
6095
6096     if ((EltIdx < 0 || EltIdx == (int)i) &&
6097         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6098       continue;
6099
6100     if (((unsigned)EltIdx == (i + NumElems)) &&
6101         (SndLaneEltIdx < 0 ||
6102          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6103       MaskValue |= (1<<i);
6104     else
6105       return SDValue();
6106   }
6107
6108   // Convert i32 vectors to floating point if it is not AVX2.
6109   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6110   MVT BlendVT = VT;
6111   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6112     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6113                                NumElems);
6114     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6115     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6116   }
6117
6118   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6119                             DAG.getConstant(MaskValue, MVT::i32));
6120   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6121 }
6122
6123 // v8i16 shuffles - Prefer shuffles in the following order:
6124 // 1. [all]   pshuflw, pshufhw, optional move
6125 // 2. [ssse3] 1 x pshufb
6126 // 3. [ssse3] 2 x pshufb + 1 x por
6127 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6128 static SDValue
6129 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6130                          SelectionDAG &DAG) {
6131   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6132   SDValue V1 = SVOp->getOperand(0);
6133   SDValue V2 = SVOp->getOperand(1);
6134   SDLoc dl(SVOp);
6135   SmallVector<int, 8> MaskVals;
6136
6137   // Determine if more than 1 of the words in each of the low and high quadwords
6138   // of the result come from the same quadword of one of the two inputs.  Undef
6139   // mask values count as coming from any quadword, for better codegen.
6140   unsigned LoQuad[] = { 0, 0, 0, 0 };
6141   unsigned HiQuad[] = { 0, 0, 0, 0 };
6142   std::bitset<4> InputQuads;
6143   for (unsigned i = 0; i < 8; ++i) {
6144     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6145     int EltIdx = SVOp->getMaskElt(i);
6146     MaskVals.push_back(EltIdx);
6147     if (EltIdx < 0) {
6148       ++Quad[0];
6149       ++Quad[1];
6150       ++Quad[2];
6151       ++Quad[3];
6152       continue;
6153     }
6154     ++Quad[EltIdx / 4];
6155     InputQuads.set(EltIdx / 4);
6156   }
6157
6158   int BestLoQuad = -1;
6159   unsigned MaxQuad = 1;
6160   for (unsigned i = 0; i < 4; ++i) {
6161     if (LoQuad[i] > MaxQuad) {
6162       BestLoQuad = i;
6163       MaxQuad = LoQuad[i];
6164     }
6165   }
6166
6167   int BestHiQuad = -1;
6168   MaxQuad = 1;
6169   for (unsigned i = 0; i < 4; ++i) {
6170     if (HiQuad[i] > MaxQuad) {
6171       BestHiQuad = i;
6172       MaxQuad = HiQuad[i];
6173     }
6174   }
6175
6176   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6177   // of the two input vectors, shuffle them into one input vector so only a
6178   // single pshufb instruction is necessary. If There are more than 2 input
6179   // quads, disable the next transformation since it does not help SSSE3.
6180   bool V1Used = InputQuads[0] || InputQuads[1];
6181   bool V2Used = InputQuads[2] || InputQuads[3];
6182   if (Subtarget->hasSSSE3()) {
6183     if (InputQuads.count() == 2 && V1Used && V2Used) {
6184       BestLoQuad = InputQuads[0] ? 0 : 1;
6185       BestHiQuad = InputQuads[2] ? 2 : 3;
6186     }
6187     if (InputQuads.count() > 2) {
6188       BestLoQuad = -1;
6189       BestHiQuad = -1;
6190     }
6191   }
6192
6193   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6194   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6195   // words from all 4 input quadwords.
6196   SDValue NewV;
6197   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6198     int MaskV[] = {
6199       BestLoQuad < 0 ? 0 : BestLoQuad,
6200       BestHiQuad < 0 ? 1 : BestHiQuad
6201     };
6202     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6203                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6204                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6205     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6206
6207     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6208     // source words for the shuffle, to aid later transformations.
6209     bool AllWordsInNewV = true;
6210     bool InOrder[2] = { true, true };
6211     for (unsigned i = 0; i != 8; ++i) {
6212       int idx = MaskVals[i];
6213       if (idx != (int)i)
6214         InOrder[i/4] = false;
6215       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6216         continue;
6217       AllWordsInNewV = false;
6218       break;
6219     }
6220
6221     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6222     if (AllWordsInNewV) {
6223       for (int i = 0; i != 8; ++i) {
6224         int idx = MaskVals[i];
6225         if (idx < 0)
6226           continue;
6227         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6228         if ((idx != i) && idx < 4)
6229           pshufhw = false;
6230         if ((idx != i) && idx > 3)
6231           pshuflw = false;
6232       }
6233       V1 = NewV;
6234       V2Used = false;
6235       BestLoQuad = 0;
6236       BestHiQuad = 1;
6237     }
6238
6239     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6240     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6241     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6242       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6243       unsigned TargetMask = 0;
6244       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6245                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6246       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6247       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6248                              getShufflePSHUFLWImmediate(SVOp);
6249       V1 = NewV.getOperand(0);
6250       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6251     }
6252   }
6253
6254   // Promote splats to a larger type which usually leads to more efficient code.
6255   // FIXME: Is this true if pshufb is available?
6256   if (SVOp->isSplat())
6257     return PromoteSplat(SVOp, DAG);
6258
6259   // If we have SSSE3, and all words of the result are from 1 input vector,
6260   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6261   // is present, fall back to case 4.
6262   if (Subtarget->hasSSSE3()) {
6263     SmallVector<SDValue,16> pshufbMask;
6264
6265     // If we have elements from both input vectors, set the high bit of the
6266     // shuffle mask element to zero out elements that come from V2 in the V1
6267     // mask, and elements that come from V1 in the V2 mask, so that the two
6268     // results can be OR'd together.
6269     bool TwoInputs = V1Used && V2Used;
6270     for (unsigned i = 0; i != 8; ++i) {
6271       int EltIdx = MaskVals[i] * 2;
6272       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
6273       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
6274       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6275       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6276     }
6277     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
6278     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6279                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6280                                  MVT::v16i8, &pshufbMask[0], 16));
6281     if (!TwoInputs)
6282       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6283
6284     // Calculate the shuffle mask for the second input, shuffle it, and
6285     // OR it with the first shuffled input.
6286     pshufbMask.clear();
6287     for (unsigned i = 0; i != 8; ++i) {
6288       int EltIdx = MaskVals[i] * 2;
6289       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6290       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
6291       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
6292       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
6293     }
6294     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
6295     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6296                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6297                                  MVT::v16i8, &pshufbMask[0], 16));
6298     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6299     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6300   }
6301
6302   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6303   // and update MaskVals with new element order.
6304   std::bitset<8> InOrder;
6305   if (BestLoQuad >= 0) {
6306     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6307     for (int i = 0; i != 4; ++i) {
6308       int idx = MaskVals[i];
6309       if (idx < 0) {
6310         InOrder.set(i);
6311       } else if ((idx / 4) == BestLoQuad) {
6312         MaskV[i] = idx & 3;
6313         InOrder.set(i);
6314       }
6315     }
6316     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6317                                 &MaskV[0]);
6318
6319     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6320       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6321       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6322                                   NewV.getOperand(0),
6323                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6324     }
6325   }
6326
6327   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6328   // and update MaskVals with the new element order.
6329   if (BestHiQuad >= 0) {
6330     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6331     for (unsigned i = 4; i != 8; ++i) {
6332       int idx = MaskVals[i];
6333       if (idx < 0) {
6334         InOrder.set(i);
6335       } else if ((idx / 4) == BestHiQuad) {
6336         MaskV[i] = (idx & 3) + 4;
6337         InOrder.set(i);
6338       }
6339     }
6340     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6341                                 &MaskV[0]);
6342
6343     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6344       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6345       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6346                                   NewV.getOperand(0),
6347                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6348     }
6349   }
6350
6351   // In case BestHi & BestLo were both -1, which means each quadword has a word
6352   // from each of the four input quadwords, calculate the InOrder bitvector now
6353   // before falling through to the insert/extract cleanup.
6354   if (BestLoQuad == -1 && BestHiQuad == -1) {
6355     NewV = V1;
6356     for (int i = 0; i != 8; ++i)
6357       if (MaskVals[i] < 0 || MaskVals[i] == i)
6358         InOrder.set(i);
6359   }
6360
6361   // The other elements are put in the right place using pextrw and pinsrw.
6362   for (unsigned i = 0; i != 8; ++i) {
6363     if (InOrder[i])
6364       continue;
6365     int EltIdx = MaskVals[i];
6366     if (EltIdx < 0)
6367       continue;
6368     SDValue ExtOp = (EltIdx < 8) ?
6369       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6370                   DAG.getIntPtrConstant(EltIdx)) :
6371       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6372                   DAG.getIntPtrConstant(EltIdx - 8));
6373     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6374                        DAG.getIntPtrConstant(i));
6375   }
6376   return NewV;
6377 }
6378
6379 // v16i8 shuffles - Prefer shuffles in the following order:
6380 // 1. [ssse3] 1 x pshufb
6381 // 2. [ssse3] 2 x pshufb + 1 x por
6382 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6383 static
6384 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6385                                  SelectionDAG &DAG,
6386                                  const X86TargetLowering &TLI) {
6387   SDValue V1 = SVOp->getOperand(0);
6388   SDValue V2 = SVOp->getOperand(1);
6389   SDLoc dl(SVOp);
6390   ArrayRef<int> MaskVals = SVOp->getMask();
6391
6392   // Promote splats to a larger type which usually leads to more efficient code.
6393   // FIXME: Is this true if pshufb is available?
6394   if (SVOp->isSplat())
6395     return PromoteSplat(SVOp, DAG);
6396
6397   // If we have SSSE3, case 1 is generated when all result bytes come from
6398   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6399   // present, fall back to case 3.
6400
6401   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6402   if (TLI.getSubtarget()->hasSSSE3()) {
6403     SmallVector<SDValue,16> pshufbMask;
6404
6405     // If all result elements are from one input vector, then only translate
6406     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6407     //
6408     // Otherwise, we have elements from both input vectors, and must zero out
6409     // elements that come from V2 in the first mask, and V1 in the second mask
6410     // so that we can OR them together.
6411     for (unsigned i = 0; i != 16; ++i) {
6412       int EltIdx = MaskVals[i];
6413       if (EltIdx < 0 || EltIdx >= 16)
6414         EltIdx = 0x80;
6415       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6416     }
6417     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6418                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6419                                  MVT::v16i8, &pshufbMask[0], 16));
6420
6421     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6422     // the 2nd operand if it's undefined or zero.
6423     if (V2.getOpcode() == ISD::UNDEF ||
6424         ISD::isBuildVectorAllZeros(V2.getNode()))
6425       return V1;
6426
6427     // Calculate the shuffle mask for the second input, shuffle it, and
6428     // OR it with the first shuffled input.
6429     pshufbMask.clear();
6430     for (unsigned i = 0; i != 16; ++i) {
6431       int EltIdx = MaskVals[i];
6432       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6433       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6434     }
6435     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6436                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6437                                  MVT::v16i8, &pshufbMask[0], 16));
6438     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6439   }
6440
6441   // No SSSE3 - Calculate in place words and then fix all out of place words
6442   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6443   // the 16 different words that comprise the two doublequadword input vectors.
6444   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6445   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6446   SDValue NewV = V1;
6447   for (int i = 0; i != 8; ++i) {
6448     int Elt0 = MaskVals[i*2];
6449     int Elt1 = MaskVals[i*2+1];
6450
6451     // This word of the result is all undef, skip it.
6452     if (Elt0 < 0 && Elt1 < 0)
6453       continue;
6454
6455     // This word of the result is already in the correct place, skip it.
6456     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6457       continue;
6458
6459     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6460     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6461     SDValue InsElt;
6462
6463     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6464     // using a single extract together, load it and store it.
6465     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6466       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6467                            DAG.getIntPtrConstant(Elt1 / 2));
6468       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6469                         DAG.getIntPtrConstant(i));
6470       continue;
6471     }
6472
6473     // If Elt1 is defined, extract it from the appropriate source.  If the
6474     // source byte is not also odd, shift the extracted word left 8 bits
6475     // otherwise clear the bottom 8 bits if we need to do an or.
6476     if (Elt1 >= 0) {
6477       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6478                            DAG.getIntPtrConstant(Elt1 / 2));
6479       if ((Elt1 & 1) == 0)
6480         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6481                              DAG.getConstant(8,
6482                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6483       else if (Elt0 >= 0)
6484         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6485                              DAG.getConstant(0xFF00, MVT::i16));
6486     }
6487     // If Elt0 is defined, extract it from the appropriate source.  If the
6488     // source byte is not also even, shift the extracted word right 8 bits. If
6489     // Elt1 was also defined, OR the extracted values together before
6490     // inserting them in the result.
6491     if (Elt0 >= 0) {
6492       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6493                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6494       if ((Elt0 & 1) != 0)
6495         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6496                               DAG.getConstant(8,
6497                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6498       else if (Elt1 >= 0)
6499         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6500                              DAG.getConstant(0x00FF, MVT::i16));
6501       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6502                          : InsElt0;
6503     }
6504     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6505                        DAG.getIntPtrConstant(i));
6506   }
6507   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6508 }
6509
6510 // v32i8 shuffles - Translate to VPSHUFB if possible.
6511 static
6512 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6513                                  const X86Subtarget *Subtarget,
6514                                  SelectionDAG &DAG) {
6515   MVT VT = SVOp->getValueType(0).getSimpleVT();
6516   SDValue V1 = SVOp->getOperand(0);
6517   SDValue V2 = SVOp->getOperand(1);
6518   SDLoc dl(SVOp);
6519   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6520
6521   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6522   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6523   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6524
6525   // VPSHUFB may be generated if
6526   // (1) one of input vector is undefined or zeroinitializer.
6527   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6528   // And (2) the mask indexes don't cross the 128-bit lane.
6529   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6530       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6531     return SDValue();
6532
6533   if (V1IsAllZero && !V2IsAllZero) {
6534     CommuteVectorShuffleMask(MaskVals, 32);
6535     V1 = V2;
6536   }
6537   SmallVector<SDValue, 32> pshufbMask;
6538   for (unsigned i = 0; i != 32; i++) {
6539     int EltIdx = MaskVals[i];
6540     if (EltIdx < 0 || EltIdx >= 32)
6541       EltIdx = 0x80;
6542     else {
6543       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6544         // Cross lane is not allowed.
6545         return SDValue();
6546       EltIdx &= 0xf;
6547     }
6548     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6549   }
6550   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6551                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6552                                   MVT::v32i8, &pshufbMask[0], 32));
6553 }
6554
6555 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6556 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6557 /// done when every pair / quad of shuffle mask elements point to elements in
6558 /// the right sequence. e.g.
6559 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6560 static
6561 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6562                                  SelectionDAG &DAG) {
6563   MVT VT = SVOp->getValueType(0).getSimpleVT();
6564   SDLoc dl(SVOp);
6565   unsigned NumElems = VT.getVectorNumElements();
6566   MVT NewVT;
6567   unsigned Scale;
6568   switch (VT.SimpleTy) {
6569   default: llvm_unreachable("Unexpected!");
6570   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6571   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6572   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6573   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6574   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6575   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6576   }
6577
6578   SmallVector<int, 8> MaskVec;
6579   for (unsigned i = 0; i != NumElems; i += Scale) {
6580     int StartIdx = -1;
6581     for (unsigned j = 0; j != Scale; ++j) {
6582       int EltIdx = SVOp->getMaskElt(i+j);
6583       if (EltIdx < 0)
6584         continue;
6585       if (StartIdx < 0)
6586         StartIdx = (EltIdx / Scale);
6587       if (EltIdx != (int)(StartIdx*Scale + j))
6588         return SDValue();
6589     }
6590     MaskVec.push_back(StartIdx);
6591   }
6592
6593   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6594   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6595   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6596 }
6597
6598 /// getVZextMovL - Return a zero-extending vector move low node.
6599 ///
6600 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6601                             SDValue SrcOp, SelectionDAG &DAG,
6602                             const X86Subtarget *Subtarget, SDLoc dl) {
6603   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6604     LoadSDNode *LD = NULL;
6605     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6606       LD = dyn_cast<LoadSDNode>(SrcOp);
6607     if (!LD) {
6608       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6609       // instead.
6610       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6611       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6612           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6613           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6614           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6615         // PR2108
6616         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6617         return DAG.getNode(ISD::BITCAST, dl, VT,
6618                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6619                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6620                                                    OpVT,
6621                                                    SrcOp.getOperand(0)
6622                                                           .getOperand(0))));
6623       }
6624     }
6625   }
6626
6627   return DAG.getNode(ISD::BITCAST, dl, VT,
6628                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6629                                  DAG.getNode(ISD::BITCAST, dl,
6630                                              OpVT, SrcOp)));
6631 }
6632
6633 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6634 /// which could not be matched by any known target speficic shuffle
6635 static SDValue
6636 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6637
6638   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6639   if (NewOp.getNode())
6640     return NewOp;
6641
6642   MVT VT = SVOp->getValueType(0).getSimpleVT();
6643
6644   unsigned NumElems = VT.getVectorNumElements();
6645   unsigned NumLaneElems = NumElems / 2;
6646
6647   SDLoc dl(SVOp);
6648   MVT EltVT = VT.getVectorElementType();
6649   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6650   SDValue Output[2];
6651
6652   SmallVector<int, 16> Mask;
6653   for (unsigned l = 0; l < 2; ++l) {
6654     // Build a shuffle mask for the output, discovering on the fly which
6655     // input vectors to use as shuffle operands (recorded in InputUsed).
6656     // If building a suitable shuffle vector proves too hard, then bail
6657     // out with UseBuildVector set.
6658     bool UseBuildVector = false;
6659     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6660     unsigned LaneStart = l * NumLaneElems;
6661     for (unsigned i = 0; i != NumLaneElems; ++i) {
6662       // The mask element.  This indexes into the input.
6663       int Idx = SVOp->getMaskElt(i+LaneStart);
6664       if (Idx < 0) {
6665         // the mask element does not index into any input vector.
6666         Mask.push_back(-1);
6667         continue;
6668       }
6669
6670       // The input vector this mask element indexes into.
6671       int Input = Idx / NumLaneElems;
6672
6673       // Turn the index into an offset from the start of the input vector.
6674       Idx -= Input * NumLaneElems;
6675
6676       // Find or create a shuffle vector operand to hold this input.
6677       unsigned OpNo;
6678       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6679         if (InputUsed[OpNo] == Input)
6680           // This input vector is already an operand.
6681           break;
6682         if (InputUsed[OpNo] < 0) {
6683           // Create a new operand for this input vector.
6684           InputUsed[OpNo] = Input;
6685           break;
6686         }
6687       }
6688
6689       if (OpNo >= array_lengthof(InputUsed)) {
6690         // More than two input vectors used!  Give up on trying to create a
6691         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6692         UseBuildVector = true;
6693         break;
6694       }
6695
6696       // Add the mask index for the new shuffle vector.
6697       Mask.push_back(Idx + OpNo * NumLaneElems);
6698     }
6699
6700     if (UseBuildVector) {
6701       SmallVector<SDValue, 16> SVOps;
6702       for (unsigned i = 0; i != NumLaneElems; ++i) {
6703         // The mask element.  This indexes into the input.
6704         int Idx = SVOp->getMaskElt(i+LaneStart);
6705         if (Idx < 0) {
6706           SVOps.push_back(DAG.getUNDEF(EltVT));
6707           continue;
6708         }
6709
6710         // The input vector this mask element indexes into.
6711         int Input = Idx / NumElems;
6712
6713         // Turn the index into an offset from the start of the input vector.
6714         Idx -= Input * NumElems;
6715
6716         // Extract the vector element by hand.
6717         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6718                                     SVOp->getOperand(Input),
6719                                     DAG.getIntPtrConstant(Idx)));
6720       }
6721
6722       // Construct the output using a BUILD_VECTOR.
6723       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6724                               SVOps.size());
6725     } else if (InputUsed[0] < 0) {
6726       // No input vectors were used! The result is undefined.
6727       Output[l] = DAG.getUNDEF(NVT);
6728     } else {
6729       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6730                                         (InputUsed[0] % 2) * NumLaneElems,
6731                                         DAG, dl);
6732       // If only one input was used, use an undefined vector for the other.
6733       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6734         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6735                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6736       // At least one input vector was used. Create a new shuffle vector.
6737       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6738     }
6739
6740     Mask.clear();
6741   }
6742
6743   // Concatenate the result back
6744   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6745 }
6746
6747 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6748 /// 4 elements, and match them with several different shuffle types.
6749 static SDValue
6750 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6751   SDValue V1 = SVOp->getOperand(0);
6752   SDValue V2 = SVOp->getOperand(1);
6753   SDLoc dl(SVOp);
6754   MVT VT = SVOp->getValueType(0).getSimpleVT();
6755
6756   assert(VT.is128BitVector() && "Unsupported vector size");
6757
6758   std::pair<int, int> Locs[4];
6759   int Mask1[] = { -1, -1, -1, -1 };
6760   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6761
6762   unsigned NumHi = 0;
6763   unsigned NumLo = 0;
6764   for (unsigned i = 0; i != 4; ++i) {
6765     int Idx = PermMask[i];
6766     if (Idx < 0) {
6767       Locs[i] = std::make_pair(-1, -1);
6768     } else {
6769       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6770       if (Idx < 4) {
6771         Locs[i] = std::make_pair(0, NumLo);
6772         Mask1[NumLo] = Idx;
6773         NumLo++;
6774       } else {
6775         Locs[i] = std::make_pair(1, NumHi);
6776         if (2+NumHi < 4)
6777           Mask1[2+NumHi] = Idx;
6778         NumHi++;
6779       }
6780     }
6781   }
6782
6783   if (NumLo <= 2 && NumHi <= 2) {
6784     // If no more than two elements come from either vector. This can be
6785     // implemented with two shuffles. First shuffle gather the elements.
6786     // The second shuffle, which takes the first shuffle as both of its
6787     // vector operands, put the elements into the right order.
6788     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6789
6790     int Mask2[] = { -1, -1, -1, -1 };
6791
6792     for (unsigned i = 0; i != 4; ++i)
6793       if (Locs[i].first != -1) {
6794         unsigned Idx = (i < 2) ? 0 : 4;
6795         Idx += Locs[i].first * 2 + Locs[i].second;
6796         Mask2[i] = Idx;
6797       }
6798
6799     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6800   }
6801
6802   if (NumLo == 3 || NumHi == 3) {
6803     // Otherwise, we must have three elements from one vector, call it X, and
6804     // one element from the other, call it Y.  First, use a shufps to build an
6805     // intermediate vector with the one element from Y and the element from X
6806     // that will be in the same half in the final destination (the indexes don't
6807     // matter). Then, use a shufps to build the final vector, taking the half
6808     // containing the element from Y from the intermediate, and the other half
6809     // from X.
6810     if (NumHi == 3) {
6811       // Normalize it so the 3 elements come from V1.
6812       CommuteVectorShuffleMask(PermMask, 4);
6813       std::swap(V1, V2);
6814     }
6815
6816     // Find the element from V2.
6817     unsigned HiIndex;
6818     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6819       int Val = PermMask[HiIndex];
6820       if (Val < 0)
6821         continue;
6822       if (Val >= 4)
6823         break;
6824     }
6825
6826     Mask1[0] = PermMask[HiIndex];
6827     Mask1[1] = -1;
6828     Mask1[2] = PermMask[HiIndex^1];
6829     Mask1[3] = -1;
6830     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6831
6832     if (HiIndex >= 2) {
6833       Mask1[0] = PermMask[0];
6834       Mask1[1] = PermMask[1];
6835       Mask1[2] = HiIndex & 1 ? 6 : 4;
6836       Mask1[3] = HiIndex & 1 ? 4 : 6;
6837       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6838     }
6839
6840     Mask1[0] = HiIndex & 1 ? 2 : 0;
6841     Mask1[1] = HiIndex & 1 ? 0 : 2;
6842     Mask1[2] = PermMask[2];
6843     Mask1[3] = PermMask[3];
6844     if (Mask1[2] >= 0)
6845       Mask1[2] += 4;
6846     if (Mask1[3] >= 0)
6847       Mask1[3] += 4;
6848     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6849   }
6850
6851   // Break it into (shuffle shuffle_hi, shuffle_lo).
6852   int LoMask[] = { -1, -1, -1, -1 };
6853   int HiMask[] = { -1, -1, -1, -1 };
6854
6855   int *MaskPtr = LoMask;
6856   unsigned MaskIdx = 0;
6857   unsigned LoIdx = 0;
6858   unsigned HiIdx = 2;
6859   for (unsigned i = 0; i != 4; ++i) {
6860     if (i == 2) {
6861       MaskPtr = HiMask;
6862       MaskIdx = 1;
6863       LoIdx = 0;
6864       HiIdx = 2;
6865     }
6866     int Idx = PermMask[i];
6867     if (Idx < 0) {
6868       Locs[i] = std::make_pair(-1, -1);
6869     } else if (Idx < 4) {
6870       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6871       MaskPtr[LoIdx] = Idx;
6872       LoIdx++;
6873     } else {
6874       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6875       MaskPtr[HiIdx] = Idx;
6876       HiIdx++;
6877     }
6878   }
6879
6880   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6881   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6882   int MaskOps[] = { -1, -1, -1, -1 };
6883   for (unsigned i = 0; i != 4; ++i)
6884     if (Locs[i].first != -1)
6885       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6886   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6887 }
6888
6889 static bool MayFoldVectorLoad(SDValue V) {
6890   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6891     V = V.getOperand(0);
6892
6893   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6894     V = V.getOperand(0);
6895   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6896       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6897     // BUILD_VECTOR (load), undef
6898     V = V.getOperand(0);
6899
6900   return MayFoldLoad(V);
6901 }
6902
6903 static
6904 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6905   EVT VT = Op.getValueType();
6906
6907   // Canonizalize to v2f64.
6908   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6909   return DAG.getNode(ISD::BITCAST, dl, VT,
6910                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6911                                           V1, DAG));
6912 }
6913
6914 static
6915 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6916                         bool HasSSE2) {
6917   SDValue V1 = Op.getOperand(0);
6918   SDValue V2 = Op.getOperand(1);
6919   EVT VT = Op.getValueType();
6920
6921   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6922
6923   if (HasSSE2 && VT == MVT::v2f64)
6924     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6925
6926   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6927   return DAG.getNode(ISD::BITCAST, dl, VT,
6928                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6929                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6930                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6931 }
6932
6933 static
6934 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6935   SDValue V1 = Op.getOperand(0);
6936   SDValue V2 = Op.getOperand(1);
6937   EVT VT = Op.getValueType();
6938
6939   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6940          "unsupported shuffle type");
6941
6942   if (V2.getOpcode() == ISD::UNDEF)
6943     V2 = V1;
6944
6945   // v4i32 or v4f32
6946   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6947 }
6948
6949 static
6950 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6951   SDValue V1 = Op.getOperand(0);
6952   SDValue V2 = Op.getOperand(1);
6953   EVT VT = Op.getValueType();
6954   unsigned NumElems = VT.getVectorNumElements();
6955
6956   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6957   // operand of these instructions is only memory, so check if there's a
6958   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6959   // same masks.
6960   bool CanFoldLoad = false;
6961
6962   // Trivial case, when V2 comes from a load.
6963   if (MayFoldVectorLoad(V2))
6964     CanFoldLoad = true;
6965
6966   // When V1 is a load, it can be folded later into a store in isel, example:
6967   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6968   //    turns into:
6969   //  (MOVLPSmr addr:$src1, VR128:$src2)
6970   // So, recognize this potential and also use MOVLPS or MOVLPD
6971   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6972     CanFoldLoad = true;
6973
6974   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6975   if (CanFoldLoad) {
6976     if (HasSSE2 && NumElems == 2)
6977       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6978
6979     if (NumElems == 4)
6980       // If we don't care about the second element, proceed to use movss.
6981       if (SVOp->getMaskElt(1) != -1)
6982         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6983   }
6984
6985   // movl and movlp will both match v2i64, but v2i64 is never matched by
6986   // movl earlier because we make it strict to avoid messing with the movlp load
6987   // folding logic (see the code above getMOVLP call). Match it here then,
6988   // this is horrible, but will stay like this until we move all shuffle
6989   // matching to x86 specific nodes. Note that for the 1st condition all
6990   // types are matched with movsd.
6991   if (HasSSE2) {
6992     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6993     // as to remove this logic from here, as much as possible
6994     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6995       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6996     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6997   }
6998
6999   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7000
7001   // Invert the operand order and use SHUFPS to match it.
7002   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7003                               getShuffleSHUFImmediate(SVOp), DAG);
7004 }
7005
7006 // Reduce a vector shuffle to zext.
7007 SDValue
7008 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
7009   // PMOVZX is only available from SSE41.
7010   if (!Subtarget->hasSSE41())
7011     return SDValue();
7012
7013   EVT VT = Op.getValueType();
7014
7015   // Only AVX2 support 256-bit vector integer extending.
7016   if (!Subtarget->hasInt256() && VT.is256BitVector())
7017     return SDValue();
7018
7019   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7020   SDLoc DL(Op);
7021   SDValue V1 = Op.getOperand(0);
7022   SDValue V2 = Op.getOperand(1);
7023   unsigned NumElems = VT.getVectorNumElements();
7024
7025   // Extending is an unary operation and the element type of the source vector
7026   // won't be equal to or larger than i64.
7027   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7028       VT.getVectorElementType() == MVT::i64)
7029     return SDValue();
7030
7031   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7032   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7033   while ((1U << Shift) < NumElems) {
7034     if (SVOp->getMaskElt(1U << Shift) == 1)
7035       break;
7036     Shift += 1;
7037     // The maximal ratio is 8, i.e. from i8 to i64.
7038     if (Shift > 3)
7039       return SDValue();
7040   }
7041
7042   // Check the shuffle mask.
7043   unsigned Mask = (1U << Shift) - 1;
7044   for (unsigned i = 0; i != NumElems; ++i) {
7045     int EltIdx = SVOp->getMaskElt(i);
7046     if ((i & Mask) != 0 && EltIdx != -1)
7047       return SDValue();
7048     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7049       return SDValue();
7050   }
7051
7052   LLVMContext *Context = DAG.getContext();
7053   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7054   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
7055   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
7056
7057   if (!isTypeLegal(NVT))
7058     return SDValue();
7059
7060   // Simplify the operand as it's prepared to be fed into shuffle.
7061   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7062   if (V1.getOpcode() == ISD::BITCAST &&
7063       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7064       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7065       V1.getOperand(0)
7066         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
7067     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7068     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7069     ConstantSDNode *CIdx =
7070       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7071     // If it's foldable, i.e. normal load with single use, we will let code
7072     // selection to fold it. Otherwise, we will short the conversion sequence.
7073     if (CIdx && CIdx->getZExtValue() == 0 &&
7074         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7075       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
7076         // The "ext_vec_elt" node is wider than the result node.
7077         // In this case we should extract subvector from V.
7078         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7079         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
7080         EVT FullVT = V.getValueType();
7081         EVT SubVecVT = EVT::getVectorVT(*Context,
7082                                         FullVT.getVectorElementType(),
7083                                         FullVT.getVectorNumElements()/Ratio);
7084         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7085                         DAG.getIntPtrConstant(0));
7086       }
7087       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
7088     }
7089   }
7090
7091   return DAG.getNode(ISD::BITCAST, DL, VT,
7092                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7093 }
7094
7095 SDValue
7096 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
7097   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7098   MVT VT = Op.getValueType().getSimpleVT();
7099   SDLoc dl(Op);
7100   SDValue V1 = Op.getOperand(0);
7101   SDValue V2 = Op.getOperand(1);
7102
7103   if (isZeroShuffle(SVOp))
7104     return getZeroVector(VT, Subtarget, DAG, dl);
7105
7106   // Handle splat operations
7107   if (SVOp->isSplat()) {
7108     // Use vbroadcast whenever the splat comes from a foldable load
7109     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
7110     if (Broadcast.getNode())
7111       return Broadcast;
7112   }
7113
7114   // Check integer expanding shuffles.
7115   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
7116   if (NewOp.getNode())
7117     return NewOp;
7118
7119   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7120   // do it!
7121   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7122       VT == MVT::v16i16 || VT == MVT::v32i8) {
7123     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7124     if (NewOp.getNode())
7125       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7126   } else if ((VT == MVT::v4i32 ||
7127              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7128     // FIXME: Figure out a cleaner way to do this.
7129     // Try to make use of movq to zero out the top part.
7130     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7131       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7132       if (NewOp.getNode()) {
7133         MVT NewVT = NewOp.getValueType().getSimpleVT();
7134         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7135                                NewVT, true, false))
7136           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7137                               DAG, Subtarget, dl);
7138       }
7139     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7140       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7141       if (NewOp.getNode()) {
7142         MVT NewVT = NewOp.getValueType().getSimpleVT();
7143         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7144           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7145                               DAG, Subtarget, dl);
7146       }
7147     }
7148   }
7149   return SDValue();
7150 }
7151
7152 SDValue
7153 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7154   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7155   SDValue V1 = Op.getOperand(0);
7156   SDValue V2 = Op.getOperand(1);
7157   MVT VT = Op.getValueType().getSimpleVT();
7158   SDLoc dl(Op);
7159   unsigned NumElems = VT.getVectorNumElements();
7160   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7161   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7162   bool V1IsSplat = false;
7163   bool V2IsSplat = false;
7164   bool HasSSE2 = Subtarget->hasSSE2();
7165   bool HasFp256    = Subtarget->hasFp256();
7166   bool HasInt256   = Subtarget->hasInt256();
7167   MachineFunction &MF = DAG.getMachineFunction();
7168   bool OptForSize = MF.getFunction()->getAttributes().
7169     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7170
7171   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7172
7173   if (V1IsUndef && V2IsUndef)
7174     return DAG.getUNDEF(VT);
7175
7176   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
7177
7178   // Vector shuffle lowering takes 3 steps:
7179   //
7180   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7181   //    narrowing and commutation of operands should be handled.
7182   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7183   //    shuffle nodes.
7184   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7185   //    so the shuffle can be broken into other shuffles and the legalizer can
7186   //    try the lowering again.
7187   //
7188   // The general idea is that no vector_shuffle operation should be left to
7189   // be matched during isel, all of them must be converted to a target specific
7190   // node here.
7191
7192   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7193   // narrowing and commutation of operands should be handled. The actual code
7194   // doesn't include all of those, work in progress...
7195   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
7196   if (NewOp.getNode())
7197     return NewOp;
7198
7199   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7200
7201   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7202   // unpckh_undef). Only use pshufd if speed is more important than size.
7203   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7204     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7205   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7206     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7207
7208   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7209       V2IsUndef && MayFoldVectorLoad(V1))
7210     return getMOVDDup(Op, dl, V1, DAG);
7211
7212   if (isMOVHLPS_v_undef_Mask(M, VT))
7213     return getMOVHighToLow(Op, dl, DAG);
7214
7215   // Use to match splats
7216   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7217       (VT == MVT::v2f64 || VT == MVT::v2i64))
7218     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7219
7220   if (isPSHUFDMask(M, VT)) {
7221     // The actual implementation will match the mask in the if above and then
7222     // during isel it can match several different instructions, not only pshufd
7223     // as its name says, sad but true, emulate the behavior for now...
7224     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7225       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7226
7227     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7228
7229     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7230       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7231
7232     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7233       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7234                                   DAG);
7235
7236     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7237                                 TargetMask, DAG);
7238   }
7239
7240   if (isPALIGNRMask(M, VT, Subtarget))
7241     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7242                                 getShufflePALIGNRImmediate(SVOp),
7243                                 DAG);
7244
7245   // Check if this can be converted into a logical shift.
7246   bool isLeft = false;
7247   unsigned ShAmt = 0;
7248   SDValue ShVal;
7249   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7250   if (isShift && ShVal.hasOneUse()) {
7251     // If the shifted value has multiple uses, it may be cheaper to use
7252     // v_set0 + movlhps or movhlps, etc.
7253     MVT EltVT = VT.getVectorElementType();
7254     ShAmt *= EltVT.getSizeInBits();
7255     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7256   }
7257
7258   if (isMOVLMask(M, VT)) {
7259     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7260       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7261     if (!isMOVLPMask(M, VT)) {
7262       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7263         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7264
7265       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7266         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7267     }
7268   }
7269
7270   // FIXME: fold these into legal mask.
7271   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7272     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7273
7274   if (isMOVHLPSMask(M, VT))
7275     return getMOVHighToLow(Op, dl, DAG);
7276
7277   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7278     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7279
7280   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7281     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7282
7283   if (isMOVLPMask(M, VT))
7284     return getMOVLP(Op, dl, DAG, HasSSE2);
7285
7286   if (ShouldXformToMOVHLPS(M, VT) ||
7287       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7288     return CommuteVectorShuffle(SVOp, DAG);
7289
7290   if (isShift) {
7291     // No better options. Use a vshldq / vsrldq.
7292     MVT EltVT = VT.getVectorElementType();
7293     ShAmt *= EltVT.getSizeInBits();
7294     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7295   }
7296
7297   bool Commuted = false;
7298   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7299   // 1,1,1,1 -> v8i16 though.
7300   V1IsSplat = isSplatVector(V1.getNode());
7301   V2IsSplat = isSplatVector(V2.getNode());
7302
7303   // Canonicalize the splat or undef, if present, to be on the RHS.
7304   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7305     CommuteVectorShuffleMask(M, NumElems);
7306     std::swap(V1, V2);
7307     std::swap(V1IsSplat, V2IsSplat);
7308     Commuted = true;
7309   }
7310
7311   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7312     // Shuffling low element of v1 into undef, just return v1.
7313     if (V2IsUndef)
7314       return V1;
7315     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7316     // the instruction selector will not match, so get a canonical MOVL with
7317     // swapped operands to undo the commute.
7318     return getMOVL(DAG, dl, VT, V2, V1);
7319   }
7320
7321   if (isUNPCKLMask(M, VT, HasInt256))
7322     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7323
7324   if (isUNPCKHMask(M, VT, HasInt256))
7325     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7326
7327   if (V2IsSplat) {
7328     // Normalize mask so all entries that point to V2 points to its first
7329     // element then try to match unpck{h|l} again. If match, return a
7330     // new vector_shuffle with the corrected mask.p
7331     SmallVector<int, 8> NewMask(M.begin(), M.end());
7332     NormalizeMask(NewMask, NumElems);
7333     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7334       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7335     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7336       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7337   }
7338
7339   if (Commuted) {
7340     // Commute is back and try unpck* again.
7341     // FIXME: this seems wrong.
7342     CommuteVectorShuffleMask(M, NumElems);
7343     std::swap(V1, V2);
7344     std::swap(V1IsSplat, V2IsSplat);
7345     Commuted = false;
7346
7347     if (isUNPCKLMask(M, VT, HasInt256))
7348       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7349
7350     if (isUNPCKHMask(M, VT, HasInt256))
7351       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7352   }
7353
7354   // Normalize the node to match x86 shuffle ops if needed
7355   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7356     return CommuteVectorShuffle(SVOp, DAG);
7357
7358   // The checks below are all present in isShuffleMaskLegal, but they are
7359   // inlined here right now to enable us to directly emit target specific
7360   // nodes, and remove one by one until they don't return Op anymore.
7361
7362   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7363       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7364     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7365       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7366   }
7367
7368   if (isPSHUFHWMask(M, VT, HasInt256))
7369     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7370                                 getShufflePSHUFHWImmediate(SVOp),
7371                                 DAG);
7372
7373   if (isPSHUFLWMask(M, VT, HasInt256))
7374     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7375                                 getShufflePSHUFLWImmediate(SVOp),
7376                                 DAG);
7377
7378   if (isSHUFPMask(M, VT, HasFp256))
7379     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7380                                 getShuffleSHUFImmediate(SVOp), DAG);
7381
7382   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7383     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7384   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7385     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7386
7387   //===--------------------------------------------------------------------===//
7388   // Generate target specific nodes for 128 or 256-bit shuffles only
7389   // supported in the AVX instruction set.
7390   //
7391
7392   // Handle VMOVDDUPY permutations
7393   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7394     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7395
7396   // Handle VPERMILPS/D* permutations
7397   if (isVPERMILPMask(M, VT, HasFp256)) {
7398     if (HasInt256 && VT == MVT::v8i32)
7399       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7400                                   getShuffleSHUFImmediate(SVOp), DAG);
7401     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7402                                 getShuffleSHUFImmediate(SVOp), DAG);
7403   }
7404
7405   // Handle VPERM2F128/VPERM2I128 permutations
7406   if (isVPERM2X128Mask(M, VT, HasFp256))
7407     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7408                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7409
7410   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7411   if (BlendOp.getNode())
7412     return BlendOp;
7413
7414   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7415     SmallVector<SDValue, 8> permclMask;
7416     for (unsigned i = 0; i != 8; ++i) {
7417       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7418     }
7419     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7420                                &permclMask[0], 8);
7421     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7422     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7423                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7424   }
7425
7426   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7427     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7428                                 getShuffleCLImmediate(SVOp), DAG);
7429
7430   //===--------------------------------------------------------------------===//
7431   // Since no target specific shuffle was selected for this generic one,
7432   // lower it into other known shuffles. FIXME: this isn't true yet, but
7433   // this is the plan.
7434   //
7435
7436   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7437   if (VT == MVT::v8i16) {
7438     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7439     if (NewOp.getNode())
7440       return NewOp;
7441   }
7442
7443   if (VT == MVT::v16i8) {
7444     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7445     if (NewOp.getNode())
7446       return NewOp;
7447   }
7448
7449   if (VT == MVT::v32i8) {
7450     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7451     if (NewOp.getNode())
7452       return NewOp;
7453   }
7454
7455   // Handle all 128-bit wide vectors with 4 elements, and match them with
7456   // several different shuffle types.
7457   if (NumElems == 4 && VT.is128BitVector())
7458     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7459
7460   // Handle general 256-bit shuffles
7461   if (VT.is256BitVector())
7462     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7463
7464   return SDValue();
7465 }
7466
7467 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7468   MVT VT = Op.getValueType().getSimpleVT();
7469   SDLoc dl(Op);
7470
7471   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7472     return SDValue();
7473
7474   if (VT.getSizeInBits() == 8) {
7475     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7476                                   Op.getOperand(0), Op.getOperand(1));
7477     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7478                                   DAG.getValueType(VT));
7479     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7480   }
7481
7482   if (VT.getSizeInBits() == 16) {
7483     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7484     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7485     if (Idx == 0)
7486       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7487                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7488                                      DAG.getNode(ISD::BITCAST, dl,
7489                                                  MVT::v4i32,
7490                                                  Op.getOperand(0)),
7491                                      Op.getOperand(1)));
7492     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7493                                   Op.getOperand(0), Op.getOperand(1));
7494     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7495                                   DAG.getValueType(VT));
7496     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7497   }
7498
7499   if (VT == MVT::f32) {
7500     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7501     // the result back to FR32 register. It's only worth matching if the
7502     // result has a single use which is a store or a bitcast to i32.  And in
7503     // the case of a store, it's not worth it if the index is a constant 0,
7504     // because a MOVSSmr can be used instead, which is smaller and faster.
7505     if (!Op.hasOneUse())
7506       return SDValue();
7507     SDNode *User = *Op.getNode()->use_begin();
7508     if ((User->getOpcode() != ISD::STORE ||
7509          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7510           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7511         (User->getOpcode() != ISD::BITCAST ||
7512          User->getValueType(0) != MVT::i32))
7513       return SDValue();
7514     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7515                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7516                                               Op.getOperand(0)),
7517                                               Op.getOperand(1));
7518     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7519   }
7520
7521   if (VT == MVT::i32 || VT == MVT::i64) {
7522     // ExtractPS/pextrq works with constant index.
7523     if (isa<ConstantSDNode>(Op.getOperand(1)))
7524       return Op;
7525   }
7526   return SDValue();
7527 }
7528
7529 SDValue
7530 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7531                                            SelectionDAG &DAG) const {
7532   SDLoc dl(Op);
7533   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7534     return SDValue();
7535
7536   SDValue Vec = Op.getOperand(0);
7537   MVT VecVT = Vec.getValueType().getSimpleVT();
7538
7539   // If this is a 256-bit vector result, first extract the 128-bit vector and
7540   // then extract the element from the 128-bit vector.
7541   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7542     SDValue Idx = Op.getOperand(1);
7543     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7544
7545     // Get the 128-bit vector.
7546     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7547     EVT EltVT = VecVT.getVectorElementType();
7548
7549     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7550
7551     //if (IdxVal >= NumElems/2)
7552     //  IdxVal -= NumElems/2;
7553     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7554     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7555                        DAG.getConstant(IdxVal, MVT::i32));
7556   }
7557
7558   assert(VecVT.is128BitVector() && "Unexpected vector length");
7559
7560   if (Subtarget->hasSSE41()) {
7561     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7562     if (Res.getNode())
7563       return Res;
7564   }
7565
7566   MVT VT = Op.getValueType().getSimpleVT();
7567   // TODO: handle v16i8.
7568   if (VT.getSizeInBits() == 16) {
7569     SDValue Vec = Op.getOperand(0);
7570     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7571     if (Idx == 0)
7572       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7573                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7574                                      DAG.getNode(ISD::BITCAST, dl,
7575                                                  MVT::v4i32, Vec),
7576                                      Op.getOperand(1)));
7577     // Transform it so it match pextrw which produces a 32-bit result.
7578     MVT EltVT = MVT::i32;
7579     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7580                                   Op.getOperand(0), Op.getOperand(1));
7581     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7582                                   DAG.getValueType(VT));
7583     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7584   }
7585
7586   if (VT.getSizeInBits() == 32) {
7587     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7588     if (Idx == 0)
7589       return Op;
7590
7591     // SHUFPS the element to the lowest double word, then movss.
7592     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7593     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7594     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7595                                        DAG.getUNDEF(VVT), Mask);
7596     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7597                        DAG.getIntPtrConstant(0));
7598   }
7599
7600   if (VT.getSizeInBits() == 64) {
7601     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7602     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7603     //        to match extract_elt for f64.
7604     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7605     if (Idx == 0)
7606       return Op;
7607
7608     // UNPCKHPD the element to the lowest double word, then movsd.
7609     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7610     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7611     int Mask[2] = { 1, -1 };
7612     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7613     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7614                                        DAG.getUNDEF(VVT), Mask);
7615     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7616                        DAG.getIntPtrConstant(0));
7617   }
7618
7619   return SDValue();
7620 }
7621
7622 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7623   MVT VT = Op.getValueType().getSimpleVT();
7624   MVT EltVT = VT.getVectorElementType();
7625   SDLoc dl(Op);
7626
7627   SDValue N0 = Op.getOperand(0);
7628   SDValue N1 = Op.getOperand(1);
7629   SDValue N2 = Op.getOperand(2);
7630
7631   if (!VT.is128BitVector())
7632     return SDValue();
7633
7634   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7635       isa<ConstantSDNode>(N2)) {
7636     unsigned Opc;
7637     if (VT == MVT::v8i16)
7638       Opc = X86ISD::PINSRW;
7639     else if (VT == MVT::v16i8)
7640       Opc = X86ISD::PINSRB;
7641     else
7642       Opc = X86ISD::PINSRB;
7643
7644     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7645     // argument.
7646     if (N1.getValueType() != MVT::i32)
7647       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7648     if (N2.getValueType() != MVT::i32)
7649       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7650     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7651   }
7652
7653   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7654     // Bits [7:6] of the constant are the source select.  This will always be
7655     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7656     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7657     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7658     // Bits [5:4] of the constant are the destination select.  This is the
7659     //  value of the incoming immediate.
7660     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7661     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7662     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7663     // Create this as a scalar to vector..
7664     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7665     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7666   }
7667
7668   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7669     // PINSR* works with constant index.
7670     return Op;
7671   }
7672   return SDValue();
7673 }
7674
7675 SDValue
7676 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7677   MVT VT = Op.getValueType().getSimpleVT();
7678   MVT EltVT = VT.getVectorElementType();
7679
7680   SDLoc dl(Op);
7681   SDValue N0 = Op.getOperand(0);
7682   SDValue N1 = Op.getOperand(1);
7683   SDValue N2 = Op.getOperand(2);
7684
7685   // If this is a 256-bit vector result, first extract the 128-bit vector,
7686   // insert the element into the extracted half and then place it back.
7687   if (VT.is256BitVector() || VT.is512BitVector()) {
7688     if (!isa<ConstantSDNode>(N2))
7689       return SDValue();
7690
7691     // Get the desired 128-bit vector half.
7692     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7693     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7694
7695     // Insert the element into the desired half.
7696     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
7697     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
7698
7699     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7700                     DAG.getConstant(IdxIn128, MVT::i32));
7701
7702     // Insert the changed part back to the 256-bit vector
7703     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7704   }
7705
7706   if (Subtarget->hasSSE41())
7707     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7708
7709   if (EltVT == MVT::i8)
7710     return SDValue();
7711
7712   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7713     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7714     // as its second argument.
7715     if (N1.getValueType() != MVT::i32)
7716       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7717     if (N2.getValueType() != MVT::i32)
7718       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7719     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7720   }
7721   return SDValue();
7722 }
7723
7724 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7725   LLVMContext *Context = DAG.getContext();
7726   SDLoc dl(Op);
7727   MVT OpVT = Op.getValueType().getSimpleVT();
7728
7729   // If this is a 256-bit vector result, first insert into a 128-bit
7730   // vector and then insert into the 256-bit vector.
7731   if (!OpVT.is128BitVector()) {
7732     // Insert into a 128-bit vector.
7733     unsigned SizeFactor = OpVT.getSizeInBits()/128;
7734     EVT VT128 = EVT::getVectorVT(*Context,
7735                                  OpVT.getVectorElementType(),
7736                                  OpVT.getVectorNumElements() / SizeFactor);
7737
7738     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7739
7740     // Insert the 128-bit vector.
7741     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7742   }
7743
7744   if (OpVT == MVT::v1i64 &&
7745       Op.getOperand(0).getValueType() == MVT::i64)
7746     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7747
7748   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7749   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7750   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7751                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7752 }
7753
7754 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7755 // a simple subregister reference or explicit instructions to grab
7756 // upper bits of a vector.
7757 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7758                                       SelectionDAG &DAG) {
7759   SDLoc dl(Op);
7760   SDValue In =  Op.getOperand(0);
7761   SDValue Idx = Op.getOperand(1);
7762   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7763   EVT ResVT   = Op.getValueType();
7764   EVT InVT    = In.getValueType();
7765
7766   if (Subtarget->hasFp256()) {
7767     if (ResVT.is128BitVector() &&
7768         (InVT.is256BitVector() || InVT.is512BitVector()) &&
7769         isa<ConstantSDNode>(Idx)) {
7770       return Extract128BitVector(In, IdxVal, DAG, dl);
7771     }
7772     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
7773         isa<ConstantSDNode>(Idx)) {
7774       return Extract256BitVector(In, IdxVal, DAG, dl);
7775     }
7776   }
7777   return SDValue();
7778 }
7779
7780 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7781 // simple superregister reference or explicit instructions to insert
7782 // the upper bits of a vector.
7783 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7784                                      SelectionDAG &DAG) {
7785   if (Subtarget->hasFp256()) {
7786     SDLoc dl(Op.getNode());
7787     SDValue Vec = Op.getNode()->getOperand(0);
7788     SDValue SubVec = Op.getNode()->getOperand(1);
7789     SDValue Idx = Op.getNode()->getOperand(2);
7790
7791     if ((Op.getNode()->getValueType(0).is256BitVector() ||
7792          Op.getNode()->getValueType(0).is512BitVector()) &&
7793         SubVec.getNode()->getValueType(0).is128BitVector() &&
7794         isa<ConstantSDNode>(Idx)) {
7795       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7796       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7797     }
7798
7799     if (Op.getNode()->getValueType(0).is512BitVector() &&
7800         SubVec.getNode()->getValueType(0).is256BitVector() &&
7801         isa<ConstantSDNode>(Idx)) {
7802       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7803       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
7804     }
7805   }
7806   return SDValue();
7807 }
7808
7809 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7810 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7811 // one of the above mentioned nodes. It has to be wrapped because otherwise
7812 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7813 // be used to form addressing mode. These wrapped nodes will be selected
7814 // into MOV32ri.
7815 SDValue
7816 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7817   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7818
7819   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7820   // global base reg.
7821   unsigned char OpFlag = 0;
7822   unsigned WrapperKind = X86ISD::Wrapper;
7823   CodeModel::Model M = getTargetMachine().getCodeModel();
7824
7825   if (Subtarget->isPICStyleRIPRel() &&
7826       (M == CodeModel::Small || M == CodeModel::Kernel))
7827     WrapperKind = X86ISD::WrapperRIP;
7828   else if (Subtarget->isPICStyleGOT())
7829     OpFlag = X86II::MO_GOTOFF;
7830   else if (Subtarget->isPICStyleStubPIC())
7831     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7832
7833   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7834                                              CP->getAlignment(),
7835                                              CP->getOffset(), OpFlag);
7836   SDLoc DL(CP);
7837   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7838   // With PIC, the address is actually $g + Offset.
7839   if (OpFlag) {
7840     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7841                          DAG.getNode(X86ISD::GlobalBaseReg,
7842                                      SDLoc(), getPointerTy()),
7843                          Result);
7844   }
7845
7846   return Result;
7847 }
7848
7849 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7850   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7851
7852   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7853   // global base reg.
7854   unsigned char OpFlag = 0;
7855   unsigned WrapperKind = X86ISD::Wrapper;
7856   CodeModel::Model M = getTargetMachine().getCodeModel();
7857
7858   if (Subtarget->isPICStyleRIPRel() &&
7859       (M == CodeModel::Small || M == CodeModel::Kernel))
7860     WrapperKind = X86ISD::WrapperRIP;
7861   else if (Subtarget->isPICStyleGOT())
7862     OpFlag = X86II::MO_GOTOFF;
7863   else if (Subtarget->isPICStyleStubPIC())
7864     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7865
7866   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7867                                           OpFlag);
7868   SDLoc DL(JT);
7869   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7870
7871   // With PIC, the address is actually $g + Offset.
7872   if (OpFlag)
7873     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7874                          DAG.getNode(X86ISD::GlobalBaseReg,
7875                                      SDLoc(), getPointerTy()),
7876                          Result);
7877
7878   return Result;
7879 }
7880
7881 SDValue
7882 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7883   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7884
7885   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7886   // global base reg.
7887   unsigned char OpFlag = 0;
7888   unsigned WrapperKind = X86ISD::Wrapper;
7889   CodeModel::Model M = getTargetMachine().getCodeModel();
7890
7891   if (Subtarget->isPICStyleRIPRel() &&
7892       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7893     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7894       OpFlag = X86II::MO_GOTPCREL;
7895     WrapperKind = X86ISD::WrapperRIP;
7896   } else if (Subtarget->isPICStyleGOT()) {
7897     OpFlag = X86II::MO_GOT;
7898   } else if (Subtarget->isPICStyleStubPIC()) {
7899     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7900   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7901     OpFlag = X86II::MO_DARWIN_NONLAZY;
7902   }
7903
7904   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7905
7906   SDLoc DL(Op);
7907   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7908
7909   // With PIC, the address is actually $g + Offset.
7910   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7911       !Subtarget->is64Bit()) {
7912     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7913                          DAG.getNode(X86ISD::GlobalBaseReg,
7914                                      SDLoc(), getPointerTy()),
7915                          Result);
7916   }
7917
7918   // For symbols that require a load from a stub to get the address, emit the
7919   // load.
7920   if (isGlobalStubReference(OpFlag))
7921     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7922                          MachinePointerInfo::getGOT(), false, false, false, 0);
7923
7924   return Result;
7925 }
7926
7927 SDValue
7928 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7929   // Create the TargetBlockAddressAddress node.
7930   unsigned char OpFlags =
7931     Subtarget->ClassifyBlockAddressReference();
7932   CodeModel::Model M = getTargetMachine().getCodeModel();
7933   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7934   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7935   SDLoc dl(Op);
7936   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7937                                              OpFlags);
7938
7939   if (Subtarget->isPICStyleRIPRel() &&
7940       (M == CodeModel::Small || M == CodeModel::Kernel))
7941     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7942   else
7943     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7944
7945   // With PIC, the address is actually $g + Offset.
7946   if (isGlobalRelativeToPICBase(OpFlags)) {
7947     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7948                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7949                          Result);
7950   }
7951
7952   return Result;
7953 }
7954
7955 SDValue
7956 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7957                                       int64_t Offset, SelectionDAG &DAG) const {
7958   // Create the TargetGlobalAddress node, folding in the constant
7959   // offset if it is legal.
7960   unsigned char OpFlags =
7961     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7962   CodeModel::Model M = getTargetMachine().getCodeModel();
7963   SDValue Result;
7964   if (OpFlags == X86II::MO_NO_FLAG &&
7965       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7966     // A direct static reference to a global.
7967     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7968     Offset = 0;
7969   } else {
7970     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7971   }
7972
7973   if (Subtarget->isPICStyleRIPRel() &&
7974       (M == CodeModel::Small || M == CodeModel::Kernel))
7975     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7976   else
7977     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7978
7979   // With PIC, the address is actually $g + Offset.
7980   if (isGlobalRelativeToPICBase(OpFlags)) {
7981     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7982                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7983                          Result);
7984   }
7985
7986   // For globals that require a load from a stub to get the address, emit the
7987   // load.
7988   if (isGlobalStubReference(OpFlags))
7989     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7990                          MachinePointerInfo::getGOT(), false, false, false, 0);
7991
7992   // If there was a non-zero offset that we didn't fold, create an explicit
7993   // addition for it.
7994   if (Offset != 0)
7995     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7996                          DAG.getConstant(Offset, getPointerTy()));
7997
7998   return Result;
7999 }
8000
8001 SDValue
8002 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8003   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8004   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8005   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8006 }
8007
8008 static SDValue
8009 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8010            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8011            unsigned char OperandFlags, bool LocalDynamic = false) {
8012   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8013   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8014   SDLoc dl(GA);
8015   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8016                                            GA->getValueType(0),
8017                                            GA->getOffset(),
8018                                            OperandFlags);
8019
8020   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8021                                            : X86ISD::TLSADDR;
8022
8023   if (InFlag) {
8024     SDValue Ops[] = { Chain,  TGA, *InFlag };
8025     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8026   } else {
8027     SDValue Ops[]  = { Chain, TGA };
8028     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
8029   }
8030
8031   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8032   MFI->setAdjustsStack(true);
8033
8034   SDValue Flag = Chain.getValue(1);
8035   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8036 }
8037
8038 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8039 static SDValue
8040 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8041                                 const EVT PtrVT) {
8042   SDValue InFlag;
8043   SDLoc dl(GA);  // ? function entry point might be better
8044   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8045                                    DAG.getNode(X86ISD::GlobalBaseReg,
8046                                                SDLoc(), PtrVT), InFlag);
8047   InFlag = Chain.getValue(1);
8048
8049   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8050 }
8051
8052 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8053 static SDValue
8054 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8055                                 const EVT PtrVT) {
8056   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
8057                     X86::RAX, X86II::MO_TLSGD);
8058 }
8059
8060 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8061                                            SelectionDAG &DAG,
8062                                            const EVT PtrVT,
8063                                            bool is64Bit) {
8064   SDLoc dl(GA);
8065
8066   // Get the start address of the TLS block for this module.
8067   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8068       .getInfo<X86MachineFunctionInfo>();
8069   MFI->incNumLocalDynamicTLSAccesses();
8070
8071   SDValue Base;
8072   if (is64Bit) {
8073     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
8074                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8075   } else {
8076     SDValue InFlag;
8077     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8078         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8079     InFlag = Chain.getValue(1);
8080     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8081                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8082   }
8083
8084   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8085   // of Base.
8086
8087   // Build x@dtpoff.
8088   unsigned char OperandFlags = X86II::MO_DTPOFF;
8089   unsigned WrapperKind = X86ISD::Wrapper;
8090   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8091                                            GA->getValueType(0),
8092                                            GA->getOffset(), OperandFlags);
8093   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8094
8095   // Add x@dtpoff with the base.
8096   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8097 }
8098
8099 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8100 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8101                                    const EVT PtrVT, TLSModel::Model model,
8102                                    bool is64Bit, bool isPIC) {
8103   SDLoc dl(GA);
8104
8105   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8106   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8107                                                          is64Bit ? 257 : 256));
8108
8109   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
8110                                       DAG.getIntPtrConstant(0),
8111                                       MachinePointerInfo(Ptr),
8112                                       false, false, false, 0);
8113
8114   unsigned char OperandFlags = 0;
8115   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8116   // initialexec.
8117   unsigned WrapperKind = X86ISD::Wrapper;
8118   if (model == TLSModel::LocalExec) {
8119     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8120   } else if (model == TLSModel::InitialExec) {
8121     if (is64Bit) {
8122       OperandFlags = X86II::MO_GOTTPOFF;
8123       WrapperKind = X86ISD::WrapperRIP;
8124     } else {
8125       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8126     }
8127   } else {
8128     llvm_unreachable("Unexpected model");
8129   }
8130
8131   // emit "addl x@ntpoff,%eax" (local exec)
8132   // or "addl x@indntpoff,%eax" (initial exec)
8133   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8134   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8135                                            GA->getValueType(0),
8136                                            GA->getOffset(), OperandFlags);
8137   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8138
8139   if (model == TLSModel::InitialExec) {
8140     if (isPIC && !is64Bit) {
8141       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8142                           DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8143                            Offset);
8144     }
8145
8146     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8147                          MachinePointerInfo::getGOT(), false, false, false,
8148                          0);
8149   }
8150
8151   // The address of the thread local variable is the add of the thread
8152   // pointer with the offset of the variable.
8153   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8154 }
8155
8156 SDValue
8157 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8158
8159   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8160   const GlobalValue *GV = GA->getGlobal();
8161
8162   if (Subtarget->isTargetELF()) {
8163     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8164
8165     switch (model) {
8166       case TLSModel::GeneralDynamic:
8167         if (Subtarget->is64Bit())
8168           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8169         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8170       case TLSModel::LocalDynamic:
8171         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8172                                            Subtarget->is64Bit());
8173       case TLSModel::InitialExec:
8174       case TLSModel::LocalExec:
8175         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8176                                    Subtarget->is64Bit(),
8177                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8178     }
8179     llvm_unreachable("Unknown TLS model.");
8180   }
8181
8182   if (Subtarget->isTargetDarwin()) {
8183     // Darwin only has one model of TLS.  Lower to that.
8184     unsigned char OpFlag = 0;
8185     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8186                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8187
8188     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8189     // global base reg.
8190     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8191                   !Subtarget->is64Bit();
8192     if (PIC32)
8193       OpFlag = X86II::MO_TLVP_PIC_BASE;
8194     else
8195       OpFlag = X86II::MO_TLVP;
8196     SDLoc DL(Op);
8197     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8198                                                 GA->getValueType(0),
8199                                                 GA->getOffset(), OpFlag);
8200     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8201
8202     // With PIC32, the address is actually $g + Offset.
8203     if (PIC32)
8204       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8205                            DAG.getNode(X86ISD::GlobalBaseReg,
8206                                        SDLoc(), getPointerTy()),
8207                            Offset);
8208
8209     // Lowering the machine isd will make sure everything is in the right
8210     // location.
8211     SDValue Chain = DAG.getEntryNode();
8212     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8213     SDValue Args[] = { Chain, Offset };
8214     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
8215
8216     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8217     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8218     MFI->setAdjustsStack(true);
8219
8220     // And our return value (tls address) is in the standard call return value
8221     // location.
8222     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8223     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8224                               Chain.getValue(1));
8225   }
8226
8227   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
8228     // Just use the implicit TLS architecture
8229     // Need to generate someting similar to:
8230     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8231     //                                  ; from TEB
8232     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8233     //   mov     rcx, qword [rdx+rcx*8]
8234     //   mov     eax, .tls$:tlsvar
8235     //   [rax+rcx] contains the address
8236     // Windows 64bit: gs:0x58
8237     // Windows 32bit: fs:__tls_array
8238
8239     // If GV is an alias then use the aliasee for determining
8240     // thread-localness.
8241     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8242       GV = GA->resolveAliasedGlobal(false);
8243     SDLoc dl(GA);
8244     SDValue Chain = DAG.getEntryNode();
8245
8246     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8247     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8248     // use its literal value of 0x2C.
8249     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8250                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8251                                                              256)
8252                                         : Type::getInt32PtrTy(*DAG.getContext(),
8253                                                               257));
8254
8255     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
8256       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
8257         DAG.getExternalSymbol("_tls_array", getPointerTy()));
8258
8259     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8260                                         MachinePointerInfo(Ptr),
8261                                         false, false, false, 0);
8262
8263     // Load the _tls_index variable
8264     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8265     if (Subtarget->is64Bit())
8266       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8267                            IDX, MachinePointerInfo(), MVT::i32,
8268                            false, false, 0);
8269     else
8270       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8271                         false, false, false, 0);
8272
8273     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8274                                     getPointerTy());
8275     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8276
8277     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8278     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8279                       false, false, false, 0);
8280
8281     // Get the offset of start of .tls section
8282     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8283                                              GA->getValueType(0),
8284                                              GA->getOffset(), X86II::MO_SECREL);
8285     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8286
8287     // The address of the thread local variable is the add of the thread
8288     // pointer with the offset of the variable.
8289     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8290   }
8291
8292   llvm_unreachable("TLS not implemented for this target.");
8293 }
8294
8295 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8296 /// and take a 2 x i32 value to shift plus a shift amount.
8297 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
8298   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8299   EVT VT = Op.getValueType();
8300   unsigned VTBits = VT.getSizeInBits();
8301   SDLoc dl(Op);
8302   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8303   SDValue ShOpLo = Op.getOperand(0);
8304   SDValue ShOpHi = Op.getOperand(1);
8305   SDValue ShAmt  = Op.getOperand(2);
8306   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8307                                      DAG.getConstant(VTBits - 1, MVT::i8))
8308                        : DAG.getConstant(0, VT);
8309
8310   SDValue Tmp2, Tmp3;
8311   if (Op.getOpcode() == ISD::SHL_PARTS) {
8312     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8313     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
8314   } else {
8315     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8316     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
8317   }
8318
8319   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8320                                 DAG.getConstant(VTBits, MVT::i8));
8321   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8322                              AndNode, DAG.getConstant(0, MVT::i8));
8323
8324   SDValue Hi, Lo;
8325   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8326   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8327   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8328
8329   if (Op.getOpcode() == ISD::SHL_PARTS) {
8330     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8331     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8332   } else {
8333     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
8334     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
8335   }
8336
8337   SDValue Ops[2] = { Lo, Hi };
8338   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8339 }
8340
8341 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8342                                            SelectionDAG &DAG) const {
8343   EVT SrcVT = Op.getOperand(0).getValueType();
8344
8345   if (SrcVT.isVector())
8346     return SDValue();
8347
8348   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
8349          "Unknown SINT_TO_FP to lower!");
8350
8351   // These are really Legal; return the operand so the caller accepts it as
8352   // Legal.
8353   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8354     return Op;
8355   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8356       Subtarget->is64Bit()) {
8357     return Op;
8358   }
8359
8360   SDLoc dl(Op);
8361   unsigned Size = SrcVT.getSizeInBits()/8;
8362   MachineFunction &MF = DAG.getMachineFunction();
8363   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8364   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8365   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8366                                StackSlot,
8367                                MachinePointerInfo::getFixedStack(SSFI),
8368                                false, false, 0);
8369   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8370 }
8371
8372 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8373                                      SDValue StackSlot,
8374                                      SelectionDAG &DAG) const {
8375   // Build the FILD
8376   SDLoc DL(Op);
8377   SDVTList Tys;
8378   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8379   if (useSSE)
8380     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8381   else
8382     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8383
8384   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8385
8386   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8387   MachineMemOperand *MMO;
8388   if (FI) {
8389     int SSFI = FI->getIndex();
8390     MMO =
8391       DAG.getMachineFunction()
8392       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8393                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8394   } else {
8395     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8396     StackSlot = StackSlot.getOperand(1);
8397   }
8398   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8399   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8400                                            X86ISD::FILD, DL,
8401                                            Tys, Ops, array_lengthof(Ops),
8402                                            SrcVT, MMO);
8403
8404   if (useSSE) {
8405     Chain = Result.getValue(1);
8406     SDValue InFlag = Result.getValue(2);
8407
8408     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8409     // shouldn't be necessary except that RFP cannot be live across
8410     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8411     MachineFunction &MF = DAG.getMachineFunction();
8412     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8413     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8414     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8415     Tys = DAG.getVTList(MVT::Other);
8416     SDValue Ops[] = {
8417       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8418     };
8419     MachineMemOperand *MMO =
8420       DAG.getMachineFunction()
8421       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8422                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8423
8424     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8425                                     Ops, array_lengthof(Ops),
8426                                     Op.getValueType(), MMO);
8427     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8428                          MachinePointerInfo::getFixedStack(SSFI),
8429                          false, false, false, 0);
8430   }
8431
8432   return Result;
8433 }
8434
8435 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8436 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8437                                                SelectionDAG &DAG) const {
8438   // This algorithm is not obvious. Here it is what we're trying to output:
8439   /*
8440      movq       %rax,  %xmm0
8441      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8442      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8443      #ifdef __SSE3__
8444        haddpd   %xmm0, %xmm0
8445      #else
8446        pshufd   $0x4e, %xmm0, %xmm1
8447        addpd    %xmm1, %xmm0
8448      #endif
8449   */
8450
8451   SDLoc dl(Op);
8452   LLVMContext *Context = DAG.getContext();
8453
8454   // Build some magic constants.
8455   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8456   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8457   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8458
8459   SmallVector<Constant*,2> CV1;
8460   CV1.push_back(
8461     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8462                                       APInt(64, 0x4330000000000000ULL))));
8463   CV1.push_back(
8464     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8465                                       APInt(64, 0x4530000000000000ULL))));
8466   Constant *C1 = ConstantVector::get(CV1);
8467   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8468
8469   // Load the 64-bit value into an XMM register.
8470   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8471                             Op.getOperand(0));
8472   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8473                               MachinePointerInfo::getConstantPool(),
8474                               false, false, false, 16);
8475   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8476                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8477                               CLod0);
8478
8479   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8480                               MachinePointerInfo::getConstantPool(),
8481                               false, false, false, 16);
8482   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8483   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8484   SDValue Result;
8485
8486   if (Subtarget->hasSSE3()) {
8487     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8488     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8489   } else {
8490     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8491     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8492                                            S2F, 0x4E, DAG);
8493     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8494                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8495                          Sub);
8496   }
8497
8498   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8499                      DAG.getIntPtrConstant(0));
8500 }
8501
8502 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8503 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8504                                                SelectionDAG &DAG) const {
8505   SDLoc dl(Op);
8506   // FP constant to bias correct the final result.
8507   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8508                                    MVT::f64);
8509
8510   // Load the 32-bit value into an XMM register.
8511   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8512                              Op.getOperand(0));
8513
8514   // Zero out the upper parts of the register.
8515   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8516
8517   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8518                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8519                      DAG.getIntPtrConstant(0));
8520
8521   // Or the load with the bias.
8522   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8523                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8524                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8525                                                    MVT::v2f64, Load)),
8526                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8527                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8528                                                    MVT::v2f64, Bias)));
8529   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8530                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8531                    DAG.getIntPtrConstant(0));
8532
8533   // Subtract the bias.
8534   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8535
8536   // Handle final rounding.
8537   EVT DestVT = Op.getValueType();
8538
8539   if (DestVT.bitsLT(MVT::f64))
8540     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8541                        DAG.getIntPtrConstant(0));
8542   if (DestVT.bitsGT(MVT::f64))
8543     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8544
8545   // Handle final rounding.
8546   return Sub;
8547 }
8548
8549 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8550                                                SelectionDAG &DAG) const {
8551   SDValue N0 = Op.getOperand(0);
8552   EVT SVT = N0.getValueType();
8553   SDLoc dl(Op);
8554
8555   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8556           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8557          "Custom UINT_TO_FP is not supported!");
8558
8559   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8560                              SVT.getVectorNumElements());
8561   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8562                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8563 }
8564
8565 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8566                                            SelectionDAG &DAG) const {
8567   SDValue N0 = Op.getOperand(0);
8568   SDLoc dl(Op);
8569
8570   if (Op.getValueType().isVector())
8571     return lowerUINT_TO_FP_vec(Op, DAG);
8572
8573   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8574   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8575   // the optimization here.
8576   if (DAG.SignBitIsZero(N0))
8577     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8578
8579   EVT SrcVT = N0.getValueType();
8580   EVT DstVT = Op.getValueType();
8581   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8582     return LowerUINT_TO_FP_i64(Op, DAG);
8583   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8584     return LowerUINT_TO_FP_i32(Op, DAG);
8585   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8586     return SDValue();
8587
8588   // Make a 64-bit buffer, and use it to build an FILD.
8589   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8590   if (SrcVT == MVT::i32) {
8591     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8592     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8593                                      getPointerTy(), StackSlot, WordOff);
8594     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8595                                   StackSlot, MachinePointerInfo(),
8596                                   false, false, 0);
8597     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8598                                   OffsetSlot, MachinePointerInfo(),
8599                                   false, false, 0);
8600     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8601     return Fild;
8602   }
8603
8604   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8605   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8606                                StackSlot, MachinePointerInfo(),
8607                                false, false, 0);
8608   // For i64 source, we need to add the appropriate power of 2 if the input
8609   // was negative.  This is the same as the optimization in
8610   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8611   // we must be careful to do the computation in x87 extended precision, not
8612   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8613   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8614   MachineMemOperand *MMO =
8615     DAG.getMachineFunction()
8616     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8617                           MachineMemOperand::MOLoad, 8, 8);
8618
8619   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8620   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8621   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8622                                          array_lengthof(Ops), MVT::i64, MMO);
8623
8624   APInt FF(32, 0x5F800000ULL);
8625
8626   // Check whether the sign bit is set.
8627   SDValue SignSet = DAG.getSetCC(dl,
8628                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8629                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8630                                  ISD::SETLT);
8631
8632   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8633   SDValue FudgePtr = DAG.getConstantPool(
8634                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8635                                          getPointerTy());
8636
8637   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8638   SDValue Zero = DAG.getIntPtrConstant(0);
8639   SDValue Four = DAG.getIntPtrConstant(4);
8640   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8641                                Zero, Four);
8642   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8643
8644   // Load the value out, extending it from f32 to f80.
8645   // FIXME: Avoid the extend by constructing the right constant pool?
8646   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8647                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8648                                  MVT::f32, false, false, 4);
8649   // Extend everything to 80 bits to force it to be done on x87.
8650   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8651   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8652 }
8653
8654 std::pair<SDValue,SDValue>
8655 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8656                                     bool IsSigned, bool IsReplace) const {
8657   SDLoc DL(Op);
8658
8659   EVT DstTy = Op.getValueType();
8660
8661   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8662     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8663     DstTy = MVT::i64;
8664   }
8665
8666   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8667          DstTy.getSimpleVT() >= MVT::i16 &&
8668          "Unknown FP_TO_INT to lower!");
8669
8670   // These are really Legal.
8671   if (DstTy == MVT::i32 &&
8672       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8673     return std::make_pair(SDValue(), SDValue());
8674   if (Subtarget->is64Bit() &&
8675       DstTy == MVT::i64 &&
8676       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8677     return std::make_pair(SDValue(), SDValue());
8678
8679   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8680   // stack slot, or into the FTOL runtime function.
8681   MachineFunction &MF = DAG.getMachineFunction();
8682   unsigned MemSize = DstTy.getSizeInBits()/8;
8683   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8684   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8685
8686   unsigned Opc;
8687   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8688     Opc = X86ISD::WIN_FTOL;
8689   else
8690     switch (DstTy.getSimpleVT().SimpleTy) {
8691     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8692     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8693     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8694     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8695     }
8696
8697   SDValue Chain = DAG.getEntryNode();
8698   SDValue Value = Op.getOperand(0);
8699   EVT TheVT = Op.getOperand(0).getValueType();
8700   // FIXME This causes a redundant load/store if the SSE-class value is already
8701   // in memory, such as if it is on the callstack.
8702   if (isScalarFPTypeInSSEReg(TheVT)) {
8703     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8704     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8705                          MachinePointerInfo::getFixedStack(SSFI),
8706                          false, false, 0);
8707     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8708     SDValue Ops[] = {
8709       Chain, StackSlot, DAG.getValueType(TheVT)
8710     };
8711
8712     MachineMemOperand *MMO =
8713       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8714                               MachineMemOperand::MOLoad, MemSize, MemSize);
8715     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8716                                     array_lengthof(Ops), DstTy, MMO);
8717     Chain = Value.getValue(1);
8718     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8719     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8720   }
8721
8722   MachineMemOperand *MMO =
8723     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8724                             MachineMemOperand::MOStore, MemSize, MemSize);
8725
8726   if (Opc != X86ISD::WIN_FTOL) {
8727     // Build the FP_TO_INT*_IN_MEM
8728     SDValue Ops[] = { Chain, Value, StackSlot };
8729     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8730                                            Ops, array_lengthof(Ops), DstTy,
8731                                            MMO);
8732     return std::make_pair(FIST, StackSlot);
8733   } else {
8734     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8735       DAG.getVTList(MVT::Other, MVT::Glue),
8736       Chain, Value);
8737     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8738       MVT::i32, ftol.getValue(1));
8739     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8740       MVT::i32, eax.getValue(2));
8741     SDValue Ops[] = { eax, edx };
8742     SDValue pair = IsReplace
8743       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8744       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8745     return std::make_pair(pair, SDValue());
8746   }
8747 }
8748
8749 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8750                               const X86Subtarget *Subtarget) {
8751   MVT VT = Op->getValueType(0).getSimpleVT();
8752   SDValue In = Op->getOperand(0);
8753   MVT InVT = In.getValueType().getSimpleVT();
8754   SDLoc dl(Op);
8755
8756   // Optimize vectors in AVX mode:
8757   //
8758   //   v8i16 -> v8i32
8759   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8760   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8761   //   Concat upper and lower parts.
8762   //
8763   //   v4i32 -> v4i64
8764   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8765   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8766   //   Concat upper and lower parts.
8767   //
8768
8769   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8770       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8771     return SDValue();
8772
8773   if (Subtarget->hasInt256())
8774     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8775
8776   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8777   SDValue Undef = DAG.getUNDEF(InVT);
8778   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8779   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8780   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8781
8782   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8783                              VT.getVectorNumElements()/2);
8784
8785   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8786   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8787
8788   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8789 }
8790
8791 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8792                                            SelectionDAG &DAG) const {
8793   if (Subtarget->hasFp256()) {
8794     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8795     if (Res.getNode())
8796       return Res;
8797   }
8798
8799   return SDValue();
8800 }
8801 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8802                                             SelectionDAG &DAG) const {
8803   SDLoc DL(Op);
8804   MVT VT = Op.getValueType().getSimpleVT();
8805   SDValue In = Op.getOperand(0);
8806   MVT SVT = In.getValueType().getSimpleVT();
8807
8808   if (Subtarget->hasFp256()) {
8809     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8810     if (Res.getNode())
8811       return Res;
8812   }
8813
8814   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8815       VT.getVectorNumElements() != SVT.getVectorNumElements())
8816     return SDValue();
8817
8818   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8819
8820   // AVX2 has better support of integer extending.
8821   if (Subtarget->hasInt256())
8822     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8823
8824   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8825   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8826   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8827                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8828                                                 DAG.getUNDEF(MVT::v8i16),
8829                                                 &Mask[0]));
8830
8831   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8832 }
8833
8834 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8835   SDLoc DL(Op);
8836   MVT VT = Op.getValueType().getSimpleVT();
8837   SDValue In = Op.getOperand(0);
8838   MVT SVT = In.getValueType().getSimpleVT();
8839
8840   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8841     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8842     if (Subtarget->hasInt256()) {
8843       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8844       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8845       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8846                                 ShufMask);
8847       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8848                          DAG.getIntPtrConstant(0));
8849     }
8850
8851     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8852     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8853                                DAG.getIntPtrConstant(0));
8854     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8855                                DAG.getIntPtrConstant(2));
8856
8857     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8858     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8859
8860     // The PSHUFD mask:
8861     static const int ShufMask1[] = {0, 2, 0, 0};
8862     SDValue Undef = DAG.getUNDEF(VT);
8863     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8864     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8865
8866     // The MOVLHPS mask:
8867     static const int ShufMask2[] = {0, 1, 4, 5};
8868     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8869   }
8870
8871   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8872     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8873     if (Subtarget->hasInt256()) {
8874       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8875
8876       SmallVector<SDValue,32> pshufbMask;
8877       for (unsigned i = 0; i < 2; ++i) {
8878         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8879         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8880         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8881         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8882         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8883         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8884         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8885         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8886         for (unsigned j = 0; j < 8; ++j)
8887           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8888       }
8889       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8890                                &pshufbMask[0], 32);
8891       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8892       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8893
8894       static const int ShufMask[] = {0,  2,  -1,  -1};
8895       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8896                                 &ShufMask[0]);
8897       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8898                        DAG.getIntPtrConstant(0));
8899       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8900     }
8901
8902     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8903                                DAG.getIntPtrConstant(0));
8904
8905     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8906                                DAG.getIntPtrConstant(4));
8907
8908     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8909     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8910
8911     // The PSHUFB mask:
8912     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8913                                    -1, -1, -1, -1, -1, -1, -1, -1};
8914
8915     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8916     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8917     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8918
8919     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8920     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8921
8922     // The MOVLHPS Mask:
8923     static const int ShufMask2[] = {0, 1, 4, 5};
8924     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8925     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8926   }
8927
8928   // Handle truncation of V256 to V128 using shuffles.
8929   if (!VT.is128BitVector() || !SVT.is256BitVector())
8930     return SDValue();
8931
8932   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8933          "Invalid op");
8934   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8935
8936   unsigned NumElems = VT.getVectorNumElements();
8937   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8938                              NumElems * 2);
8939
8940   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8941   // Prepare truncation shuffle mask
8942   for (unsigned i = 0; i != NumElems; ++i)
8943     MaskVec[i] = i * 2;
8944   SDValue V = DAG.getVectorShuffle(NVT, DL,
8945                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8946                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8947   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8948                      DAG.getIntPtrConstant(0));
8949 }
8950
8951 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8952                                            SelectionDAG &DAG) const {
8953   MVT VT = Op.getValueType().getSimpleVT();
8954   if (VT.isVector()) {
8955     if (VT == MVT::v8i16)
8956       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8957                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8958                                      MVT::v8i32, Op.getOperand(0)));
8959     return SDValue();
8960   }
8961
8962   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8963     /*IsSigned=*/ true, /*IsReplace=*/ false);
8964   SDValue FIST = Vals.first, StackSlot = Vals.second;
8965   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8966   if (FIST.getNode() == 0) return Op;
8967
8968   if (StackSlot.getNode())
8969     // Load the result.
8970     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8971                        FIST, StackSlot, MachinePointerInfo(),
8972                        false, false, false, 0);
8973
8974   // The node is the result.
8975   return FIST;
8976 }
8977
8978 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8979                                            SelectionDAG &DAG) const {
8980   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8981     /*IsSigned=*/ false, /*IsReplace=*/ false);
8982   SDValue FIST = Vals.first, StackSlot = Vals.second;
8983   assert(FIST.getNode() && "Unexpected failure");
8984
8985   if (StackSlot.getNode())
8986     // Load the result.
8987     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8988                        FIST, StackSlot, MachinePointerInfo(),
8989                        false, false, false, 0);
8990
8991   // The node is the result.
8992   return FIST;
8993 }
8994
8995 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8996   SDLoc DL(Op);
8997   MVT VT = Op.getValueType().getSimpleVT();
8998   SDValue In = Op.getOperand(0);
8999   MVT SVT = In.getValueType().getSimpleVT();
9000
9001   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9002
9003   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9004                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9005                                  In, DAG.getUNDEF(SVT)));
9006 }
9007
9008 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
9009   LLVMContext *Context = DAG.getContext();
9010   SDLoc dl(Op);
9011   MVT VT = Op.getValueType().getSimpleVT();
9012   MVT EltVT = VT;
9013   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9014   if (VT.isVector()) {
9015     EltVT = VT.getVectorElementType();
9016     NumElts = VT.getVectorNumElements();
9017   }
9018   Constant *C;
9019   if (EltVT == MVT::f64)
9020     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9021                                           APInt(64, ~(1ULL << 63))));
9022   else
9023     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9024                                           APInt(32, ~(1U << 31))));
9025   C = ConstantVector::getSplat(NumElts, C);
9026   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9027   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9028   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9029                              MachinePointerInfo::getConstantPool(),
9030                              false, false, false, Alignment);
9031   if (VT.isVector()) {
9032     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9033     return DAG.getNode(ISD::BITCAST, dl, VT,
9034                        DAG.getNode(ISD::AND, dl, ANDVT,
9035                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9036                                                Op.getOperand(0)),
9037                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9038   }
9039   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9040 }
9041
9042 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
9043   LLVMContext *Context = DAG.getContext();
9044   SDLoc dl(Op);
9045   MVT VT = Op.getValueType().getSimpleVT();
9046   MVT EltVT = VT;
9047   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9048   if (VT.isVector()) {
9049     EltVT = VT.getVectorElementType();
9050     NumElts = VT.getVectorNumElements();
9051   }
9052   Constant *C;
9053   if (EltVT == MVT::f64)
9054     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9055                                           APInt(64, 1ULL << 63)));
9056   else
9057     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9058                                           APInt(32, 1U << 31)));
9059   C = ConstantVector::getSplat(NumElts, C);
9060   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
9061   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9062   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9063                              MachinePointerInfo::getConstantPool(),
9064                              false, false, false, Alignment);
9065   if (VT.isVector()) {
9066     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9067     return DAG.getNode(ISD::BITCAST, dl, VT,
9068                        DAG.getNode(ISD::XOR, dl, XORVT,
9069                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9070                                                Op.getOperand(0)),
9071                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9072   }
9073
9074   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9075 }
9076
9077 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
9078   LLVMContext *Context = DAG.getContext();
9079   SDValue Op0 = Op.getOperand(0);
9080   SDValue Op1 = Op.getOperand(1);
9081   SDLoc dl(Op);
9082   MVT VT = Op.getValueType().getSimpleVT();
9083   MVT SrcVT = Op1.getValueType().getSimpleVT();
9084
9085   // If second operand is smaller, extend it first.
9086   if (SrcVT.bitsLT(VT)) {
9087     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9088     SrcVT = VT;
9089   }
9090   // And if it is bigger, shrink it first.
9091   if (SrcVT.bitsGT(VT)) {
9092     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9093     SrcVT = VT;
9094   }
9095
9096   // At this point the operands and the result should have the same
9097   // type, and that won't be f80 since that is not custom lowered.
9098
9099   // First get the sign bit of second operand.
9100   SmallVector<Constant*,4> CV;
9101   if (SrcVT == MVT::f64) {
9102     const fltSemantics &Sem = APFloat::IEEEdouble;
9103     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9104     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9105   } else {
9106     const fltSemantics &Sem = APFloat::IEEEsingle;
9107     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9108     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9109     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9110     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9111   }
9112   Constant *C = ConstantVector::get(CV);
9113   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9114   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9115                               MachinePointerInfo::getConstantPool(),
9116                               false, false, false, 16);
9117   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9118
9119   // Shift sign bit right or left if the two operands have different types.
9120   if (SrcVT.bitsGT(VT)) {
9121     // Op0 is MVT::f32, Op1 is MVT::f64.
9122     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9123     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9124                           DAG.getConstant(32, MVT::i32));
9125     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9126     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9127                           DAG.getIntPtrConstant(0));
9128   }
9129
9130   // Clear first operand sign bit.
9131   CV.clear();
9132   if (VT == MVT::f64) {
9133     const fltSemantics &Sem = APFloat::IEEEdouble;
9134     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9135                                                    APInt(64, ~(1ULL << 63)))));
9136     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9137   } else {
9138     const fltSemantics &Sem = APFloat::IEEEsingle;
9139     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9140                                                    APInt(32, ~(1U << 31)))));
9141     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9142     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9143     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9144   }
9145   C = ConstantVector::get(CV);
9146   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9147   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9148                               MachinePointerInfo::getConstantPool(),
9149                               false, false, false, 16);
9150   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9151
9152   // Or the value with the sign bit.
9153   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9154 }
9155
9156 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9157   SDValue N0 = Op.getOperand(0);
9158   SDLoc dl(Op);
9159   MVT VT = Op.getValueType().getSimpleVT();
9160
9161   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9162   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9163                                   DAG.getConstant(1, VT));
9164   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9165 }
9166
9167 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9168 //
9169 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
9170                                                   SelectionDAG &DAG) const {
9171   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9172
9173   if (!Subtarget->hasSSE41())
9174     return SDValue();
9175
9176   if (!Op->hasOneUse())
9177     return SDValue();
9178
9179   SDNode *N = Op.getNode();
9180   SDLoc DL(N);
9181
9182   SmallVector<SDValue, 8> Opnds;
9183   DenseMap<SDValue, unsigned> VecInMap;
9184   EVT VT = MVT::Other;
9185
9186   // Recognize a special case where a vector is casted into wide integer to
9187   // test all 0s.
9188   Opnds.push_back(N->getOperand(0));
9189   Opnds.push_back(N->getOperand(1));
9190
9191   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9192     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9193     // BFS traverse all OR'd operands.
9194     if (I->getOpcode() == ISD::OR) {
9195       Opnds.push_back(I->getOperand(0));
9196       Opnds.push_back(I->getOperand(1));
9197       // Re-evaluate the number of nodes to be traversed.
9198       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9199       continue;
9200     }
9201
9202     // Quit if a non-EXTRACT_VECTOR_ELT
9203     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9204       return SDValue();
9205
9206     // Quit if without a constant index.
9207     SDValue Idx = I->getOperand(1);
9208     if (!isa<ConstantSDNode>(Idx))
9209       return SDValue();
9210
9211     SDValue ExtractedFromVec = I->getOperand(0);
9212     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9213     if (M == VecInMap.end()) {
9214       VT = ExtractedFromVec.getValueType();
9215       // Quit if not 128/256-bit vector.
9216       if (!VT.is128BitVector() && !VT.is256BitVector())
9217         return SDValue();
9218       // Quit if not the same type.
9219       if (VecInMap.begin() != VecInMap.end() &&
9220           VT != VecInMap.begin()->first.getValueType())
9221         return SDValue();
9222       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9223     }
9224     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9225   }
9226
9227   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9228          "Not extracted from 128-/256-bit vector.");
9229
9230   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9231   SmallVector<SDValue, 8> VecIns;
9232
9233   for (DenseMap<SDValue, unsigned>::const_iterator
9234         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9235     // Quit if not all elements are used.
9236     if (I->second != FullMask)
9237       return SDValue();
9238     VecIns.push_back(I->first);
9239   }
9240
9241   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9242
9243   // Cast all vectors into TestVT for PTEST.
9244   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9245     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9246
9247   // If more than one full vectors are evaluated, OR them first before PTEST.
9248   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9249     // Each iteration will OR 2 nodes and append the result until there is only
9250     // 1 node left, i.e. the final OR'd value of all vectors.
9251     SDValue LHS = VecIns[Slot];
9252     SDValue RHS = VecIns[Slot + 1];
9253     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9254   }
9255
9256   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9257                      VecIns.back(), VecIns.back());
9258 }
9259
9260 /// Emit nodes that will be selected as "test Op0,Op0", or something
9261 /// equivalent.
9262 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
9263                                     SelectionDAG &DAG) const {
9264   SDLoc dl(Op);
9265
9266   // CF and OF aren't always set the way we want. Determine which
9267   // of these we need.
9268   bool NeedCF = false;
9269   bool NeedOF = false;
9270   switch (X86CC) {
9271   default: break;
9272   case X86::COND_A: case X86::COND_AE:
9273   case X86::COND_B: case X86::COND_BE:
9274     NeedCF = true;
9275     break;
9276   case X86::COND_G: case X86::COND_GE:
9277   case X86::COND_L: case X86::COND_LE:
9278   case X86::COND_O: case X86::COND_NO:
9279     NeedOF = true;
9280     break;
9281   }
9282
9283   // See if we can use the EFLAGS value from the operand instead of
9284   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9285   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9286   if (Op.getResNo() != 0 || NeedOF || NeedCF)
9287     // Emit a CMP with 0, which is the TEST pattern.
9288     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9289                        DAG.getConstant(0, Op.getValueType()));
9290
9291   unsigned Opcode = 0;
9292   unsigned NumOperands = 0;
9293
9294   // Truncate operations may prevent the merge of the SETCC instruction
9295   // and the arithmetic intruction before it. Attempt to truncate the operands
9296   // of the arithmetic instruction and use a reduced bit-width instruction.
9297   bool NeedTruncation = false;
9298   SDValue ArithOp = Op;
9299   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9300     SDValue Arith = Op->getOperand(0);
9301     // Both the trunc and the arithmetic op need to have one user each.
9302     if (Arith->hasOneUse())
9303       switch (Arith.getOpcode()) {
9304         default: break;
9305         case ISD::ADD:
9306         case ISD::SUB:
9307         case ISD::AND:
9308         case ISD::OR:
9309         case ISD::XOR: {
9310           NeedTruncation = true;
9311           ArithOp = Arith;
9312         }
9313       }
9314   }
9315
9316   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9317   // which may be the result of a CAST.  We use the variable 'Op', which is the
9318   // non-casted variable when we check for possible users.
9319   switch (ArithOp.getOpcode()) {
9320   case ISD::ADD:
9321     // Due to an isel shortcoming, be conservative if this add is likely to be
9322     // selected as part of a load-modify-store instruction. When the root node
9323     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9324     // uses of other nodes in the match, such as the ADD in this case. This
9325     // leads to the ADD being left around and reselected, with the result being
9326     // two adds in the output.  Alas, even if none our users are stores, that
9327     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9328     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9329     // climbing the DAG back to the root, and it doesn't seem to be worth the
9330     // effort.
9331     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9332          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9333       if (UI->getOpcode() != ISD::CopyToReg &&
9334           UI->getOpcode() != ISD::SETCC &&
9335           UI->getOpcode() != ISD::STORE)
9336         goto default_case;
9337
9338     if (ConstantSDNode *C =
9339         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9340       // An add of one will be selected as an INC.
9341       if (C->getAPIntValue() == 1) {
9342         Opcode = X86ISD::INC;
9343         NumOperands = 1;
9344         break;
9345       }
9346
9347       // An add of negative one (subtract of one) will be selected as a DEC.
9348       if (C->getAPIntValue().isAllOnesValue()) {
9349         Opcode = X86ISD::DEC;
9350         NumOperands = 1;
9351         break;
9352       }
9353     }
9354
9355     // Otherwise use a regular EFLAGS-setting add.
9356     Opcode = X86ISD::ADD;
9357     NumOperands = 2;
9358     break;
9359   case ISD::AND: {
9360     // If the primary and result isn't used, don't bother using X86ISD::AND,
9361     // because a TEST instruction will be better.
9362     bool NonFlagUse = false;
9363     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9364            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9365       SDNode *User = *UI;
9366       unsigned UOpNo = UI.getOperandNo();
9367       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9368         // Look pass truncate.
9369         UOpNo = User->use_begin().getOperandNo();
9370         User = *User->use_begin();
9371       }
9372
9373       if (User->getOpcode() != ISD::BRCOND &&
9374           User->getOpcode() != ISD::SETCC &&
9375           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9376         NonFlagUse = true;
9377         break;
9378       }
9379     }
9380
9381     if (!NonFlagUse)
9382       break;
9383   }
9384     // FALL THROUGH
9385   case ISD::SUB:
9386   case ISD::OR:
9387   case ISD::XOR:
9388     // Due to the ISEL shortcoming noted above, be conservative if this op is
9389     // likely to be selected as part of a load-modify-store instruction.
9390     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9391            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9392       if (UI->getOpcode() == ISD::STORE)
9393         goto default_case;
9394
9395     // Otherwise use a regular EFLAGS-setting instruction.
9396     switch (ArithOp.getOpcode()) {
9397     default: llvm_unreachable("unexpected operator!");
9398     case ISD::SUB: Opcode = X86ISD::SUB; break;
9399     case ISD::XOR: Opcode = X86ISD::XOR; break;
9400     case ISD::AND: Opcode = X86ISD::AND; break;
9401     case ISD::OR: {
9402       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9403         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9404         if (EFLAGS.getNode())
9405           return EFLAGS;
9406       }
9407       Opcode = X86ISD::OR;
9408       break;
9409     }
9410     }
9411
9412     NumOperands = 2;
9413     break;
9414   case X86ISD::ADD:
9415   case X86ISD::SUB:
9416   case X86ISD::INC:
9417   case X86ISD::DEC:
9418   case X86ISD::OR:
9419   case X86ISD::XOR:
9420   case X86ISD::AND:
9421     return SDValue(Op.getNode(), 1);
9422   default:
9423   default_case:
9424     break;
9425   }
9426
9427   // If we found that truncation is beneficial, perform the truncation and
9428   // update 'Op'.
9429   if (NeedTruncation) {
9430     EVT VT = Op.getValueType();
9431     SDValue WideVal = Op->getOperand(0);
9432     EVT WideVT = WideVal.getValueType();
9433     unsigned ConvertedOp = 0;
9434     // Use a target machine opcode to prevent further DAGCombine
9435     // optimizations that may separate the arithmetic operations
9436     // from the setcc node.
9437     switch (WideVal.getOpcode()) {
9438       default: break;
9439       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9440       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9441       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9442       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9443       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9444     }
9445
9446     if (ConvertedOp) {
9447       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9448       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9449         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9450         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9451         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9452       }
9453     }
9454   }
9455
9456   if (Opcode == 0)
9457     // Emit a CMP with 0, which is the TEST pattern.
9458     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9459                        DAG.getConstant(0, Op.getValueType()));
9460
9461   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9462   SmallVector<SDValue, 4> Ops;
9463   for (unsigned i = 0; i != NumOperands; ++i)
9464     Ops.push_back(Op.getOperand(i));
9465
9466   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9467   DAG.ReplaceAllUsesWith(Op, New);
9468   return SDValue(New.getNode(), 1);
9469 }
9470
9471 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9472 /// equivalent.
9473 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9474                                    SelectionDAG &DAG) const {
9475   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9476     if (C->getAPIntValue() == 0)
9477       return EmitTest(Op0, X86CC, DAG);
9478
9479   SDLoc dl(Op0);
9480   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9481        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9482     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9483     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9484     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9485                               Op0, Op1);
9486     return SDValue(Sub.getNode(), 1);
9487   }
9488   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9489 }
9490
9491 /// Convert a comparison if required by the subtarget.
9492 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9493                                                  SelectionDAG &DAG) const {
9494   // If the subtarget does not support the FUCOMI instruction, floating-point
9495   // comparisons have to be converted.
9496   if (Subtarget->hasCMov() ||
9497       Cmp.getOpcode() != X86ISD::CMP ||
9498       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9499       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9500     return Cmp;
9501
9502   // The instruction selector will select an FUCOM instruction instead of
9503   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9504   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9505   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9506   SDLoc dl(Cmp);
9507   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9508   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9509   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9510                             DAG.getConstant(8, MVT::i8));
9511   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9512   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9513 }
9514
9515 static bool isAllOnes(SDValue V) {
9516   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9517   return C && C->isAllOnesValue();
9518 }
9519
9520 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9521 /// if it's possible.
9522 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9523                                      SDLoc dl, SelectionDAG &DAG) const {
9524   SDValue Op0 = And.getOperand(0);
9525   SDValue Op1 = And.getOperand(1);
9526   if (Op0.getOpcode() == ISD::TRUNCATE)
9527     Op0 = Op0.getOperand(0);
9528   if (Op1.getOpcode() == ISD::TRUNCATE)
9529     Op1 = Op1.getOperand(0);
9530
9531   SDValue LHS, RHS;
9532   if (Op1.getOpcode() == ISD::SHL)
9533     std::swap(Op0, Op1);
9534   if (Op0.getOpcode() == ISD::SHL) {
9535     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9536       if (And00C->getZExtValue() == 1) {
9537         // If we looked past a truncate, check that it's only truncating away
9538         // known zeros.
9539         unsigned BitWidth = Op0.getValueSizeInBits();
9540         unsigned AndBitWidth = And.getValueSizeInBits();
9541         if (BitWidth > AndBitWidth) {
9542           APInt Zeros, Ones;
9543           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9544           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9545             return SDValue();
9546         }
9547         LHS = Op1;
9548         RHS = Op0.getOperand(1);
9549       }
9550   } else if (Op1.getOpcode() == ISD::Constant) {
9551     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9552     uint64_t AndRHSVal = AndRHS->getZExtValue();
9553     SDValue AndLHS = Op0;
9554
9555     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9556       LHS = AndLHS.getOperand(0);
9557       RHS = AndLHS.getOperand(1);
9558     }
9559
9560     // Use BT if the immediate can't be encoded in a TEST instruction.
9561     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9562       LHS = AndLHS;
9563       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9564     }
9565   }
9566
9567   if (LHS.getNode()) {
9568     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9569     // instruction.  Since the shift amount is in-range-or-undefined, we know
9570     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9571     // the encoding for the i16 version is larger than the i32 version.
9572     // Also promote i16 to i32 for performance / code size reason.
9573     if (LHS.getValueType() == MVT::i8 ||
9574         LHS.getValueType() == MVT::i16)
9575       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9576
9577     // If the operand types disagree, extend the shift amount to match.  Since
9578     // BT ignores high bits (like shifts) we can use anyextend.
9579     if (LHS.getValueType() != RHS.getValueType())
9580       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9581
9582     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9583     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9584     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9585                        DAG.getConstant(Cond, MVT::i8), BT);
9586   }
9587
9588   return SDValue();
9589 }
9590
9591 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
9592 /// mask CMPs.
9593 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
9594                               SDValue &Op1) {
9595   unsigned SSECC;
9596   bool Swap = false;
9597
9598   // SSE Condition code mapping:
9599   //  0 - EQ
9600   //  1 - LT
9601   //  2 - LE
9602   //  3 - UNORD
9603   //  4 - NEQ
9604   //  5 - NLT
9605   //  6 - NLE
9606   //  7 - ORD
9607   switch (SetCCOpcode) {
9608   default: llvm_unreachable("Unexpected SETCC condition");
9609   case ISD::SETOEQ:
9610   case ISD::SETEQ:  SSECC = 0; break;
9611   case ISD::SETOGT:
9612   case ISD::SETGT:  Swap = true; // Fallthrough
9613   case ISD::SETLT:
9614   case ISD::SETOLT: SSECC = 1; break;
9615   case ISD::SETOGE:
9616   case ISD::SETGE:  Swap = true; // Fallthrough
9617   case ISD::SETLE:
9618   case ISD::SETOLE: SSECC = 2; break;
9619   case ISD::SETUO:  SSECC = 3; break;
9620   case ISD::SETUNE:
9621   case ISD::SETNE:  SSECC = 4; break;
9622   case ISD::SETULE: Swap = true; // Fallthrough
9623   case ISD::SETUGE: SSECC = 5; break;
9624   case ISD::SETULT: Swap = true; // Fallthrough
9625   case ISD::SETUGT: SSECC = 6; break;
9626   case ISD::SETO:   SSECC = 7; break;
9627   case ISD::SETUEQ:
9628   case ISD::SETONE: SSECC = 8; break;
9629   }
9630   if (Swap)
9631     std::swap(Op0, Op1);
9632
9633   return SSECC;
9634 }
9635
9636 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9637 // ones, and then concatenate the result back.
9638 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9639   MVT VT = Op.getValueType().getSimpleVT();
9640
9641   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9642          "Unsupported value type for operation");
9643
9644   unsigned NumElems = VT.getVectorNumElements();
9645   SDLoc dl(Op);
9646   SDValue CC = Op.getOperand(2);
9647
9648   // Extract the LHS vectors
9649   SDValue LHS = Op.getOperand(0);
9650   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9651   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9652
9653   // Extract the RHS vectors
9654   SDValue RHS = Op.getOperand(1);
9655   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9656   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9657
9658   // Issue the operation on the smaller types and concatenate the result back
9659   MVT EltVT = VT.getVectorElementType();
9660   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9661   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9662                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9663                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9664 }
9665
9666 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9667                            SelectionDAG &DAG) {
9668   SDValue Cond;
9669   SDValue Op0 = Op.getOperand(0);
9670   SDValue Op1 = Op.getOperand(1);
9671   SDValue CC = Op.getOperand(2);
9672   MVT VT = Op.getValueType().getSimpleVT();
9673   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9674   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9675   SDLoc dl(Op);
9676
9677   if (isFP) {
9678 #ifndef NDEBUG
9679     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9680     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9681 #endif
9682
9683     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
9684
9685     // In the two special cases we can't handle, emit two comparisons.
9686     if (SSECC == 8) {
9687       unsigned CC0, CC1;
9688       unsigned CombineOpc;
9689       if (SetCCOpcode == ISD::SETUEQ) {
9690         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9691       } else {
9692         assert(SetCCOpcode == ISD::SETONE);
9693         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9694       }
9695
9696       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9697                                  DAG.getConstant(CC0, MVT::i8));
9698       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9699                                  DAG.getConstant(CC1, MVT::i8));
9700       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9701     }
9702     // Handle all other FP comparisons here.
9703     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9704                        DAG.getConstant(SSECC, MVT::i8));
9705   }
9706
9707   // Break 256-bit integer vector compare into smaller ones.
9708   if (VT.is256BitVector() && !Subtarget->hasInt256())
9709     return Lower256IntVSETCC(Op, DAG);
9710
9711   // We are handling one of the integer comparisons here.  Since SSE only has
9712   // GT and EQ comparisons for integer, swapping operands and multiple
9713   // operations may be required for some comparisons.
9714   unsigned Opc;
9715   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
9716   
9717   switch (SetCCOpcode) {
9718   default: llvm_unreachable("Unexpected SETCC condition");
9719   case ISD::SETNE:  Invert = true;
9720   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9721   case ISD::SETLT:  Swap = true;
9722   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9723   case ISD::SETGE:  Swap = true;
9724   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9725   case ISD::SETULT: Swap = true;
9726   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9727   case ISD::SETUGE: Swap = true;
9728   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9729   }
9730   
9731   // Special case: Use min/max operations for SETULE/SETUGE
9732   MVT VET = VT.getVectorElementType();
9733   bool hasMinMax =
9734        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
9735     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
9736   
9737   if (hasMinMax) {
9738     switch (SetCCOpcode) {
9739     default: break;
9740     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
9741     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
9742     }
9743     
9744     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
9745   }
9746   
9747   if (Swap)
9748     std::swap(Op0, Op1);
9749
9750   // Check that the operation in question is available (most are plain SSE2,
9751   // but PCMPGTQ and PCMPEQQ have different requirements).
9752   if (VT == MVT::v2i64) {
9753     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9754       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9755
9756       // First cast everything to the right type.
9757       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9758       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9759
9760       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9761       // bits of the inputs before performing those operations. The lower
9762       // compare is always unsigned.
9763       SDValue SB;
9764       if (FlipSigns) {
9765         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9766       } else {
9767         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9768         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9769         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9770                          Sign, Zero, Sign, Zero);
9771       }
9772       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9773       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9774
9775       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9776       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9777       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9778
9779       // Create masks for only the low parts/high parts of the 64 bit integers.
9780       static const int MaskHi[] = { 1, 1, 3, 3 };
9781       static const int MaskLo[] = { 0, 0, 2, 2 };
9782       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9783       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9784       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9785
9786       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9787       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9788
9789       if (Invert)
9790         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9791
9792       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9793     }
9794
9795     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9796       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9797       // pcmpeqd + pshufd + pand.
9798       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9799
9800       // First cast everything to the right type.
9801       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9802       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9803
9804       // Do the compare.
9805       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9806
9807       // Make sure the lower and upper halves are both all-ones.
9808       static const int Mask[] = { 1, 0, 3, 2 };
9809       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9810       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9811
9812       if (Invert)
9813         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9814
9815       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9816     }
9817   }
9818
9819   // Since SSE has no unsigned integer comparisons, we need to flip the sign
9820   // bits of the inputs before performing those operations.
9821   if (FlipSigns) {
9822     EVT EltVT = VT.getVectorElementType();
9823     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9824     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9825     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9826   }
9827
9828   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9829
9830   // If the logical-not of the result is required, perform that now.
9831   if (Invert)
9832     Result = DAG.getNOT(dl, Result, VT);
9833   
9834   if (MinMax)
9835     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
9836
9837   return Result;
9838 }
9839
9840 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9841
9842   MVT VT = Op.getValueType().getSimpleVT();
9843
9844   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9845
9846   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9847   SDValue Op0 = Op.getOperand(0);
9848   SDValue Op1 = Op.getOperand(1);
9849   SDLoc dl(Op);
9850   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9851
9852   // Optimize to BT if possible.
9853   // Lower (X & (1 << N)) == 0 to BT(X, N).
9854   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9855   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9856   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9857       Op1.getOpcode() == ISD::Constant &&
9858       cast<ConstantSDNode>(Op1)->isNullValue() &&
9859       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9860     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9861     if (NewSetCC.getNode())
9862       return NewSetCC;
9863   }
9864
9865   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9866   // these.
9867   if (Op1.getOpcode() == ISD::Constant &&
9868       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9869        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9870       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9871
9872     // If the input is a setcc, then reuse the input setcc or use a new one with
9873     // the inverted condition.
9874     if (Op0.getOpcode() == X86ISD::SETCC) {
9875       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9876       bool Invert = (CC == ISD::SETNE) ^
9877         cast<ConstantSDNode>(Op1)->isNullValue();
9878       if (!Invert) return Op0;
9879
9880       CCode = X86::GetOppositeBranchCondition(CCode);
9881       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9882                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9883     }
9884   }
9885
9886   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9887   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9888   if (X86CC == X86::COND_INVALID)
9889     return SDValue();
9890
9891   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9892   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9893   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9894                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9895 }
9896
9897 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9898 static bool isX86LogicalCmp(SDValue Op) {
9899   unsigned Opc = Op.getNode()->getOpcode();
9900   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9901       Opc == X86ISD::SAHF)
9902     return true;
9903   if (Op.getResNo() == 1 &&
9904       (Opc == X86ISD::ADD ||
9905        Opc == X86ISD::SUB ||
9906        Opc == X86ISD::ADC ||
9907        Opc == X86ISD::SBB ||
9908        Opc == X86ISD::SMUL ||
9909        Opc == X86ISD::UMUL ||
9910        Opc == X86ISD::INC ||
9911        Opc == X86ISD::DEC ||
9912        Opc == X86ISD::OR ||
9913        Opc == X86ISD::XOR ||
9914        Opc == X86ISD::AND))
9915     return true;
9916
9917   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9918     return true;
9919
9920   return false;
9921 }
9922
9923 static bool isZero(SDValue V) {
9924   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9925   return C && C->isNullValue();
9926 }
9927
9928 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9929   if (V.getOpcode() != ISD::TRUNCATE)
9930     return false;
9931
9932   SDValue VOp0 = V.getOperand(0);
9933   unsigned InBits = VOp0.getValueSizeInBits();
9934   unsigned Bits = V.getValueSizeInBits();
9935   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9936 }
9937
9938 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9939   bool addTest = true;
9940   SDValue Cond  = Op.getOperand(0);
9941   SDValue Op1 = Op.getOperand(1);
9942   SDValue Op2 = Op.getOperand(2);
9943   SDLoc DL(Op);
9944   EVT VT = Op1.getValueType();
9945   SDValue CC;
9946
9947   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
9948   // are available. Otherwise fp cmovs get lowered into a less efficient branch
9949   // sequence later on.
9950   if (Cond.getOpcode() == ISD::SETCC &&
9951       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
9952        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
9953       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
9954     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
9955     int SSECC = translateX86FSETCC(
9956         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
9957
9958     if (SSECC != 8) {
9959       unsigned Opcode = VT == MVT::f32 ? X86ISD::FSETCCss : X86ISD::FSETCCsd;
9960       SDValue Cmp = DAG.getNode(Opcode, DL, VT, CondOp0, CondOp1,
9961                                 DAG.getConstant(SSECC, MVT::i8));
9962       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
9963       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
9964       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
9965     }
9966   }
9967
9968   if (Cond.getOpcode() == ISD::SETCC) {
9969     SDValue NewCond = LowerSETCC(Cond, DAG);
9970     if (NewCond.getNode())
9971       Cond = NewCond;
9972   }
9973
9974   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9975   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9976   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9977   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9978   if (Cond.getOpcode() == X86ISD::SETCC &&
9979       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9980       isZero(Cond.getOperand(1).getOperand(1))) {
9981     SDValue Cmp = Cond.getOperand(1);
9982
9983     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9984
9985     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9986         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9987       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9988
9989       SDValue CmpOp0 = Cmp.getOperand(0);
9990       // Apply further optimizations for special cases
9991       // (select (x != 0), -1, 0) -> neg & sbb
9992       // (select (x == 0), 0, -1) -> neg & sbb
9993       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9994         if (YC->isNullValue() &&
9995             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9996           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9997           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9998                                     DAG.getConstant(0, CmpOp0.getValueType()),
9999                                     CmpOp0);
10000           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10001                                     DAG.getConstant(X86::COND_B, MVT::i8),
10002                                     SDValue(Neg.getNode(), 1));
10003           return Res;
10004         }
10005
10006       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10007                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10008       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10009
10010       SDValue Res =   // Res = 0 or -1.
10011         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10012                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10013
10014       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10015         Res = DAG.getNOT(DL, Res, Res.getValueType());
10016
10017       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10018       if (N2C == 0 || !N2C->isNullValue())
10019         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10020       return Res;
10021     }
10022   }
10023
10024   // Look past (and (setcc_carry (cmp ...)), 1).
10025   if (Cond.getOpcode() == ISD::AND &&
10026       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10027     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10028     if (C && C->getAPIntValue() == 1)
10029       Cond = Cond.getOperand(0);
10030   }
10031
10032   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10033   // setting operand in place of the X86ISD::SETCC.
10034   unsigned CondOpcode = Cond.getOpcode();
10035   if (CondOpcode == X86ISD::SETCC ||
10036       CondOpcode == X86ISD::SETCC_CARRY) {
10037     CC = Cond.getOperand(0);
10038
10039     SDValue Cmp = Cond.getOperand(1);
10040     unsigned Opc = Cmp.getOpcode();
10041     MVT VT = Op.getValueType().getSimpleVT();
10042
10043     bool IllegalFPCMov = false;
10044     if (VT.isFloatingPoint() && !VT.isVector() &&
10045         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10046       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10047
10048     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10049         Opc == X86ISD::BT) { // FIXME
10050       Cond = Cmp;
10051       addTest = false;
10052     }
10053   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10054              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10055              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10056               Cond.getOperand(0).getValueType() != MVT::i8)) {
10057     SDValue LHS = Cond.getOperand(0);
10058     SDValue RHS = Cond.getOperand(1);
10059     unsigned X86Opcode;
10060     unsigned X86Cond;
10061     SDVTList VTs;
10062     switch (CondOpcode) {
10063     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10064     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10065     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10066     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10067     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10068     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10069     default: llvm_unreachable("unexpected overflowing operator");
10070     }
10071     if (CondOpcode == ISD::UMULO)
10072       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10073                           MVT::i32);
10074     else
10075       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10076
10077     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10078
10079     if (CondOpcode == ISD::UMULO)
10080       Cond = X86Op.getValue(2);
10081     else
10082       Cond = X86Op.getValue(1);
10083
10084     CC = DAG.getConstant(X86Cond, MVT::i8);
10085     addTest = false;
10086   }
10087
10088   if (addTest) {
10089     // Look pass the truncate if the high bits are known zero.
10090     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10091         Cond = Cond.getOperand(0);
10092
10093     // We know the result of AND is compared against zero. Try to match
10094     // it to BT.
10095     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10096       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10097       if (NewSetCC.getNode()) {
10098         CC = NewSetCC.getOperand(0);
10099         Cond = NewSetCC.getOperand(1);
10100         addTest = false;
10101       }
10102     }
10103   }
10104
10105   if (addTest) {
10106     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10107     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10108   }
10109
10110   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10111   // a <  b ?  0 : -1 -> RES = setcc_carry
10112   // a >= b ? -1 :  0 -> RES = setcc_carry
10113   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10114   if (Cond.getOpcode() == X86ISD::SUB) {
10115     Cond = ConvertCmpIfNecessary(Cond, DAG);
10116     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10117
10118     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10119         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10120       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10121                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10122       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10123         return DAG.getNOT(DL, Res, Res.getValueType());
10124       return Res;
10125     }
10126   }
10127
10128   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10129   // widen the cmov and push the truncate through. This avoids introducing a new
10130   // branch during isel and doesn't add any extensions.
10131   if (Op.getValueType() == MVT::i8 &&
10132       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10133     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10134     if (T1.getValueType() == T2.getValueType() &&
10135         // Blacklist CopyFromReg to avoid partial register stalls.
10136         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10137       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10138       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10139       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10140     }
10141   }
10142
10143   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10144   // condition is true.
10145   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10146   SDValue Ops[] = { Op2, Op1, CC, Cond };
10147   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
10148 }
10149
10150 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
10151                                             SelectionDAG &DAG) const {
10152   MVT VT = Op->getValueType(0).getSimpleVT();
10153   SDValue In = Op->getOperand(0);
10154   MVT InVT = In.getValueType().getSimpleVT();
10155   SDLoc dl(Op);
10156
10157   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10158       (VT != MVT::v8i32 || InVT != MVT::v8i16))
10159     return SDValue();
10160
10161   if (Subtarget->hasInt256())
10162     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
10163
10164   // Optimize vectors in AVX mode
10165   // Sign extend  v8i16 to v8i32 and
10166   //              v4i32 to v4i64
10167   //
10168   // Divide input vector into two parts
10169   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10170   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10171   // concat the vectors to original VT
10172
10173   unsigned NumElems = InVT.getVectorNumElements();
10174   SDValue Undef = DAG.getUNDEF(InVT);
10175
10176   SmallVector<int,8> ShufMask1(NumElems, -1);
10177   for (unsigned i = 0; i != NumElems/2; ++i)
10178     ShufMask1[i] = i;
10179
10180   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10181
10182   SmallVector<int,8> ShufMask2(NumElems, -1);
10183   for (unsigned i = 0; i != NumElems/2; ++i)
10184     ShufMask2[i] = i + NumElems/2;
10185
10186   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10187
10188   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10189                                 VT.getVectorNumElements()/2);
10190
10191   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
10192   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
10193
10194   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10195 }
10196
10197 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10198 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10199 // from the AND / OR.
10200 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10201   Opc = Op.getOpcode();
10202   if (Opc != ISD::OR && Opc != ISD::AND)
10203     return false;
10204   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10205           Op.getOperand(0).hasOneUse() &&
10206           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10207           Op.getOperand(1).hasOneUse());
10208 }
10209
10210 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10211 // 1 and that the SETCC node has a single use.
10212 static bool isXor1OfSetCC(SDValue Op) {
10213   if (Op.getOpcode() != ISD::XOR)
10214     return false;
10215   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10216   if (N1C && N1C->getAPIntValue() == 1) {
10217     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10218       Op.getOperand(0).hasOneUse();
10219   }
10220   return false;
10221 }
10222
10223 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10224   bool addTest = true;
10225   SDValue Chain = Op.getOperand(0);
10226   SDValue Cond  = Op.getOperand(1);
10227   SDValue Dest  = Op.getOperand(2);
10228   SDLoc dl(Op);
10229   SDValue CC;
10230   bool Inverted = false;
10231
10232   if (Cond.getOpcode() == ISD::SETCC) {
10233     // Check for setcc([su]{add,sub,mul}o == 0).
10234     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10235         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10236         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10237         Cond.getOperand(0).getResNo() == 1 &&
10238         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10239          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10240          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10241          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10242          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10243          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10244       Inverted = true;
10245       Cond = Cond.getOperand(0);
10246     } else {
10247       SDValue NewCond = LowerSETCC(Cond, DAG);
10248       if (NewCond.getNode())
10249         Cond = NewCond;
10250     }
10251   }
10252 #if 0
10253   // FIXME: LowerXALUO doesn't handle these!!
10254   else if (Cond.getOpcode() == X86ISD::ADD  ||
10255            Cond.getOpcode() == X86ISD::SUB  ||
10256            Cond.getOpcode() == X86ISD::SMUL ||
10257            Cond.getOpcode() == X86ISD::UMUL)
10258     Cond = LowerXALUO(Cond, DAG);
10259 #endif
10260
10261   // Look pass (and (setcc_carry (cmp ...)), 1).
10262   if (Cond.getOpcode() == ISD::AND &&
10263       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10264     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10265     if (C && C->getAPIntValue() == 1)
10266       Cond = Cond.getOperand(0);
10267   }
10268
10269   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10270   // setting operand in place of the X86ISD::SETCC.
10271   unsigned CondOpcode = Cond.getOpcode();
10272   if (CondOpcode == X86ISD::SETCC ||
10273       CondOpcode == X86ISD::SETCC_CARRY) {
10274     CC = Cond.getOperand(0);
10275
10276     SDValue Cmp = Cond.getOperand(1);
10277     unsigned Opc = Cmp.getOpcode();
10278     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
10279     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
10280       Cond = Cmp;
10281       addTest = false;
10282     } else {
10283       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
10284       default: break;
10285       case X86::COND_O:
10286       case X86::COND_B:
10287         // These can only come from an arithmetic instruction with overflow,
10288         // e.g. SADDO, UADDO.
10289         Cond = Cond.getNode()->getOperand(1);
10290         addTest = false;
10291         break;
10292       }
10293     }
10294   }
10295   CondOpcode = Cond.getOpcode();
10296   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10297       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10298       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10299        Cond.getOperand(0).getValueType() != MVT::i8)) {
10300     SDValue LHS = Cond.getOperand(0);
10301     SDValue RHS = Cond.getOperand(1);
10302     unsigned X86Opcode;
10303     unsigned X86Cond;
10304     SDVTList VTs;
10305     switch (CondOpcode) {
10306     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10307     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10308     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10309     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10310     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10311     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10312     default: llvm_unreachable("unexpected overflowing operator");
10313     }
10314     if (Inverted)
10315       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
10316     if (CondOpcode == ISD::UMULO)
10317       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10318                           MVT::i32);
10319     else
10320       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10321
10322     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
10323
10324     if (CondOpcode == ISD::UMULO)
10325       Cond = X86Op.getValue(2);
10326     else
10327       Cond = X86Op.getValue(1);
10328
10329     CC = DAG.getConstant(X86Cond, MVT::i8);
10330     addTest = false;
10331   } else {
10332     unsigned CondOpc;
10333     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
10334       SDValue Cmp = Cond.getOperand(0).getOperand(1);
10335       if (CondOpc == ISD::OR) {
10336         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
10337         // two branches instead of an explicit OR instruction with a
10338         // separate test.
10339         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10340             isX86LogicalCmp(Cmp)) {
10341           CC = Cond.getOperand(0).getOperand(0);
10342           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10343                               Chain, Dest, CC, Cmp);
10344           CC = Cond.getOperand(1).getOperand(0);
10345           Cond = Cmp;
10346           addTest = false;
10347         }
10348       } else { // ISD::AND
10349         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
10350         // two branches instead of an explicit AND instruction with a
10351         // separate test. However, we only do this if this block doesn't
10352         // have a fall-through edge, because this requires an explicit
10353         // jmp when the condition is false.
10354         if (Cmp == Cond.getOperand(1).getOperand(1) &&
10355             isX86LogicalCmp(Cmp) &&
10356             Op.getNode()->hasOneUse()) {
10357           X86::CondCode CCode =
10358             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10359           CCode = X86::GetOppositeBranchCondition(CCode);
10360           CC = DAG.getConstant(CCode, MVT::i8);
10361           SDNode *User = *Op.getNode()->use_begin();
10362           // Look for an unconditional branch following this conditional branch.
10363           // We need this because we need to reverse the successors in order
10364           // to implement FCMP_OEQ.
10365           if (User->getOpcode() == ISD::BR) {
10366             SDValue FalseBB = User->getOperand(1);
10367             SDNode *NewBR =
10368               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10369             assert(NewBR == User);
10370             (void)NewBR;
10371             Dest = FalseBB;
10372
10373             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10374                                 Chain, Dest, CC, Cmp);
10375             X86::CondCode CCode =
10376               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
10377             CCode = X86::GetOppositeBranchCondition(CCode);
10378             CC = DAG.getConstant(CCode, MVT::i8);
10379             Cond = Cmp;
10380             addTest = false;
10381           }
10382         }
10383       }
10384     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
10385       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
10386       // It should be transformed during dag combiner except when the condition
10387       // is set by a arithmetics with overflow node.
10388       X86::CondCode CCode =
10389         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
10390       CCode = X86::GetOppositeBranchCondition(CCode);
10391       CC = DAG.getConstant(CCode, MVT::i8);
10392       Cond = Cond.getOperand(0).getOperand(1);
10393       addTest = false;
10394     } else if (Cond.getOpcode() == ISD::SETCC &&
10395                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
10396       // For FCMP_OEQ, we can emit
10397       // two branches instead of an explicit AND instruction with a
10398       // separate test. However, we only do this if this block doesn't
10399       // have a fall-through edge, because this requires an explicit
10400       // jmp when the condition is false.
10401       if (Op.getNode()->hasOneUse()) {
10402         SDNode *User = *Op.getNode()->use_begin();
10403         // Look for an unconditional branch following this conditional branch.
10404         // We need this because we need to reverse the successors in order
10405         // to implement FCMP_OEQ.
10406         if (User->getOpcode() == ISD::BR) {
10407           SDValue FalseBB = User->getOperand(1);
10408           SDNode *NewBR =
10409             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10410           assert(NewBR == User);
10411           (void)NewBR;
10412           Dest = FalseBB;
10413
10414           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10415                                     Cond.getOperand(0), Cond.getOperand(1));
10416           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10417           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10418           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10419                               Chain, Dest, CC, Cmp);
10420           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10421           Cond = Cmp;
10422           addTest = false;
10423         }
10424       }
10425     } else if (Cond.getOpcode() == ISD::SETCC &&
10426                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10427       // For FCMP_UNE, we can emit
10428       // two branches instead of an explicit AND instruction with a
10429       // separate test. However, we only do this if this block doesn't
10430       // have a fall-through edge, because this requires an explicit
10431       // jmp when the condition is false.
10432       if (Op.getNode()->hasOneUse()) {
10433         SDNode *User = *Op.getNode()->use_begin();
10434         // Look for an unconditional branch following this conditional branch.
10435         // We need this because we need to reverse the successors in order
10436         // to implement FCMP_UNE.
10437         if (User->getOpcode() == ISD::BR) {
10438           SDValue FalseBB = User->getOperand(1);
10439           SDNode *NewBR =
10440             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10441           assert(NewBR == User);
10442           (void)NewBR;
10443
10444           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10445                                     Cond.getOperand(0), Cond.getOperand(1));
10446           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10447           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10448           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10449                               Chain, Dest, CC, Cmp);
10450           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10451           Cond = Cmp;
10452           addTest = false;
10453           Dest = FalseBB;
10454         }
10455       }
10456     }
10457   }
10458
10459   if (addTest) {
10460     // Look pass the truncate if the high bits are known zero.
10461     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10462         Cond = Cond.getOperand(0);
10463
10464     // We know the result of AND is compared against zero. Try to match
10465     // it to BT.
10466     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10467       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10468       if (NewSetCC.getNode()) {
10469         CC = NewSetCC.getOperand(0);
10470         Cond = NewSetCC.getOperand(1);
10471         addTest = false;
10472       }
10473     }
10474   }
10475
10476   if (addTest) {
10477     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10478     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10479   }
10480   Cond = ConvertCmpIfNecessary(Cond, DAG);
10481   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10482                      Chain, Dest, CC, Cond);
10483 }
10484
10485 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10486 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10487 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10488 // that the guard pages used by the OS virtual memory manager are allocated in
10489 // correct sequence.
10490 SDValue
10491 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10492                                            SelectionDAG &DAG) const {
10493   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10494           getTargetMachine().Options.EnableSegmentedStacks) &&
10495          "This should be used only on Windows targets or when segmented stacks "
10496          "are being used");
10497   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10498   SDLoc dl(Op);
10499
10500   // Get the inputs.
10501   SDValue Chain = Op.getOperand(0);
10502   SDValue Size  = Op.getOperand(1);
10503   // FIXME: Ensure alignment here
10504
10505   bool Is64Bit = Subtarget->is64Bit();
10506   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10507
10508   if (getTargetMachine().Options.EnableSegmentedStacks) {
10509     MachineFunction &MF = DAG.getMachineFunction();
10510     MachineRegisterInfo &MRI = MF.getRegInfo();
10511
10512     if (Is64Bit) {
10513       // The 64 bit implementation of segmented stacks needs to clobber both r10
10514       // r11. This makes it impossible to use it along with nested parameters.
10515       const Function *F = MF.getFunction();
10516
10517       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10518            I != E; ++I)
10519         if (I->hasNestAttr())
10520           report_fatal_error("Cannot use segmented stacks with functions that "
10521                              "have nested arguments.");
10522     }
10523
10524     const TargetRegisterClass *AddrRegClass =
10525       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10526     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10527     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10528     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10529                                 DAG.getRegister(Vreg, SPTy));
10530     SDValue Ops1[2] = { Value, Chain };
10531     return DAG.getMergeValues(Ops1, 2, dl);
10532   } else {
10533     SDValue Flag;
10534     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10535
10536     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10537     Flag = Chain.getValue(1);
10538     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10539
10540     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10541     Flag = Chain.getValue(1);
10542
10543     const X86RegisterInfo *RegInfo =
10544       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10545     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10546                                SPTy).getValue(1);
10547
10548     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10549     return DAG.getMergeValues(Ops1, 2, dl);
10550   }
10551 }
10552
10553 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10554   MachineFunction &MF = DAG.getMachineFunction();
10555   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10556
10557   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10558   SDLoc DL(Op);
10559
10560   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10561     // vastart just stores the address of the VarArgsFrameIndex slot into the
10562     // memory location argument.
10563     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10564                                    getPointerTy());
10565     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10566                         MachinePointerInfo(SV), false, false, 0);
10567   }
10568
10569   // __va_list_tag:
10570   //   gp_offset         (0 - 6 * 8)
10571   //   fp_offset         (48 - 48 + 8 * 16)
10572   //   overflow_arg_area (point to parameters coming in memory).
10573   //   reg_save_area
10574   SmallVector<SDValue, 8> MemOps;
10575   SDValue FIN = Op.getOperand(1);
10576   // Store gp_offset
10577   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10578                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10579                                                MVT::i32),
10580                                FIN, MachinePointerInfo(SV), false, false, 0);
10581   MemOps.push_back(Store);
10582
10583   // Store fp_offset
10584   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10585                     FIN, DAG.getIntPtrConstant(4));
10586   Store = DAG.getStore(Op.getOperand(0), DL,
10587                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10588                                        MVT::i32),
10589                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10590   MemOps.push_back(Store);
10591
10592   // Store ptr to overflow_arg_area
10593   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10594                     FIN, DAG.getIntPtrConstant(4));
10595   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10596                                     getPointerTy());
10597   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10598                        MachinePointerInfo(SV, 8),
10599                        false, false, 0);
10600   MemOps.push_back(Store);
10601
10602   // Store ptr to reg_save_area.
10603   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10604                     FIN, DAG.getIntPtrConstant(8));
10605   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10606                                     getPointerTy());
10607   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10608                        MachinePointerInfo(SV, 16), false, false, 0);
10609   MemOps.push_back(Store);
10610   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10611                      &MemOps[0], MemOps.size());
10612 }
10613
10614 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10615   assert(Subtarget->is64Bit() &&
10616          "LowerVAARG only handles 64-bit va_arg!");
10617   assert((Subtarget->isTargetLinux() ||
10618           Subtarget->isTargetDarwin()) &&
10619           "Unhandled target in LowerVAARG");
10620   assert(Op.getNode()->getNumOperands() == 4);
10621   SDValue Chain = Op.getOperand(0);
10622   SDValue SrcPtr = Op.getOperand(1);
10623   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10624   unsigned Align = Op.getConstantOperandVal(3);
10625   SDLoc dl(Op);
10626
10627   EVT ArgVT = Op.getNode()->getValueType(0);
10628   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10629   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10630   uint8_t ArgMode;
10631
10632   // Decide which area this value should be read from.
10633   // TODO: Implement the AMD64 ABI in its entirety. This simple
10634   // selection mechanism works only for the basic types.
10635   if (ArgVT == MVT::f80) {
10636     llvm_unreachable("va_arg for f80 not yet implemented");
10637   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10638     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10639   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10640     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10641   } else {
10642     llvm_unreachable("Unhandled argument type in LowerVAARG");
10643   }
10644
10645   if (ArgMode == 2) {
10646     // Sanity Check: Make sure using fp_offset makes sense.
10647     assert(!getTargetMachine().Options.UseSoftFloat &&
10648            !(DAG.getMachineFunction()
10649                 .getFunction()->getAttributes()
10650                 .hasAttribute(AttributeSet::FunctionIndex,
10651                               Attribute::NoImplicitFloat)) &&
10652            Subtarget->hasSSE1());
10653   }
10654
10655   // Insert VAARG_64 node into the DAG
10656   // VAARG_64 returns two values: Variable Argument Address, Chain
10657   SmallVector<SDValue, 11> InstOps;
10658   InstOps.push_back(Chain);
10659   InstOps.push_back(SrcPtr);
10660   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10661   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10662   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10663   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10664   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10665                                           VTs, &InstOps[0], InstOps.size(),
10666                                           MVT::i64,
10667                                           MachinePointerInfo(SV),
10668                                           /*Align=*/0,
10669                                           /*Volatile=*/false,
10670                                           /*ReadMem=*/true,
10671                                           /*WriteMem=*/true);
10672   Chain = VAARG.getValue(1);
10673
10674   // Load the next argument and return it
10675   return DAG.getLoad(ArgVT, dl,
10676                      Chain,
10677                      VAARG,
10678                      MachinePointerInfo(),
10679                      false, false, false, 0);
10680 }
10681
10682 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10683                            SelectionDAG &DAG) {
10684   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10685   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10686   SDValue Chain = Op.getOperand(0);
10687   SDValue DstPtr = Op.getOperand(1);
10688   SDValue SrcPtr = Op.getOperand(2);
10689   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10690   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10691   SDLoc DL(Op);
10692
10693   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10694                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10695                        false,
10696                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10697 }
10698
10699 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10700 // may or may not be a constant. Takes immediate version of shift as input.
10701 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10702                                    SDValue SrcOp, SDValue ShAmt,
10703                                    SelectionDAG &DAG) {
10704   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10705
10706   if (isa<ConstantSDNode>(ShAmt)) {
10707     // Constant may be a TargetConstant. Use a regular constant.
10708     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10709     switch (Opc) {
10710       default: llvm_unreachable("Unknown target vector shift node");
10711       case X86ISD::VSHLI:
10712       case X86ISD::VSRLI:
10713       case X86ISD::VSRAI:
10714         return DAG.getNode(Opc, dl, VT, SrcOp,
10715                            DAG.getConstant(ShiftAmt, MVT::i32));
10716     }
10717   }
10718
10719   // Change opcode to non-immediate version
10720   switch (Opc) {
10721     default: llvm_unreachable("Unknown target vector shift node");
10722     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10723     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10724     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10725   }
10726
10727   // Need to build a vector containing shift amount
10728   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10729   SDValue ShOps[4];
10730   ShOps[0] = ShAmt;
10731   ShOps[1] = DAG.getConstant(0, MVT::i32);
10732   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10733   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10734
10735   // The return type has to be a 128-bit type with the same element
10736   // type as the input type.
10737   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10738   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10739
10740   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10741   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10742 }
10743
10744 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10745   SDLoc dl(Op);
10746   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10747   switch (IntNo) {
10748   default: return SDValue();    // Don't custom lower most intrinsics.
10749   // Comparison intrinsics.
10750   case Intrinsic::x86_sse_comieq_ss:
10751   case Intrinsic::x86_sse_comilt_ss:
10752   case Intrinsic::x86_sse_comile_ss:
10753   case Intrinsic::x86_sse_comigt_ss:
10754   case Intrinsic::x86_sse_comige_ss:
10755   case Intrinsic::x86_sse_comineq_ss:
10756   case Intrinsic::x86_sse_ucomieq_ss:
10757   case Intrinsic::x86_sse_ucomilt_ss:
10758   case Intrinsic::x86_sse_ucomile_ss:
10759   case Intrinsic::x86_sse_ucomigt_ss:
10760   case Intrinsic::x86_sse_ucomige_ss:
10761   case Intrinsic::x86_sse_ucomineq_ss:
10762   case Intrinsic::x86_sse2_comieq_sd:
10763   case Intrinsic::x86_sse2_comilt_sd:
10764   case Intrinsic::x86_sse2_comile_sd:
10765   case Intrinsic::x86_sse2_comigt_sd:
10766   case Intrinsic::x86_sse2_comige_sd:
10767   case Intrinsic::x86_sse2_comineq_sd:
10768   case Intrinsic::x86_sse2_ucomieq_sd:
10769   case Intrinsic::x86_sse2_ucomilt_sd:
10770   case Intrinsic::x86_sse2_ucomile_sd:
10771   case Intrinsic::x86_sse2_ucomigt_sd:
10772   case Intrinsic::x86_sse2_ucomige_sd:
10773   case Intrinsic::x86_sse2_ucomineq_sd: {
10774     unsigned Opc;
10775     ISD::CondCode CC;
10776     switch (IntNo) {
10777     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10778     case Intrinsic::x86_sse_comieq_ss:
10779     case Intrinsic::x86_sse2_comieq_sd:
10780       Opc = X86ISD::COMI;
10781       CC = ISD::SETEQ;
10782       break;
10783     case Intrinsic::x86_sse_comilt_ss:
10784     case Intrinsic::x86_sse2_comilt_sd:
10785       Opc = X86ISD::COMI;
10786       CC = ISD::SETLT;
10787       break;
10788     case Intrinsic::x86_sse_comile_ss:
10789     case Intrinsic::x86_sse2_comile_sd:
10790       Opc = X86ISD::COMI;
10791       CC = ISD::SETLE;
10792       break;
10793     case Intrinsic::x86_sse_comigt_ss:
10794     case Intrinsic::x86_sse2_comigt_sd:
10795       Opc = X86ISD::COMI;
10796       CC = ISD::SETGT;
10797       break;
10798     case Intrinsic::x86_sse_comige_ss:
10799     case Intrinsic::x86_sse2_comige_sd:
10800       Opc = X86ISD::COMI;
10801       CC = ISD::SETGE;
10802       break;
10803     case Intrinsic::x86_sse_comineq_ss:
10804     case Intrinsic::x86_sse2_comineq_sd:
10805       Opc = X86ISD::COMI;
10806       CC = ISD::SETNE;
10807       break;
10808     case Intrinsic::x86_sse_ucomieq_ss:
10809     case Intrinsic::x86_sse2_ucomieq_sd:
10810       Opc = X86ISD::UCOMI;
10811       CC = ISD::SETEQ;
10812       break;
10813     case Intrinsic::x86_sse_ucomilt_ss:
10814     case Intrinsic::x86_sse2_ucomilt_sd:
10815       Opc = X86ISD::UCOMI;
10816       CC = ISD::SETLT;
10817       break;
10818     case Intrinsic::x86_sse_ucomile_ss:
10819     case Intrinsic::x86_sse2_ucomile_sd:
10820       Opc = X86ISD::UCOMI;
10821       CC = ISD::SETLE;
10822       break;
10823     case Intrinsic::x86_sse_ucomigt_ss:
10824     case Intrinsic::x86_sse2_ucomigt_sd:
10825       Opc = X86ISD::UCOMI;
10826       CC = ISD::SETGT;
10827       break;
10828     case Intrinsic::x86_sse_ucomige_ss:
10829     case Intrinsic::x86_sse2_ucomige_sd:
10830       Opc = X86ISD::UCOMI;
10831       CC = ISD::SETGE;
10832       break;
10833     case Intrinsic::x86_sse_ucomineq_ss:
10834     case Intrinsic::x86_sse2_ucomineq_sd:
10835       Opc = X86ISD::UCOMI;
10836       CC = ISD::SETNE;
10837       break;
10838     }
10839
10840     SDValue LHS = Op.getOperand(1);
10841     SDValue RHS = Op.getOperand(2);
10842     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10843     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10844     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10845     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10846                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10847     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10848   }
10849
10850   // Arithmetic intrinsics.
10851   case Intrinsic::x86_sse2_pmulu_dq:
10852   case Intrinsic::x86_avx2_pmulu_dq:
10853     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10854                        Op.getOperand(1), Op.getOperand(2));
10855
10856   // SSE2/AVX2 sub with unsigned saturation intrinsics
10857   case Intrinsic::x86_sse2_psubus_b:
10858   case Intrinsic::x86_sse2_psubus_w:
10859   case Intrinsic::x86_avx2_psubus_b:
10860   case Intrinsic::x86_avx2_psubus_w:
10861     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10862                        Op.getOperand(1), Op.getOperand(2));
10863
10864   // SSE3/AVX horizontal add/sub intrinsics
10865   case Intrinsic::x86_sse3_hadd_ps:
10866   case Intrinsic::x86_sse3_hadd_pd:
10867   case Intrinsic::x86_avx_hadd_ps_256:
10868   case Intrinsic::x86_avx_hadd_pd_256:
10869   case Intrinsic::x86_sse3_hsub_ps:
10870   case Intrinsic::x86_sse3_hsub_pd:
10871   case Intrinsic::x86_avx_hsub_ps_256:
10872   case Intrinsic::x86_avx_hsub_pd_256:
10873   case Intrinsic::x86_ssse3_phadd_w_128:
10874   case Intrinsic::x86_ssse3_phadd_d_128:
10875   case Intrinsic::x86_avx2_phadd_w:
10876   case Intrinsic::x86_avx2_phadd_d:
10877   case Intrinsic::x86_ssse3_phsub_w_128:
10878   case Intrinsic::x86_ssse3_phsub_d_128:
10879   case Intrinsic::x86_avx2_phsub_w:
10880   case Intrinsic::x86_avx2_phsub_d: {
10881     unsigned Opcode;
10882     switch (IntNo) {
10883     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10884     case Intrinsic::x86_sse3_hadd_ps:
10885     case Intrinsic::x86_sse3_hadd_pd:
10886     case Intrinsic::x86_avx_hadd_ps_256:
10887     case Intrinsic::x86_avx_hadd_pd_256:
10888       Opcode = X86ISD::FHADD;
10889       break;
10890     case Intrinsic::x86_sse3_hsub_ps:
10891     case Intrinsic::x86_sse3_hsub_pd:
10892     case Intrinsic::x86_avx_hsub_ps_256:
10893     case Intrinsic::x86_avx_hsub_pd_256:
10894       Opcode = X86ISD::FHSUB;
10895       break;
10896     case Intrinsic::x86_ssse3_phadd_w_128:
10897     case Intrinsic::x86_ssse3_phadd_d_128:
10898     case Intrinsic::x86_avx2_phadd_w:
10899     case Intrinsic::x86_avx2_phadd_d:
10900       Opcode = X86ISD::HADD;
10901       break;
10902     case Intrinsic::x86_ssse3_phsub_w_128:
10903     case Intrinsic::x86_ssse3_phsub_d_128:
10904     case Intrinsic::x86_avx2_phsub_w:
10905     case Intrinsic::x86_avx2_phsub_d:
10906       Opcode = X86ISD::HSUB;
10907       break;
10908     }
10909     return DAG.getNode(Opcode, dl, Op.getValueType(),
10910                        Op.getOperand(1), Op.getOperand(2));
10911   }
10912
10913   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10914   case Intrinsic::x86_sse2_pmaxu_b:
10915   case Intrinsic::x86_sse41_pmaxuw:
10916   case Intrinsic::x86_sse41_pmaxud:
10917   case Intrinsic::x86_avx2_pmaxu_b:
10918   case Intrinsic::x86_avx2_pmaxu_w:
10919   case Intrinsic::x86_avx2_pmaxu_d:
10920   case Intrinsic::x86_sse2_pminu_b:
10921   case Intrinsic::x86_sse41_pminuw:
10922   case Intrinsic::x86_sse41_pminud:
10923   case Intrinsic::x86_avx2_pminu_b:
10924   case Intrinsic::x86_avx2_pminu_w:
10925   case Intrinsic::x86_avx2_pminu_d:
10926   case Intrinsic::x86_sse41_pmaxsb:
10927   case Intrinsic::x86_sse2_pmaxs_w:
10928   case Intrinsic::x86_sse41_pmaxsd:
10929   case Intrinsic::x86_avx2_pmaxs_b:
10930   case Intrinsic::x86_avx2_pmaxs_w:
10931   case Intrinsic::x86_avx2_pmaxs_d:
10932   case Intrinsic::x86_sse41_pminsb:
10933   case Intrinsic::x86_sse2_pmins_w:
10934   case Intrinsic::x86_sse41_pminsd:
10935   case Intrinsic::x86_avx2_pmins_b:
10936   case Intrinsic::x86_avx2_pmins_w:
10937   case Intrinsic::x86_avx2_pmins_d: {
10938     unsigned Opcode;
10939     switch (IntNo) {
10940     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10941     case Intrinsic::x86_sse2_pmaxu_b:
10942     case Intrinsic::x86_sse41_pmaxuw:
10943     case Intrinsic::x86_sse41_pmaxud:
10944     case Intrinsic::x86_avx2_pmaxu_b:
10945     case Intrinsic::x86_avx2_pmaxu_w:
10946     case Intrinsic::x86_avx2_pmaxu_d:
10947       Opcode = X86ISD::UMAX;
10948       break;
10949     case Intrinsic::x86_sse2_pminu_b:
10950     case Intrinsic::x86_sse41_pminuw:
10951     case Intrinsic::x86_sse41_pminud:
10952     case Intrinsic::x86_avx2_pminu_b:
10953     case Intrinsic::x86_avx2_pminu_w:
10954     case Intrinsic::x86_avx2_pminu_d:
10955       Opcode = X86ISD::UMIN;
10956       break;
10957     case Intrinsic::x86_sse41_pmaxsb:
10958     case Intrinsic::x86_sse2_pmaxs_w:
10959     case Intrinsic::x86_sse41_pmaxsd:
10960     case Intrinsic::x86_avx2_pmaxs_b:
10961     case Intrinsic::x86_avx2_pmaxs_w:
10962     case Intrinsic::x86_avx2_pmaxs_d:
10963       Opcode = X86ISD::SMAX;
10964       break;
10965     case Intrinsic::x86_sse41_pminsb:
10966     case Intrinsic::x86_sse2_pmins_w:
10967     case Intrinsic::x86_sse41_pminsd:
10968     case Intrinsic::x86_avx2_pmins_b:
10969     case Intrinsic::x86_avx2_pmins_w:
10970     case Intrinsic::x86_avx2_pmins_d:
10971       Opcode = X86ISD::SMIN;
10972       break;
10973     }
10974     return DAG.getNode(Opcode, dl, Op.getValueType(),
10975                        Op.getOperand(1), Op.getOperand(2));
10976   }
10977
10978   // SSE/SSE2/AVX floating point max/min intrinsics.
10979   case Intrinsic::x86_sse_max_ps:
10980   case Intrinsic::x86_sse2_max_pd:
10981   case Intrinsic::x86_avx_max_ps_256:
10982   case Intrinsic::x86_avx_max_pd_256:
10983   case Intrinsic::x86_sse_min_ps:
10984   case Intrinsic::x86_sse2_min_pd:
10985   case Intrinsic::x86_avx_min_ps_256:
10986   case Intrinsic::x86_avx_min_pd_256: {
10987     unsigned Opcode;
10988     switch (IntNo) {
10989     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10990     case Intrinsic::x86_sse_max_ps:
10991     case Intrinsic::x86_sse2_max_pd:
10992     case Intrinsic::x86_avx_max_ps_256:
10993     case Intrinsic::x86_avx_max_pd_256:
10994       Opcode = X86ISD::FMAX;
10995       break;
10996     case Intrinsic::x86_sse_min_ps:
10997     case Intrinsic::x86_sse2_min_pd:
10998     case Intrinsic::x86_avx_min_ps_256:
10999     case Intrinsic::x86_avx_min_pd_256:
11000       Opcode = X86ISD::FMIN;
11001       break;
11002     }
11003     return DAG.getNode(Opcode, dl, Op.getValueType(),
11004                        Op.getOperand(1), Op.getOperand(2));
11005   }
11006
11007   // AVX2 variable shift intrinsics
11008   case Intrinsic::x86_avx2_psllv_d:
11009   case Intrinsic::x86_avx2_psllv_q:
11010   case Intrinsic::x86_avx2_psllv_d_256:
11011   case Intrinsic::x86_avx2_psllv_q_256:
11012   case Intrinsic::x86_avx2_psrlv_d:
11013   case Intrinsic::x86_avx2_psrlv_q:
11014   case Intrinsic::x86_avx2_psrlv_d_256:
11015   case Intrinsic::x86_avx2_psrlv_q_256:
11016   case Intrinsic::x86_avx2_psrav_d:
11017   case Intrinsic::x86_avx2_psrav_d_256: {
11018     unsigned Opcode;
11019     switch (IntNo) {
11020     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11021     case Intrinsic::x86_avx2_psllv_d:
11022     case Intrinsic::x86_avx2_psllv_q:
11023     case Intrinsic::x86_avx2_psllv_d_256:
11024     case Intrinsic::x86_avx2_psllv_q_256:
11025       Opcode = ISD::SHL;
11026       break;
11027     case Intrinsic::x86_avx2_psrlv_d:
11028     case Intrinsic::x86_avx2_psrlv_q:
11029     case Intrinsic::x86_avx2_psrlv_d_256:
11030     case Intrinsic::x86_avx2_psrlv_q_256:
11031       Opcode = ISD::SRL;
11032       break;
11033     case Intrinsic::x86_avx2_psrav_d:
11034     case Intrinsic::x86_avx2_psrav_d_256:
11035       Opcode = ISD::SRA;
11036       break;
11037     }
11038     return DAG.getNode(Opcode, dl, Op.getValueType(),
11039                        Op.getOperand(1), Op.getOperand(2));
11040   }
11041
11042   case Intrinsic::x86_ssse3_pshuf_b_128:
11043   case Intrinsic::x86_avx2_pshuf_b:
11044     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11045                        Op.getOperand(1), Op.getOperand(2));
11046
11047   case Intrinsic::x86_ssse3_psign_b_128:
11048   case Intrinsic::x86_ssse3_psign_w_128:
11049   case Intrinsic::x86_ssse3_psign_d_128:
11050   case Intrinsic::x86_avx2_psign_b:
11051   case Intrinsic::x86_avx2_psign_w:
11052   case Intrinsic::x86_avx2_psign_d:
11053     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11054                        Op.getOperand(1), Op.getOperand(2));
11055
11056   case Intrinsic::x86_sse41_insertps:
11057     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11058                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11059
11060   case Intrinsic::x86_avx_vperm2f128_ps_256:
11061   case Intrinsic::x86_avx_vperm2f128_pd_256:
11062   case Intrinsic::x86_avx_vperm2f128_si_256:
11063   case Intrinsic::x86_avx2_vperm2i128:
11064     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11065                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11066
11067   case Intrinsic::x86_avx2_permd:
11068   case Intrinsic::x86_avx2_permps:
11069     // Operands intentionally swapped. Mask is last operand to intrinsic,
11070     // but second operand for node/intruction.
11071     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11072                        Op.getOperand(2), Op.getOperand(1));
11073
11074   case Intrinsic::x86_sse_sqrt_ps:
11075   case Intrinsic::x86_sse2_sqrt_pd:
11076   case Intrinsic::x86_avx_sqrt_ps_256:
11077   case Intrinsic::x86_avx_sqrt_pd_256:
11078     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11079
11080   // ptest and testp intrinsics. The intrinsic these come from are designed to
11081   // return an integer value, not just an instruction so lower it to the ptest
11082   // or testp pattern and a setcc for the result.
11083   case Intrinsic::x86_sse41_ptestz:
11084   case Intrinsic::x86_sse41_ptestc:
11085   case Intrinsic::x86_sse41_ptestnzc:
11086   case Intrinsic::x86_avx_ptestz_256:
11087   case Intrinsic::x86_avx_ptestc_256:
11088   case Intrinsic::x86_avx_ptestnzc_256:
11089   case Intrinsic::x86_avx_vtestz_ps:
11090   case Intrinsic::x86_avx_vtestc_ps:
11091   case Intrinsic::x86_avx_vtestnzc_ps:
11092   case Intrinsic::x86_avx_vtestz_pd:
11093   case Intrinsic::x86_avx_vtestc_pd:
11094   case Intrinsic::x86_avx_vtestnzc_pd:
11095   case Intrinsic::x86_avx_vtestz_ps_256:
11096   case Intrinsic::x86_avx_vtestc_ps_256:
11097   case Intrinsic::x86_avx_vtestnzc_ps_256:
11098   case Intrinsic::x86_avx_vtestz_pd_256:
11099   case Intrinsic::x86_avx_vtestc_pd_256:
11100   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11101     bool IsTestPacked = false;
11102     unsigned X86CC;
11103     switch (IntNo) {
11104     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11105     case Intrinsic::x86_avx_vtestz_ps:
11106     case Intrinsic::x86_avx_vtestz_pd:
11107     case Intrinsic::x86_avx_vtestz_ps_256:
11108     case Intrinsic::x86_avx_vtestz_pd_256:
11109       IsTestPacked = true; // Fallthrough
11110     case Intrinsic::x86_sse41_ptestz:
11111     case Intrinsic::x86_avx_ptestz_256:
11112       // ZF = 1
11113       X86CC = X86::COND_E;
11114       break;
11115     case Intrinsic::x86_avx_vtestc_ps:
11116     case Intrinsic::x86_avx_vtestc_pd:
11117     case Intrinsic::x86_avx_vtestc_ps_256:
11118     case Intrinsic::x86_avx_vtestc_pd_256:
11119       IsTestPacked = true; // Fallthrough
11120     case Intrinsic::x86_sse41_ptestc:
11121     case Intrinsic::x86_avx_ptestc_256:
11122       // CF = 1
11123       X86CC = X86::COND_B;
11124       break;
11125     case Intrinsic::x86_avx_vtestnzc_ps:
11126     case Intrinsic::x86_avx_vtestnzc_pd:
11127     case Intrinsic::x86_avx_vtestnzc_ps_256:
11128     case Intrinsic::x86_avx_vtestnzc_pd_256:
11129       IsTestPacked = true; // Fallthrough
11130     case Intrinsic::x86_sse41_ptestnzc:
11131     case Intrinsic::x86_avx_ptestnzc_256:
11132       // ZF and CF = 0
11133       X86CC = X86::COND_A;
11134       break;
11135     }
11136
11137     SDValue LHS = Op.getOperand(1);
11138     SDValue RHS = Op.getOperand(2);
11139     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
11140     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
11141     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
11142     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
11143     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11144   }
11145
11146   // SSE/AVX shift intrinsics
11147   case Intrinsic::x86_sse2_psll_w:
11148   case Intrinsic::x86_sse2_psll_d:
11149   case Intrinsic::x86_sse2_psll_q:
11150   case Intrinsic::x86_avx2_psll_w:
11151   case Intrinsic::x86_avx2_psll_d:
11152   case Intrinsic::x86_avx2_psll_q:
11153   case Intrinsic::x86_sse2_psrl_w:
11154   case Intrinsic::x86_sse2_psrl_d:
11155   case Intrinsic::x86_sse2_psrl_q:
11156   case Intrinsic::x86_avx2_psrl_w:
11157   case Intrinsic::x86_avx2_psrl_d:
11158   case Intrinsic::x86_avx2_psrl_q:
11159   case Intrinsic::x86_sse2_psra_w:
11160   case Intrinsic::x86_sse2_psra_d:
11161   case Intrinsic::x86_avx2_psra_w:
11162   case Intrinsic::x86_avx2_psra_d: {
11163     unsigned Opcode;
11164     switch (IntNo) {
11165     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11166     case Intrinsic::x86_sse2_psll_w:
11167     case Intrinsic::x86_sse2_psll_d:
11168     case Intrinsic::x86_sse2_psll_q:
11169     case Intrinsic::x86_avx2_psll_w:
11170     case Intrinsic::x86_avx2_psll_d:
11171     case Intrinsic::x86_avx2_psll_q:
11172       Opcode = X86ISD::VSHL;
11173       break;
11174     case Intrinsic::x86_sse2_psrl_w:
11175     case Intrinsic::x86_sse2_psrl_d:
11176     case Intrinsic::x86_sse2_psrl_q:
11177     case Intrinsic::x86_avx2_psrl_w:
11178     case Intrinsic::x86_avx2_psrl_d:
11179     case Intrinsic::x86_avx2_psrl_q:
11180       Opcode = X86ISD::VSRL;
11181       break;
11182     case Intrinsic::x86_sse2_psra_w:
11183     case Intrinsic::x86_sse2_psra_d:
11184     case Intrinsic::x86_avx2_psra_w:
11185     case Intrinsic::x86_avx2_psra_d:
11186       Opcode = X86ISD::VSRA;
11187       break;
11188     }
11189     return DAG.getNode(Opcode, dl, Op.getValueType(),
11190                        Op.getOperand(1), Op.getOperand(2));
11191   }
11192
11193   // SSE/AVX immediate shift intrinsics
11194   case Intrinsic::x86_sse2_pslli_w:
11195   case Intrinsic::x86_sse2_pslli_d:
11196   case Intrinsic::x86_sse2_pslli_q:
11197   case Intrinsic::x86_avx2_pslli_w:
11198   case Intrinsic::x86_avx2_pslli_d:
11199   case Intrinsic::x86_avx2_pslli_q:
11200   case Intrinsic::x86_sse2_psrli_w:
11201   case Intrinsic::x86_sse2_psrli_d:
11202   case Intrinsic::x86_sse2_psrli_q:
11203   case Intrinsic::x86_avx2_psrli_w:
11204   case Intrinsic::x86_avx2_psrli_d:
11205   case Intrinsic::x86_avx2_psrli_q:
11206   case Intrinsic::x86_sse2_psrai_w:
11207   case Intrinsic::x86_sse2_psrai_d:
11208   case Intrinsic::x86_avx2_psrai_w:
11209   case Intrinsic::x86_avx2_psrai_d: {
11210     unsigned Opcode;
11211     switch (IntNo) {
11212     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11213     case Intrinsic::x86_sse2_pslli_w:
11214     case Intrinsic::x86_sse2_pslli_d:
11215     case Intrinsic::x86_sse2_pslli_q:
11216     case Intrinsic::x86_avx2_pslli_w:
11217     case Intrinsic::x86_avx2_pslli_d:
11218     case Intrinsic::x86_avx2_pslli_q:
11219       Opcode = X86ISD::VSHLI;
11220       break;
11221     case Intrinsic::x86_sse2_psrli_w:
11222     case Intrinsic::x86_sse2_psrli_d:
11223     case Intrinsic::x86_sse2_psrli_q:
11224     case Intrinsic::x86_avx2_psrli_w:
11225     case Intrinsic::x86_avx2_psrli_d:
11226     case Intrinsic::x86_avx2_psrli_q:
11227       Opcode = X86ISD::VSRLI;
11228       break;
11229     case Intrinsic::x86_sse2_psrai_w:
11230     case Intrinsic::x86_sse2_psrai_d:
11231     case Intrinsic::x86_avx2_psrai_w:
11232     case Intrinsic::x86_avx2_psrai_d:
11233       Opcode = X86ISD::VSRAI;
11234       break;
11235     }
11236     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
11237                                Op.getOperand(1), Op.getOperand(2), DAG);
11238   }
11239
11240   case Intrinsic::x86_sse42_pcmpistria128:
11241   case Intrinsic::x86_sse42_pcmpestria128:
11242   case Intrinsic::x86_sse42_pcmpistric128:
11243   case Intrinsic::x86_sse42_pcmpestric128:
11244   case Intrinsic::x86_sse42_pcmpistrio128:
11245   case Intrinsic::x86_sse42_pcmpestrio128:
11246   case Intrinsic::x86_sse42_pcmpistris128:
11247   case Intrinsic::x86_sse42_pcmpestris128:
11248   case Intrinsic::x86_sse42_pcmpistriz128:
11249   case Intrinsic::x86_sse42_pcmpestriz128: {
11250     unsigned Opcode;
11251     unsigned X86CC;
11252     switch (IntNo) {
11253     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11254     case Intrinsic::x86_sse42_pcmpistria128:
11255       Opcode = X86ISD::PCMPISTRI;
11256       X86CC = X86::COND_A;
11257       break;
11258     case Intrinsic::x86_sse42_pcmpestria128:
11259       Opcode = X86ISD::PCMPESTRI;
11260       X86CC = X86::COND_A;
11261       break;
11262     case Intrinsic::x86_sse42_pcmpistric128:
11263       Opcode = X86ISD::PCMPISTRI;
11264       X86CC = X86::COND_B;
11265       break;
11266     case Intrinsic::x86_sse42_pcmpestric128:
11267       Opcode = X86ISD::PCMPESTRI;
11268       X86CC = X86::COND_B;
11269       break;
11270     case Intrinsic::x86_sse42_pcmpistrio128:
11271       Opcode = X86ISD::PCMPISTRI;
11272       X86CC = X86::COND_O;
11273       break;
11274     case Intrinsic::x86_sse42_pcmpestrio128:
11275       Opcode = X86ISD::PCMPESTRI;
11276       X86CC = X86::COND_O;
11277       break;
11278     case Intrinsic::x86_sse42_pcmpistris128:
11279       Opcode = X86ISD::PCMPISTRI;
11280       X86CC = X86::COND_S;
11281       break;
11282     case Intrinsic::x86_sse42_pcmpestris128:
11283       Opcode = X86ISD::PCMPESTRI;
11284       X86CC = X86::COND_S;
11285       break;
11286     case Intrinsic::x86_sse42_pcmpistriz128:
11287       Opcode = X86ISD::PCMPISTRI;
11288       X86CC = X86::COND_E;
11289       break;
11290     case Intrinsic::x86_sse42_pcmpestriz128:
11291       Opcode = X86ISD::PCMPESTRI;
11292       X86CC = X86::COND_E;
11293       break;
11294     }
11295     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11296     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11297     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11298     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11299                                 DAG.getConstant(X86CC, MVT::i8),
11300                                 SDValue(PCMP.getNode(), 1));
11301     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11302   }
11303
11304   case Intrinsic::x86_sse42_pcmpistri128:
11305   case Intrinsic::x86_sse42_pcmpestri128: {
11306     unsigned Opcode;
11307     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
11308       Opcode = X86ISD::PCMPISTRI;
11309     else
11310       Opcode = X86ISD::PCMPESTRI;
11311
11312     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
11313     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11314     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
11315   }
11316   case Intrinsic::x86_fma_vfmadd_ps:
11317   case Intrinsic::x86_fma_vfmadd_pd:
11318   case Intrinsic::x86_fma_vfmsub_ps:
11319   case Intrinsic::x86_fma_vfmsub_pd:
11320   case Intrinsic::x86_fma_vfnmadd_ps:
11321   case Intrinsic::x86_fma_vfnmadd_pd:
11322   case Intrinsic::x86_fma_vfnmsub_ps:
11323   case Intrinsic::x86_fma_vfnmsub_pd:
11324   case Intrinsic::x86_fma_vfmaddsub_ps:
11325   case Intrinsic::x86_fma_vfmaddsub_pd:
11326   case Intrinsic::x86_fma_vfmsubadd_ps:
11327   case Intrinsic::x86_fma_vfmsubadd_pd:
11328   case Intrinsic::x86_fma_vfmadd_ps_256:
11329   case Intrinsic::x86_fma_vfmadd_pd_256:
11330   case Intrinsic::x86_fma_vfmsub_ps_256:
11331   case Intrinsic::x86_fma_vfmsub_pd_256:
11332   case Intrinsic::x86_fma_vfnmadd_ps_256:
11333   case Intrinsic::x86_fma_vfnmadd_pd_256:
11334   case Intrinsic::x86_fma_vfnmsub_ps_256:
11335   case Intrinsic::x86_fma_vfnmsub_pd_256:
11336   case Intrinsic::x86_fma_vfmaddsub_ps_256:
11337   case Intrinsic::x86_fma_vfmaddsub_pd_256:
11338   case Intrinsic::x86_fma_vfmsubadd_ps_256:
11339   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
11340     unsigned Opc;
11341     switch (IntNo) {
11342     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11343     case Intrinsic::x86_fma_vfmadd_ps:
11344     case Intrinsic::x86_fma_vfmadd_pd:
11345     case Intrinsic::x86_fma_vfmadd_ps_256:
11346     case Intrinsic::x86_fma_vfmadd_pd_256:
11347       Opc = X86ISD::FMADD;
11348       break;
11349     case Intrinsic::x86_fma_vfmsub_ps:
11350     case Intrinsic::x86_fma_vfmsub_pd:
11351     case Intrinsic::x86_fma_vfmsub_ps_256:
11352     case Intrinsic::x86_fma_vfmsub_pd_256:
11353       Opc = X86ISD::FMSUB;
11354       break;
11355     case Intrinsic::x86_fma_vfnmadd_ps:
11356     case Intrinsic::x86_fma_vfnmadd_pd:
11357     case Intrinsic::x86_fma_vfnmadd_ps_256:
11358     case Intrinsic::x86_fma_vfnmadd_pd_256:
11359       Opc = X86ISD::FNMADD;
11360       break;
11361     case Intrinsic::x86_fma_vfnmsub_ps:
11362     case Intrinsic::x86_fma_vfnmsub_pd:
11363     case Intrinsic::x86_fma_vfnmsub_ps_256:
11364     case Intrinsic::x86_fma_vfnmsub_pd_256:
11365       Opc = X86ISD::FNMSUB;
11366       break;
11367     case Intrinsic::x86_fma_vfmaddsub_ps:
11368     case Intrinsic::x86_fma_vfmaddsub_pd:
11369     case Intrinsic::x86_fma_vfmaddsub_ps_256:
11370     case Intrinsic::x86_fma_vfmaddsub_pd_256:
11371       Opc = X86ISD::FMADDSUB;
11372       break;
11373     case Intrinsic::x86_fma_vfmsubadd_ps:
11374     case Intrinsic::x86_fma_vfmsubadd_pd:
11375     case Intrinsic::x86_fma_vfmsubadd_ps_256:
11376     case Intrinsic::x86_fma_vfmsubadd_pd_256:
11377       Opc = X86ISD::FMSUBADD;
11378       break;
11379     }
11380
11381     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
11382                        Op.getOperand(2), Op.getOperand(3));
11383   }
11384   }
11385 }
11386
11387 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
11388   SDLoc dl(Op);
11389   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11390   switch (IntNo) {
11391   default: return SDValue();    // Don't custom lower most intrinsics.
11392
11393   // RDRAND/RDSEED intrinsics.
11394   case Intrinsic::x86_rdrand_16:
11395   case Intrinsic::x86_rdrand_32:
11396   case Intrinsic::x86_rdrand_64:
11397   case Intrinsic::x86_rdseed_16:
11398   case Intrinsic::x86_rdseed_32:
11399   case Intrinsic::x86_rdseed_64: {
11400     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11401                        IntNo == Intrinsic::x86_rdseed_32 ||
11402                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11403                                                             X86ISD::RDRAND;
11404     // Emit the node with the right value type.
11405     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11406     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11407
11408     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11409     // Otherwise return the value from Rand, which is always 0, casted to i32.
11410     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11411                       DAG.getConstant(1, Op->getValueType(1)),
11412                       DAG.getConstant(X86::COND_B, MVT::i32),
11413                       SDValue(Result.getNode(), 1) };
11414     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11415                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11416                                   Ops, array_lengthof(Ops));
11417
11418     // Return { result, isValid, chain }.
11419     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11420                        SDValue(Result.getNode(), 2));
11421   }
11422
11423   // XTEST intrinsics.
11424   case Intrinsic::x86_xtest: {
11425     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11426     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11427     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11428                                 DAG.getConstant(X86::COND_NE, MVT::i8),
11429                                 InTrans);
11430     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11431     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11432                        Ret, SDValue(InTrans.getNode(), 1));
11433   }
11434   }
11435 }
11436
11437 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11438                                            SelectionDAG &DAG) const {
11439   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11440   MFI->setReturnAddressIsTaken(true);
11441
11442   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11443   SDLoc dl(Op);
11444   EVT PtrVT = getPointerTy();
11445
11446   if (Depth > 0) {
11447     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11448     const X86RegisterInfo *RegInfo =
11449       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11450     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11451     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11452                        DAG.getNode(ISD::ADD, dl, PtrVT,
11453                                    FrameAddr, Offset),
11454                        MachinePointerInfo(), false, false, false, 0);
11455   }
11456
11457   // Just load the return address.
11458   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11459   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11460                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11461 }
11462
11463 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11464   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11465   MFI->setFrameAddressIsTaken(true);
11466
11467   EVT VT = Op.getValueType();
11468   SDLoc dl(Op);  // FIXME probably not meaningful
11469   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11470   const X86RegisterInfo *RegInfo =
11471     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11472   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11473   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11474           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11475          "Invalid Frame Register!");
11476   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11477   while (Depth--)
11478     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11479                             MachinePointerInfo(),
11480                             false, false, false, 0);
11481   return FrameAddr;
11482 }
11483
11484 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11485                                                      SelectionDAG &DAG) const {
11486   const X86RegisterInfo *RegInfo =
11487     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11488   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11489 }
11490
11491 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11492   SDValue Chain     = Op.getOperand(0);
11493   SDValue Offset    = Op.getOperand(1);
11494   SDValue Handler   = Op.getOperand(2);
11495   SDLoc dl      (Op);
11496
11497   EVT PtrVT = getPointerTy();
11498   const X86RegisterInfo *RegInfo =
11499     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11500   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11501   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11502           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11503          "Invalid Frame Register!");
11504   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11505   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11506
11507   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11508                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11509   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11510   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11511                        false, false, 0);
11512   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11513
11514   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11515                      DAG.getRegister(StoreAddrReg, PtrVT));
11516 }
11517
11518 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11519                                                SelectionDAG &DAG) const {
11520   SDLoc DL(Op);
11521   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11522                      DAG.getVTList(MVT::i32, MVT::Other),
11523                      Op.getOperand(0), Op.getOperand(1));
11524 }
11525
11526 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11527                                                 SelectionDAG &DAG) const {
11528   SDLoc DL(Op);
11529   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11530                      Op.getOperand(0), Op.getOperand(1));
11531 }
11532
11533 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11534   return Op.getOperand(0);
11535 }
11536
11537 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11538                                                 SelectionDAG &DAG) const {
11539   SDValue Root = Op.getOperand(0);
11540   SDValue Trmp = Op.getOperand(1); // trampoline
11541   SDValue FPtr = Op.getOperand(2); // nested function
11542   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11543   SDLoc dl (Op);
11544
11545   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11546   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11547
11548   if (Subtarget->is64Bit()) {
11549     SDValue OutChains[6];
11550
11551     // Large code-model.
11552     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11553     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11554
11555     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11556     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11557
11558     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11559
11560     // Load the pointer to the nested function into R11.
11561     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11562     SDValue Addr = Trmp;
11563     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11564                                 Addr, MachinePointerInfo(TrmpAddr),
11565                                 false, false, 0);
11566
11567     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11568                        DAG.getConstant(2, MVT::i64));
11569     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11570                                 MachinePointerInfo(TrmpAddr, 2),
11571                                 false, false, 2);
11572
11573     // Load the 'nest' parameter value into R10.
11574     // R10 is specified in X86CallingConv.td
11575     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11576     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11577                        DAG.getConstant(10, MVT::i64));
11578     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11579                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11580                                 false, false, 0);
11581
11582     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11583                        DAG.getConstant(12, MVT::i64));
11584     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11585                                 MachinePointerInfo(TrmpAddr, 12),
11586                                 false, false, 2);
11587
11588     // Jump to the nested function.
11589     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11590     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11591                        DAG.getConstant(20, MVT::i64));
11592     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11593                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11594                                 false, false, 0);
11595
11596     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11597     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11598                        DAG.getConstant(22, MVT::i64));
11599     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11600                                 MachinePointerInfo(TrmpAddr, 22),
11601                                 false, false, 0);
11602
11603     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11604   } else {
11605     const Function *Func =
11606       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11607     CallingConv::ID CC = Func->getCallingConv();
11608     unsigned NestReg;
11609
11610     switch (CC) {
11611     default:
11612       llvm_unreachable("Unsupported calling convention");
11613     case CallingConv::C:
11614     case CallingConv::X86_StdCall: {
11615       // Pass 'nest' parameter in ECX.
11616       // Must be kept in sync with X86CallingConv.td
11617       NestReg = X86::ECX;
11618
11619       // Check that ECX wasn't needed by an 'inreg' parameter.
11620       FunctionType *FTy = Func->getFunctionType();
11621       const AttributeSet &Attrs = Func->getAttributes();
11622
11623       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11624         unsigned InRegCount = 0;
11625         unsigned Idx = 1;
11626
11627         for (FunctionType::param_iterator I = FTy->param_begin(),
11628              E = FTy->param_end(); I != E; ++I, ++Idx)
11629           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11630             // FIXME: should only count parameters that are lowered to integers.
11631             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11632
11633         if (InRegCount > 2) {
11634           report_fatal_error("Nest register in use - reduce number of inreg"
11635                              " parameters!");
11636         }
11637       }
11638       break;
11639     }
11640     case CallingConv::X86_FastCall:
11641     case CallingConv::X86_ThisCall:
11642     case CallingConv::Fast:
11643       // Pass 'nest' parameter in EAX.
11644       // Must be kept in sync with X86CallingConv.td
11645       NestReg = X86::EAX;
11646       break;
11647     }
11648
11649     SDValue OutChains[4];
11650     SDValue Addr, Disp;
11651
11652     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11653                        DAG.getConstant(10, MVT::i32));
11654     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11655
11656     // This is storing the opcode for MOV32ri.
11657     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11658     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11659     OutChains[0] = DAG.getStore(Root, dl,
11660                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11661                                 Trmp, MachinePointerInfo(TrmpAddr),
11662                                 false, false, 0);
11663
11664     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11665                        DAG.getConstant(1, MVT::i32));
11666     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11667                                 MachinePointerInfo(TrmpAddr, 1),
11668                                 false, false, 1);
11669
11670     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11671     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11672                        DAG.getConstant(5, MVT::i32));
11673     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11674                                 MachinePointerInfo(TrmpAddr, 5),
11675                                 false, false, 1);
11676
11677     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11678                        DAG.getConstant(6, MVT::i32));
11679     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11680                                 MachinePointerInfo(TrmpAddr, 6),
11681                                 false, false, 1);
11682
11683     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11684   }
11685 }
11686
11687 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11688                                             SelectionDAG &DAG) const {
11689   /*
11690    The rounding mode is in bits 11:10 of FPSR, and has the following
11691    settings:
11692      00 Round to nearest
11693      01 Round to -inf
11694      10 Round to +inf
11695      11 Round to 0
11696
11697   FLT_ROUNDS, on the other hand, expects the following:
11698     -1 Undefined
11699      0 Round to 0
11700      1 Round to nearest
11701      2 Round to +inf
11702      3 Round to -inf
11703
11704   To perform the conversion, we do:
11705     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11706   */
11707
11708   MachineFunction &MF = DAG.getMachineFunction();
11709   const TargetMachine &TM = MF.getTarget();
11710   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11711   unsigned StackAlignment = TFI.getStackAlignment();
11712   EVT VT = Op.getValueType();
11713   SDLoc DL(Op);
11714
11715   // Save FP Control Word to stack slot
11716   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11717   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11718
11719   MachineMemOperand *MMO =
11720    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11721                            MachineMemOperand::MOStore, 2, 2);
11722
11723   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11724   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11725                                           DAG.getVTList(MVT::Other),
11726                                           Ops, array_lengthof(Ops), MVT::i16,
11727                                           MMO);
11728
11729   // Load FP Control Word from stack slot
11730   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11731                             MachinePointerInfo(), false, false, false, 0);
11732
11733   // Transform as necessary
11734   SDValue CWD1 =
11735     DAG.getNode(ISD::SRL, DL, MVT::i16,
11736                 DAG.getNode(ISD::AND, DL, MVT::i16,
11737                             CWD, DAG.getConstant(0x800, MVT::i16)),
11738                 DAG.getConstant(11, MVT::i8));
11739   SDValue CWD2 =
11740     DAG.getNode(ISD::SRL, DL, MVT::i16,
11741                 DAG.getNode(ISD::AND, DL, MVT::i16,
11742                             CWD, DAG.getConstant(0x400, MVT::i16)),
11743                 DAG.getConstant(9, MVT::i8));
11744
11745   SDValue RetVal =
11746     DAG.getNode(ISD::AND, DL, MVT::i16,
11747                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11748                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11749                             DAG.getConstant(1, MVT::i16)),
11750                 DAG.getConstant(3, MVT::i16));
11751
11752   return DAG.getNode((VT.getSizeInBits() < 16 ?
11753                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11754 }
11755
11756 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11757   EVT VT = Op.getValueType();
11758   EVT OpVT = VT;
11759   unsigned NumBits = VT.getSizeInBits();
11760   SDLoc dl(Op);
11761
11762   Op = Op.getOperand(0);
11763   if (VT == MVT::i8) {
11764     // Zero extend to i32 since there is not an i8 bsr.
11765     OpVT = MVT::i32;
11766     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11767   }
11768
11769   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11770   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11771   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11772
11773   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11774   SDValue Ops[] = {
11775     Op,
11776     DAG.getConstant(NumBits+NumBits-1, OpVT),
11777     DAG.getConstant(X86::COND_E, MVT::i8),
11778     Op.getValue(1)
11779   };
11780   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11781
11782   // Finally xor with NumBits-1.
11783   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11784
11785   if (VT == MVT::i8)
11786     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11787   return Op;
11788 }
11789
11790 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11791   EVT VT = Op.getValueType();
11792   EVT OpVT = VT;
11793   unsigned NumBits = VT.getSizeInBits();
11794   SDLoc dl(Op);
11795
11796   Op = Op.getOperand(0);
11797   if (VT == MVT::i8) {
11798     // Zero extend to i32 since there is not an i8 bsr.
11799     OpVT = MVT::i32;
11800     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11801   }
11802
11803   // Issue a bsr (scan bits in reverse).
11804   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11805   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11806
11807   // And xor with NumBits-1.
11808   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11809
11810   if (VT == MVT::i8)
11811     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11812   return Op;
11813 }
11814
11815 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11816   EVT VT = Op.getValueType();
11817   unsigned NumBits = VT.getSizeInBits();
11818   SDLoc dl(Op);
11819   Op = Op.getOperand(0);
11820
11821   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11822   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11823   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11824
11825   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11826   SDValue Ops[] = {
11827     Op,
11828     DAG.getConstant(NumBits, VT),
11829     DAG.getConstant(X86::COND_E, MVT::i8),
11830     Op.getValue(1)
11831   };
11832   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11833 }
11834
11835 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11836 // ones, and then concatenate the result back.
11837 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11838   EVT VT = Op.getValueType();
11839
11840   assert(VT.is256BitVector() && VT.isInteger() &&
11841          "Unsupported value type for operation");
11842
11843   unsigned NumElems = VT.getVectorNumElements();
11844   SDLoc dl(Op);
11845
11846   // Extract the LHS vectors
11847   SDValue LHS = Op.getOperand(0);
11848   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11849   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11850
11851   // Extract the RHS vectors
11852   SDValue RHS = Op.getOperand(1);
11853   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11854   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11855
11856   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11857   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11858
11859   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11860                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11861                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11862 }
11863
11864 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11865   assert(Op.getValueType().is256BitVector() &&
11866          Op.getValueType().isInteger() &&
11867          "Only handle AVX 256-bit vector integer operation");
11868   return Lower256IntArith(Op, DAG);
11869 }
11870
11871 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11872   assert(Op.getValueType().is256BitVector() &&
11873          Op.getValueType().isInteger() &&
11874          "Only handle AVX 256-bit vector integer operation");
11875   return Lower256IntArith(Op, DAG);
11876 }
11877
11878 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11879                         SelectionDAG &DAG) {
11880   SDLoc dl(Op);
11881   EVT VT = Op.getValueType();
11882
11883   // Decompose 256-bit ops into smaller 128-bit ops.
11884   if (VT.is256BitVector() && !Subtarget->hasInt256())
11885     return Lower256IntArith(Op, DAG);
11886
11887   SDValue A = Op.getOperand(0);
11888   SDValue B = Op.getOperand(1);
11889
11890   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11891   if (VT == MVT::v4i32) {
11892     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11893            "Should not custom lower when pmuldq is available!");
11894
11895     // Extract the odd parts.
11896     static const int UnpackMask[] = { 1, -1, 3, -1 };
11897     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11898     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11899
11900     // Multiply the even parts.
11901     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11902     // Now multiply odd parts.
11903     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11904
11905     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11906     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11907
11908     // Merge the two vectors back together with a shuffle. This expands into 2
11909     // shuffles.
11910     static const int ShufMask[] = { 0, 4, 2, 6 };
11911     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11912   }
11913
11914   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11915          "Only know how to lower V2I64/V4I64 multiply");
11916
11917   //  Ahi = psrlqi(a, 32);
11918   //  Bhi = psrlqi(b, 32);
11919   //
11920   //  AloBlo = pmuludq(a, b);
11921   //  AloBhi = pmuludq(a, Bhi);
11922   //  AhiBlo = pmuludq(Ahi, b);
11923
11924   //  AloBhi = psllqi(AloBhi, 32);
11925   //  AhiBlo = psllqi(AhiBlo, 32);
11926   //  return AloBlo + AloBhi + AhiBlo;
11927
11928   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11929
11930   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11931   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11932
11933   // Bit cast to 32-bit vectors for MULUDQ
11934   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11935   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11936   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11937   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11938   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11939
11940   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11941   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11942   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11943
11944   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11945   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11946
11947   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11948   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11949 }
11950
11951 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11952   EVT VT = Op.getValueType();
11953   EVT EltTy = VT.getVectorElementType();
11954   unsigned NumElts = VT.getVectorNumElements();
11955   SDValue N0 = Op.getOperand(0);
11956   SDLoc dl(Op);
11957
11958   // Lower sdiv X, pow2-const.
11959   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11960   if (!C)
11961     return SDValue();
11962
11963   APInt SplatValue, SplatUndef;
11964   unsigned SplatBitSize;
11965   bool HasAnyUndefs;
11966   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11967                           HasAnyUndefs) ||
11968       EltTy.getSizeInBits() < SplatBitSize)
11969     return SDValue();
11970
11971   if ((SplatValue != 0) &&
11972       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11973     unsigned lg2 = SplatValue.countTrailingZeros();
11974     // Splat the sign bit.
11975     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11976     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11977     // Add (N0 < 0) ? abs2 - 1 : 0;
11978     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11979     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11980     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11981     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11982     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11983
11984     // If we're dividing by a positive value, we're done.  Otherwise, we must
11985     // negate the result.
11986     if (SplatValue.isNonNegative())
11987       return SRA;
11988
11989     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11990     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11991     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11992   }
11993   return SDValue();
11994 }
11995
11996 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11997                                          const X86Subtarget *Subtarget) {
11998   EVT VT = Op.getValueType();
11999   SDLoc dl(Op);
12000   SDValue R = Op.getOperand(0);
12001   SDValue Amt = Op.getOperand(1);
12002
12003   // Optimize shl/srl/sra with constant shift amount.
12004   if (isSplatVector(Amt.getNode())) {
12005     SDValue SclrAmt = Amt->getOperand(0);
12006     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
12007       uint64_t ShiftAmt = C->getZExtValue();
12008
12009       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
12010           (Subtarget->hasInt256() &&
12011            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
12012         if (Op.getOpcode() == ISD::SHL)
12013           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12014                              DAG.getConstant(ShiftAmt, MVT::i32));
12015         if (Op.getOpcode() == ISD::SRL)
12016           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12017                              DAG.getConstant(ShiftAmt, MVT::i32));
12018         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
12019           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12020                              DAG.getConstant(ShiftAmt, MVT::i32));
12021       }
12022
12023       if (VT == MVT::v16i8) {
12024         if (Op.getOpcode() == ISD::SHL) {
12025           // Make a large shift.
12026           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
12027                                     DAG.getConstant(ShiftAmt, MVT::i32));
12028           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12029           // Zero out the rightmost bits.
12030           SmallVector<SDValue, 16> V(16,
12031                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12032                                                      MVT::i8));
12033           return DAG.getNode(ISD::AND, dl, VT, SHL,
12034                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12035         }
12036         if (Op.getOpcode() == ISD::SRL) {
12037           // Make a large shift.
12038           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
12039                                     DAG.getConstant(ShiftAmt, MVT::i32));
12040           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12041           // Zero out the leftmost bits.
12042           SmallVector<SDValue, 16> V(16,
12043                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12044                                                      MVT::i8));
12045           return DAG.getNode(ISD::AND, dl, VT, SRL,
12046                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
12047         }
12048         if (Op.getOpcode() == ISD::SRA) {
12049           if (ShiftAmt == 7) {
12050             // R s>> 7  ===  R s< 0
12051             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12052             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12053           }
12054
12055           // R s>> a === ((R u>> a) ^ m) - m
12056           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12057           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
12058                                                          MVT::i8));
12059           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
12060           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12061           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12062           return Res;
12063         }
12064         llvm_unreachable("Unknown shift opcode.");
12065       }
12066
12067       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
12068         if (Op.getOpcode() == ISD::SHL) {
12069           // Make a large shift.
12070           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
12071                                     DAG.getConstant(ShiftAmt, MVT::i32));
12072           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
12073           // Zero out the rightmost bits.
12074           SmallVector<SDValue, 32> V(32,
12075                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
12076                                                      MVT::i8));
12077           return DAG.getNode(ISD::AND, dl, VT, SHL,
12078                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12079         }
12080         if (Op.getOpcode() == ISD::SRL) {
12081           // Make a large shift.
12082           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
12083                                     DAG.getConstant(ShiftAmt, MVT::i32));
12084           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
12085           // Zero out the leftmost bits.
12086           SmallVector<SDValue, 32> V(32,
12087                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
12088                                                      MVT::i8));
12089           return DAG.getNode(ISD::AND, dl, VT, SRL,
12090                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
12091         }
12092         if (Op.getOpcode() == ISD::SRA) {
12093           if (ShiftAmt == 7) {
12094             // R s>> 7  ===  R s< 0
12095             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12096             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
12097           }
12098
12099           // R s>> a === ((R u>> a) ^ m) - m
12100           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
12101           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
12102                                                          MVT::i8));
12103           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
12104           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
12105           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
12106           return Res;
12107         }
12108         llvm_unreachable("Unknown shift opcode.");
12109       }
12110     }
12111   }
12112
12113   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12114   if (!Subtarget->is64Bit() &&
12115       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12116       Amt.getOpcode() == ISD::BITCAST &&
12117       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12118     Amt = Amt.getOperand(0);
12119     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12120                      VT.getVectorNumElements();
12121     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
12122     uint64_t ShiftAmt = 0;
12123     for (unsigned i = 0; i != Ratio; ++i) {
12124       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
12125       if (C == 0)
12126         return SDValue();
12127       // 6 == Log2(64)
12128       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
12129     }
12130     // Check remaining shift amounts.
12131     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12132       uint64_t ShAmt = 0;
12133       for (unsigned j = 0; j != Ratio; ++j) {
12134         ConstantSDNode *C =
12135           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
12136         if (C == 0)
12137           return SDValue();
12138         // 6 == Log2(64)
12139         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
12140       }
12141       if (ShAmt != ShiftAmt)
12142         return SDValue();
12143     }
12144     switch (Op.getOpcode()) {
12145     default:
12146       llvm_unreachable("Unknown shift opcode!");
12147     case ISD::SHL:
12148       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
12149                          DAG.getConstant(ShiftAmt, MVT::i32));
12150     case ISD::SRL:
12151       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
12152                          DAG.getConstant(ShiftAmt, MVT::i32));
12153     case ISD::SRA:
12154       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
12155                          DAG.getConstant(ShiftAmt, MVT::i32));
12156     }
12157   }
12158
12159   return SDValue();
12160 }
12161
12162 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
12163                                         const X86Subtarget* Subtarget) {
12164   EVT VT = Op.getValueType();
12165   SDLoc dl(Op);
12166   SDValue R = Op.getOperand(0);
12167   SDValue Amt = Op.getOperand(1);
12168
12169   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
12170       VT == MVT::v4i32 || VT == MVT::v8i16 ||
12171       (Subtarget->hasInt256() &&
12172        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
12173         VT == MVT::v8i32 || VT == MVT::v16i16))) {
12174     SDValue BaseShAmt;
12175     EVT EltVT = VT.getVectorElementType();
12176
12177     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12178       unsigned NumElts = VT.getVectorNumElements();
12179       unsigned i, j;
12180       for (i = 0; i != NumElts; ++i) {
12181         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
12182           continue;
12183         break;
12184       }
12185       for (j = i; j != NumElts; ++j) {
12186         SDValue Arg = Amt.getOperand(j);
12187         if (Arg.getOpcode() == ISD::UNDEF) continue;
12188         if (Arg != Amt.getOperand(i))
12189           break;
12190       }
12191       if (i != NumElts && j == NumElts)
12192         BaseShAmt = Amt.getOperand(i);
12193     } else {
12194       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
12195         Amt = Amt.getOperand(0);
12196       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
12197                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
12198         SDValue InVec = Amt.getOperand(0);
12199         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
12200           unsigned NumElts = InVec.getValueType().getVectorNumElements();
12201           unsigned i = 0;
12202           for (; i != NumElts; ++i) {
12203             SDValue Arg = InVec.getOperand(i);
12204             if (Arg.getOpcode() == ISD::UNDEF) continue;
12205             BaseShAmt = Arg;
12206             break;
12207           }
12208         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
12209            if (ConstantSDNode *C =
12210                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
12211              unsigned SplatIdx =
12212                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
12213              if (C->getZExtValue() == SplatIdx)
12214                BaseShAmt = InVec.getOperand(1);
12215            }
12216         }
12217         if (BaseShAmt.getNode() == 0)
12218           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
12219                                   DAG.getIntPtrConstant(0));
12220       }
12221     }
12222
12223     if (BaseShAmt.getNode()) {
12224       if (EltVT.bitsGT(MVT::i32))
12225         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
12226       else if (EltVT.bitsLT(MVT::i32))
12227         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
12228
12229       switch (Op.getOpcode()) {
12230       default:
12231         llvm_unreachable("Unknown shift opcode!");
12232       case ISD::SHL:
12233         switch (VT.getSimpleVT().SimpleTy) {
12234         default: return SDValue();
12235         case MVT::v2i64:
12236         case MVT::v4i32:
12237         case MVT::v8i16:
12238         case MVT::v4i64:
12239         case MVT::v8i32:
12240         case MVT::v16i16:
12241           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
12242         }
12243       case ISD::SRA:
12244         switch (VT.getSimpleVT().SimpleTy) {
12245         default: return SDValue();
12246         case MVT::v4i32:
12247         case MVT::v8i16:
12248         case MVT::v8i32:
12249         case MVT::v16i16:
12250           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
12251         }
12252       case ISD::SRL:
12253         switch (VT.getSimpleVT().SimpleTy) {
12254         default: return SDValue();
12255         case MVT::v2i64:
12256         case MVT::v4i32:
12257         case MVT::v8i16:
12258         case MVT::v4i64:
12259         case MVT::v8i32:
12260         case MVT::v16i16:
12261           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
12262         }
12263       }
12264     }
12265   }
12266
12267   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
12268   if (!Subtarget->is64Bit() &&
12269       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
12270       Amt.getOpcode() == ISD::BITCAST &&
12271       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
12272     Amt = Amt.getOperand(0);
12273     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
12274                      VT.getVectorNumElements();
12275     std::vector<SDValue> Vals(Ratio);
12276     for (unsigned i = 0; i != Ratio; ++i)
12277       Vals[i] = Amt.getOperand(i);
12278     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
12279       for (unsigned j = 0; j != Ratio; ++j)
12280         if (Vals[j] != Amt.getOperand(i + j))
12281           return SDValue();
12282     }
12283     switch (Op.getOpcode()) {
12284     default:
12285       llvm_unreachable("Unknown shift opcode!");
12286     case ISD::SHL:
12287       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
12288     case ISD::SRL:
12289       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
12290     case ISD::SRA:
12291       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
12292     }
12293   }
12294
12295   return SDValue();
12296 }
12297
12298 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
12299
12300   EVT VT = Op.getValueType();
12301   SDLoc dl(Op);
12302   SDValue R = Op.getOperand(0);
12303   SDValue Amt = Op.getOperand(1);
12304   SDValue V;
12305
12306   if (!Subtarget->hasSSE2())
12307     return SDValue();
12308
12309   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
12310   if (V.getNode())
12311     return V;
12312
12313   V = LowerScalarVariableShift(Op, DAG, Subtarget);
12314   if (V.getNode())
12315       return V;
12316
12317   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
12318   if (Subtarget->hasInt256()) {
12319     if (Op.getOpcode() == ISD::SRL &&
12320         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12321          VT == MVT::v4i64 || VT == MVT::v8i32))
12322       return Op;
12323     if (Op.getOpcode() == ISD::SHL &&
12324         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
12325          VT == MVT::v4i64 || VT == MVT::v8i32))
12326       return Op;
12327     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
12328       return Op;
12329   }
12330
12331   // Lower SHL with variable shift amount.
12332   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
12333     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
12334
12335     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
12336     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
12337     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
12338     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
12339   }
12340   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
12341     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
12342
12343     // a = a << 5;
12344     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
12345     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
12346
12347     // Turn 'a' into a mask suitable for VSELECT
12348     SDValue VSelM = DAG.getConstant(0x80, VT);
12349     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12350     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12351
12352     SDValue CM1 = DAG.getConstant(0x0f, VT);
12353     SDValue CM2 = DAG.getConstant(0x3f, VT);
12354
12355     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
12356     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
12357     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12358                             DAG.getConstant(4, MVT::i32), DAG);
12359     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12360     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12361
12362     // a += a
12363     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12364     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12365     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12366
12367     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
12368     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
12369     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
12370                             DAG.getConstant(2, MVT::i32), DAG);
12371     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
12372     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
12373
12374     // a += a
12375     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
12376     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
12377     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
12378
12379     // return VSELECT(r, r+r, a);
12380     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
12381                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
12382     return R;
12383   }
12384
12385   // Decompose 256-bit shifts into smaller 128-bit shifts.
12386   if (VT.is256BitVector()) {
12387     unsigned NumElems = VT.getVectorNumElements();
12388     MVT EltVT = VT.getVectorElementType().getSimpleVT();
12389     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12390
12391     // Extract the two vectors
12392     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
12393     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
12394
12395     // Recreate the shift amount vectors
12396     SDValue Amt1, Amt2;
12397     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
12398       // Constant shift amount
12399       SmallVector<SDValue, 4> Amt1Csts;
12400       SmallVector<SDValue, 4> Amt2Csts;
12401       for (unsigned i = 0; i != NumElems/2; ++i)
12402         Amt1Csts.push_back(Amt->getOperand(i));
12403       for (unsigned i = NumElems/2; i != NumElems; ++i)
12404         Amt2Csts.push_back(Amt->getOperand(i));
12405
12406       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12407                                  &Amt1Csts[0], NumElems/2);
12408       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12409                                  &Amt2Csts[0], NumElems/2);
12410     } else {
12411       // Variable shift amount
12412       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12413       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12414     }
12415
12416     // Issue new vector shifts for the smaller types
12417     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12418     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12419
12420     // Concatenate the result back
12421     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12422   }
12423
12424   return SDValue();
12425 }
12426
12427 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12428   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12429   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12430   // looks for this combo and may remove the "setcc" instruction if the "setcc"
12431   // has only one use.
12432   SDNode *N = Op.getNode();
12433   SDValue LHS = N->getOperand(0);
12434   SDValue RHS = N->getOperand(1);
12435   unsigned BaseOp = 0;
12436   unsigned Cond = 0;
12437   SDLoc DL(Op);
12438   switch (Op.getOpcode()) {
12439   default: llvm_unreachable("Unknown ovf instruction!");
12440   case ISD::SADDO:
12441     // A subtract of one will be selected as a INC. Note that INC doesn't
12442     // set CF, so we can't do this for UADDO.
12443     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12444       if (C->isOne()) {
12445         BaseOp = X86ISD::INC;
12446         Cond = X86::COND_O;
12447         break;
12448       }
12449     BaseOp = X86ISD::ADD;
12450     Cond = X86::COND_O;
12451     break;
12452   case ISD::UADDO:
12453     BaseOp = X86ISD::ADD;
12454     Cond = X86::COND_B;
12455     break;
12456   case ISD::SSUBO:
12457     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12458     // set CF, so we can't do this for USUBO.
12459     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12460       if (C->isOne()) {
12461         BaseOp = X86ISD::DEC;
12462         Cond = X86::COND_O;
12463         break;
12464       }
12465     BaseOp = X86ISD::SUB;
12466     Cond = X86::COND_O;
12467     break;
12468   case ISD::USUBO:
12469     BaseOp = X86ISD::SUB;
12470     Cond = X86::COND_B;
12471     break;
12472   case ISD::SMULO:
12473     BaseOp = X86ISD::SMUL;
12474     Cond = X86::COND_O;
12475     break;
12476   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12477     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12478                                  MVT::i32);
12479     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12480
12481     SDValue SetCC =
12482       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12483                   DAG.getConstant(X86::COND_O, MVT::i32),
12484                   SDValue(Sum.getNode(), 2));
12485
12486     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12487   }
12488   }
12489
12490   // Also sets EFLAGS.
12491   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12492   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12493
12494   SDValue SetCC =
12495     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12496                 DAG.getConstant(Cond, MVT::i32),
12497                 SDValue(Sum.getNode(), 1));
12498
12499   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12500 }
12501
12502 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12503                                                   SelectionDAG &DAG) const {
12504   SDLoc dl(Op);
12505   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12506   EVT VT = Op.getValueType();
12507
12508   if (!Subtarget->hasSSE2() || !VT.isVector())
12509     return SDValue();
12510
12511   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12512                       ExtraVT.getScalarType().getSizeInBits();
12513   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12514
12515   switch (VT.getSimpleVT().SimpleTy) {
12516     default: return SDValue();
12517     case MVT::v8i32:
12518     case MVT::v16i16:
12519       if (!Subtarget->hasFp256())
12520         return SDValue();
12521       if (!Subtarget->hasInt256()) {
12522         // needs to be split
12523         unsigned NumElems = VT.getVectorNumElements();
12524
12525         // Extract the LHS vectors
12526         SDValue LHS = Op.getOperand(0);
12527         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12528         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12529
12530         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12531         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12532
12533         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12534         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12535         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12536                                    ExtraNumElems/2);
12537         SDValue Extra = DAG.getValueType(ExtraVT);
12538
12539         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12540         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12541
12542         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12543       }
12544       // fall through
12545     case MVT::v4i32:
12546     case MVT::v8i16: {
12547       // (sext (vzext x)) -> (vsext x)
12548       SDValue Op0 = Op.getOperand(0);
12549       SDValue Op00 = Op0.getOperand(0);
12550       SDValue Tmp1;
12551       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12552       if (Op0.getOpcode() == ISD::BITCAST &&
12553           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12554         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12555       if (Tmp1.getNode()) {
12556         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12557         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12558                "This optimization is invalid without a VZEXT.");
12559         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12560       }
12561
12562       // If the above didn't work, then just use Shift-Left + Shift-Right.
12563       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12564       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12565     }
12566   }
12567 }
12568
12569 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12570                                  SelectionDAG &DAG) {
12571   SDLoc dl(Op);
12572   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12573     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12574   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12575     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12576
12577   // The only fence that needs an instruction is a sequentially-consistent
12578   // cross-thread fence.
12579   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12580     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12581     // no-sse2). There isn't any reason to disable it if the target processor
12582     // supports it.
12583     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12584       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12585
12586     SDValue Chain = Op.getOperand(0);
12587     SDValue Zero = DAG.getConstant(0, MVT::i32);
12588     SDValue Ops[] = {
12589       DAG.getRegister(X86::ESP, MVT::i32), // Base
12590       DAG.getTargetConstant(1, MVT::i8),   // Scale
12591       DAG.getRegister(0, MVT::i32),        // Index
12592       DAG.getTargetConstant(0, MVT::i32),  // Disp
12593       DAG.getRegister(0, MVT::i32),        // Segment.
12594       Zero,
12595       Chain
12596     };
12597     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12598     return SDValue(Res, 0);
12599   }
12600
12601   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12602   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12603 }
12604
12605 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12606                              SelectionDAG &DAG) {
12607   EVT T = Op.getValueType();
12608   SDLoc DL(Op);
12609   unsigned Reg = 0;
12610   unsigned size = 0;
12611   switch(T.getSimpleVT().SimpleTy) {
12612   default: llvm_unreachable("Invalid value type!");
12613   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12614   case MVT::i16: Reg = X86::AX;  size = 2; break;
12615   case MVT::i32: Reg = X86::EAX; size = 4; break;
12616   case MVT::i64:
12617     assert(Subtarget->is64Bit() && "Node not type legal!");
12618     Reg = X86::RAX; size = 8;
12619     break;
12620   }
12621   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12622                                     Op.getOperand(2), SDValue());
12623   SDValue Ops[] = { cpIn.getValue(0),
12624                     Op.getOperand(1),
12625                     Op.getOperand(3),
12626                     DAG.getTargetConstant(size, MVT::i8),
12627                     cpIn.getValue(1) };
12628   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12629   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12630   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12631                                            Ops, array_lengthof(Ops), T, MMO);
12632   SDValue cpOut =
12633     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12634   return cpOut;
12635 }
12636
12637 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12638                                      SelectionDAG &DAG) {
12639   assert(Subtarget->is64Bit() && "Result not type legalized?");
12640   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12641   SDValue TheChain = Op.getOperand(0);
12642   SDLoc dl(Op);
12643   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12644   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12645   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12646                                    rax.getValue(2));
12647   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12648                             DAG.getConstant(32, MVT::i8));
12649   SDValue Ops[] = {
12650     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12651     rdx.getValue(1)
12652   };
12653   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12654 }
12655
12656 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12657   EVT SrcVT = Op.getOperand(0).getValueType();
12658   EVT DstVT = Op.getValueType();
12659   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12660          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12661   assert((DstVT == MVT::i64 ||
12662           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12663          "Unexpected custom BITCAST");
12664   // i64 <=> MMX conversions are Legal.
12665   if (SrcVT==MVT::i64 && DstVT.isVector())
12666     return Op;
12667   if (DstVT==MVT::i64 && SrcVT.isVector())
12668     return Op;
12669   // MMX <=> MMX conversions are Legal.
12670   if (SrcVT.isVector() && DstVT.isVector())
12671     return Op;
12672   // All other conversions need to be expanded.
12673   return SDValue();
12674 }
12675
12676 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12677   SDNode *Node = Op.getNode();
12678   SDLoc dl(Node);
12679   EVT T = Node->getValueType(0);
12680   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12681                               DAG.getConstant(0, T), Node->getOperand(2));
12682   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12683                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12684                        Node->getOperand(0),
12685                        Node->getOperand(1), negOp,
12686                        cast<AtomicSDNode>(Node)->getSrcValue(),
12687                        cast<AtomicSDNode>(Node)->getAlignment(),
12688                        cast<AtomicSDNode>(Node)->getOrdering(),
12689                        cast<AtomicSDNode>(Node)->getSynchScope());
12690 }
12691
12692 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12693   SDNode *Node = Op.getNode();
12694   SDLoc dl(Node);
12695   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12696
12697   // Convert seq_cst store -> xchg
12698   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12699   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12700   //        (The only way to get a 16-byte store is cmpxchg16b)
12701   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12702   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12703       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12704     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12705                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12706                                  Node->getOperand(0),
12707                                  Node->getOperand(1), Node->getOperand(2),
12708                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12709                                  cast<AtomicSDNode>(Node)->getOrdering(),
12710                                  cast<AtomicSDNode>(Node)->getSynchScope());
12711     return Swap.getValue(1);
12712   }
12713   // Other atomic stores have a simple pattern.
12714   return Op;
12715 }
12716
12717 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12718   EVT VT = Op.getNode()->getValueType(0);
12719
12720   // Let legalize expand this if it isn't a legal type yet.
12721   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12722     return SDValue();
12723
12724   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12725
12726   unsigned Opc;
12727   bool ExtraOp = false;
12728   switch (Op.getOpcode()) {
12729   default: llvm_unreachable("Invalid code");
12730   case ISD::ADDC: Opc = X86ISD::ADD; break;
12731   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12732   case ISD::SUBC: Opc = X86ISD::SUB; break;
12733   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12734   }
12735
12736   if (!ExtraOp)
12737     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12738                        Op.getOperand(1));
12739   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12740                      Op.getOperand(1), Op.getOperand(2));
12741 }
12742
12743 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12744   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12745
12746   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12747   // which returns the values as { float, float } (in XMM0) or
12748   // { double, double } (which is returned in XMM0, XMM1).
12749   SDLoc dl(Op);
12750   SDValue Arg = Op.getOperand(0);
12751   EVT ArgVT = Arg.getValueType();
12752   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12753
12754   ArgListTy Args;
12755   ArgListEntry Entry;
12756
12757   Entry.Node = Arg;
12758   Entry.Ty = ArgTy;
12759   Entry.isSExt = false;
12760   Entry.isZExt = false;
12761   Args.push_back(Entry);
12762
12763   bool isF64 = ArgVT == MVT::f64;
12764   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12765   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12766   // the results are returned via SRet in memory.
12767   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12768   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12769
12770   Type *RetTy = isF64
12771     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12772     : (Type*)VectorType::get(ArgTy, 4);
12773   TargetLowering::
12774     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12775                          false, false, false, false, 0,
12776                          CallingConv::C, /*isTaillCall=*/false,
12777                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12778                          Callee, Args, DAG, dl);
12779   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12780
12781   if (isF64)
12782     // Returned in xmm0 and xmm1.
12783     return CallResult.first;
12784
12785   // Returned in bits 0:31 and 32:64 xmm0.
12786   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12787                                CallResult.first, DAG.getIntPtrConstant(0));
12788   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12789                                CallResult.first, DAG.getIntPtrConstant(1));
12790   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12791   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12792 }
12793
12794 /// LowerOperation - Provide custom lowering hooks for some operations.
12795 ///
12796 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12797   switch (Op.getOpcode()) {
12798   default: llvm_unreachable("Should not custom lower this!");
12799   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12800   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12801   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12802   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12803   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12804   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12805   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12806   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12807   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12808   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12809   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12810   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12811   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12812   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12813   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12814   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12815   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12816   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12817   case ISD::SHL_PARTS:
12818   case ISD::SRA_PARTS:
12819   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12820   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12821   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12822   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12823   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12824   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12825   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12826   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12827   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12828   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12829   case ISD::FABS:               return LowerFABS(Op, DAG);
12830   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12831   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12832   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12833   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12834   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12835   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12836   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12837   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12838   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12839   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12840   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12841   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12842   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12843   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12844   case ISD::FRAME_TO_ARGS_OFFSET:
12845                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12846   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12847   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12848   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12849   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12850   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12851   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12852   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12853   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12854   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12855   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12856   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12857   case ISD::SRA:
12858   case ISD::SRL:
12859   case ISD::SHL:                return LowerShift(Op, DAG);
12860   case ISD::SADDO:
12861   case ISD::UADDO:
12862   case ISD::SSUBO:
12863   case ISD::USUBO:
12864   case ISD::SMULO:
12865   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12866   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12867   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12868   case ISD::ADDC:
12869   case ISD::ADDE:
12870   case ISD::SUBC:
12871   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12872   case ISD::ADD:                return LowerADD(Op, DAG);
12873   case ISD::SUB:                return LowerSUB(Op, DAG);
12874   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12875   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12876   }
12877 }
12878
12879 static void ReplaceATOMIC_LOAD(SDNode *Node,
12880                                   SmallVectorImpl<SDValue> &Results,
12881                                   SelectionDAG &DAG) {
12882   SDLoc dl(Node);
12883   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12884
12885   // Convert wide load -> cmpxchg8b/cmpxchg16b
12886   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12887   //        (The only way to get a 16-byte load is cmpxchg16b)
12888   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12889   SDValue Zero = DAG.getConstant(0, VT);
12890   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12891                                Node->getOperand(0),
12892                                Node->getOperand(1), Zero, Zero,
12893                                cast<AtomicSDNode>(Node)->getMemOperand(),
12894                                cast<AtomicSDNode>(Node)->getOrdering(),
12895                                cast<AtomicSDNode>(Node)->getSynchScope());
12896   Results.push_back(Swap.getValue(0));
12897   Results.push_back(Swap.getValue(1));
12898 }
12899
12900 static void
12901 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12902                         SelectionDAG &DAG, unsigned NewOp) {
12903   SDLoc dl(Node);
12904   assert (Node->getValueType(0) == MVT::i64 &&
12905           "Only know how to expand i64 atomics");
12906
12907   SDValue Chain = Node->getOperand(0);
12908   SDValue In1 = Node->getOperand(1);
12909   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12910                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12911   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12912                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12913   SDValue Ops[] = { Chain, In1, In2L, In2H };
12914   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12915   SDValue Result =
12916     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12917                             cast<MemSDNode>(Node)->getMemOperand());
12918   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12919   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12920   Results.push_back(Result.getValue(2));
12921 }
12922
12923 /// ReplaceNodeResults - Replace a node with an illegal result type
12924 /// with a new node built out of custom code.
12925 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12926                                            SmallVectorImpl<SDValue>&Results,
12927                                            SelectionDAG &DAG) const {
12928   SDLoc dl(N);
12929   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12930   switch (N->getOpcode()) {
12931   default:
12932     llvm_unreachable("Do not know how to custom type legalize this operation!");
12933   case ISD::SIGN_EXTEND_INREG:
12934   case ISD::ADDC:
12935   case ISD::ADDE:
12936   case ISD::SUBC:
12937   case ISD::SUBE:
12938     // We don't want to expand or promote these.
12939     return;
12940   case ISD::FP_TO_SINT:
12941   case ISD::FP_TO_UINT: {
12942     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12943
12944     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12945       return;
12946
12947     std::pair<SDValue,SDValue> Vals =
12948         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12949     SDValue FIST = Vals.first, StackSlot = Vals.second;
12950     if (FIST.getNode() != 0) {
12951       EVT VT = N->getValueType(0);
12952       // Return a load from the stack slot.
12953       if (StackSlot.getNode() != 0)
12954         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12955                                       MachinePointerInfo(),
12956                                       false, false, false, 0));
12957       else
12958         Results.push_back(FIST);
12959     }
12960     return;
12961   }
12962   case ISD::UINT_TO_FP: {
12963     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12964     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12965         N->getValueType(0) != MVT::v2f32)
12966       return;
12967     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12968                                  N->getOperand(0));
12969     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12970                                      MVT::f64);
12971     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12972     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12973                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12974     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12975     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12976     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12977     return;
12978   }
12979   case ISD::FP_ROUND: {
12980     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12981         return;
12982     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12983     Results.push_back(V);
12984     return;
12985   }
12986   case ISD::READCYCLECOUNTER: {
12987     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12988     SDValue TheChain = N->getOperand(0);
12989     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12990     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12991                                      rd.getValue(1));
12992     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12993                                      eax.getValue(2));
12994     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12995     SDValue Ops[] = { eax, edx };
12996     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12997                                   array_lengthof(Ops)));
12998     Results.push_back(edx.getValue(1));
12999     return;
13000   }
13001   case ISD::ATOMIC_CMP_SWAP: {
13002     EVT T = N->getValueType(0);
13003     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
13004     bool Regs64bit = T == MVT::i128;
13005     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
13006     SDValue cpInL, cpInH;
13007     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13008                         DAG.getConstant(0, HalfT));
13009     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
13010                         DAG.getConstant(1, HalfT));
13011     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
13012                              Regs64bit ? X86::RAX : X86::EAX,
13013                              cpInL, SDValue());
13014     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
13015                              Regs64bit ? X86::RDX : X86::EDX,
13016                              cpInH, cpInL.getValue(1));
13017     SDValue swapInL, swapInH;
13018     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13019                           DAG.getConstant(0, HalfT));
13020     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
13021                           DAG.getConstant(1, HalfT));
13022     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
13023                                Regs64bit ? X86::RBX : X86::EBX,
13024                                swapInL, cpInH.getValue(1));
13025     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
13026                                Regs64bit ? X86::RCX : X86::ECX,
13027                                swapInH, swapInL.getValue(1));
13028     SDValue Ops[] = { swapInH.getValue(0),
13029                       N->getOperand(1),
13030                       swapInH.getValue(1) };
13031     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13032     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
13033     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
13034                                   X86ISD::LCMPXCHG8_DAG;
13035     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
13036                                              Ops, array_lengthof(Ops), T, MMO);
13037     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
13038                                         Regs64bit ? X86::RAX : X86::EAX,
13039                                         HalfT, Result.getValue(1));
13040     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
13041                                         Regs64bit ? X86::RDX : X86::EDX,
13042                                         HalfT, cpOutL.getValue(2));
13043     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
13044     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
13045     Results.push_back(cpOutH.getValue(1));
13046     return;
13047   }
13048   case ISD::ATOMIC_LOAD_ADD:
13049   case ISD::ATOMIC_LOAD_AND:
13050   case ISD::ATOMIC_LOAD_NAND:
13051   case ISD::ATOMIC_LOAD_OR:
13052   case ISD::ATOMIC_LOAD_SUB:
13053   case ISD::ATOMIC_LOAD_XOR:
13054   case ISD::ATOMIC_LOAD_MAX:
13055   case ISD::ATOMIC_LOAD_MIN:
13056   case ISD::ATOMIC_LOAD_UMAX:
13057   case ISD::ATOMIC_LOAD_UMIN:
13058   case ISD::ATOMIC_SWAP: {
13059     unsigned Opc;
13060     switch (N->getOpcode()) {
13061     default: llvm_unreachable("Unexpected opcode");
13062     case ISD::ATOMIC_LOAD_ADD:
13063       Opc = X86ISD::ATOMADD64_DAG;
13064       break;
13065     case ISD::ATOMIC_LOAD_AND:
13066       Opc = X86ISD::ATOMAND64_DAG;
13067       break;
13068     case ISD::ATOMIC_LOAD_NAND:
13069       Opc = X86ISD::ATOMNAND64_DAG;
13070       break;
13071     case ISD::ATOMIC_LOAD_OR:
13072       Opc = X86ISD::ATOMOR64_DAG;
13073       break;
13074     case ISD::ATOMIC_LOAD_SUB:
13075       Opc = X86ISD::ATOMSUB64_DAG;
13076       break;
13077     case ISD::ATOMIC_LOAD_XOR:
13078       Opc = X86ISD::ATOMXOR64_DAG;
13079       break;
13080     case ISD::ATOMIC_LOAD_MAX:
13081       Opc = X86ISD::ATOMMAX64_DAG;
13082       break;
13083     case ISD::ATOMIC_LOAD_MIN:
13084       Opc = X86ISD::ATOMMIN64_DAG;
13085       break;
13086     case ISD::ATOMIC_LOAD_UMAX:
13087       Opc = X86ISD::ATOMUMAX64_DAG;
13088       break;
13089     case ISD::ATOMIC_LOAD_UMIN:
13090       Opc = X86ISD::ATOMUMIN64_DAG;
13091       break;
13092     case ISD::ATOMIC_SWAP:
13093       Opc = X86ISD::ATOMSWAP64_DAG;
13094       break;
13095     }
13096     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
13097     return;
13098   }
13099   case ISD::ATOMIC_LOAD:
13100     ReplaceATOMIC_LOAD(N, Results, DAG);
13101   }
13102 }
13103
13104 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
13105   switch (Opcode) {
13106   default: return NULL;
13107   case X86ISD::BSF:                return "X86ISD::BSF";
13108   case X86ISD::BSR:                return "X86ISD::BSR";
13109   case X86ISD::SHLD:               return "X86ISD::SHLD";
13110   case X86ISD::SHRD:               return "X86ISD::SHRD";
13111   case X86ISD::FAND:               return "X86ISD::FAND";
13112   case X86ISD::FANDN:              return "X86ISD::FANDN";
13113   case X86ISD::FOR:                return "X86ISD::FOR";
13114   case X86ISD::FXOR:               return "X86ISD::FXOR";
13115   case X86ISD::FSRL:               return "X86ISD::FSRL";
13116   case X86ISD::FILD:               return "X86ISD::FILD";
13117   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
13118   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
13119   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
13120   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
13121   case X86ISD::FLD:                return "X86ISD::FLD";
13122   case X86ISD::FST:                return "X86ISD::FST";
13123   case X86ISD::CALL:               return "X86ISD::CALL";
13124   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
13125   case X86ISD::BT:                 return "X86ISD::BT";
13126   case X86ISD::CMP:                return "X86ISD::CMP";
13127   case X86ISD::COMI:               return "X86ISD::COMI";
13128   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
13129   case X86ISD::SETCC:              return "X86ISD::SETCC";
13130   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
13131   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
13132   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
13133   case X86ISD::CMOV:               return "X86ISD::CMOV";
13134   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
13135   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
13136   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
13137   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
13138   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
13139   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
13140   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
13141   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
13142   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
13143   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
13144   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
13145   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
13146   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
13147   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
13148   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
13149   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
13150   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
13151   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
13152   case X86ISD::HADD:               return "X86ISD::HADD";
13153   case X86ISD::HSUB:               return "X86ISD::HSUB";
13154   case X86ISD::FHADD:              return "X86ISD::FHADD";
13155   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
13156   case X86ISD::UMAX:               return "X86ISD::UMAX";
13157   case X86ISD::UMIN:               return "X86ISD::UMIN";
13158   case X86ISD::SMAX:               return "X86ISD::SMAX";
13159   case X86ISD::SMIN:               return "X86ISD::SMIN";
13160   case X86ISD::FMAX:               return "X86ISD::FMAX";
13161   case X86ISD::FMIN:               return "X86ISD::FMIN";
13162   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
13163   case X86ISD::FMINC:              return "X86ISD::FMINC";
13164   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
13165   case X86ISD::FRCP:               return "X86ISD::FRCP";
13166   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
13167   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
13168   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
13169   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
13170   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
13171   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
13172   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
13173   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
13174   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
13175   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
13176   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
13177   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
13178   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
13179   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
13180   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
13181   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
13182   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
13183   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
13184   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
13185   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
13186   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
13187   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
13188   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
13189   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
13190   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
13191   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
13192   case X86ISD::VSHL:               return "X86ISD::VSHL";
13193   case X86ISD::VSRL:               return "X86ISD::VSRL";
13194   case X86ISD::VSRA:               return "X86ISD::VSRA";
13195   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
13196   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
13197   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
13198   case X86ISD::CMPP:               return "X86ISD::CMPP";
13199   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
13200   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
13201   case X86ISD::ADD:                return "X86ISD::ADD";
13202   case X86ISD::SUB:                return "X86ISD::SUB";
13203   case X86ISD::ADC:                return "X86ISD::ADC";
13204   case X86ISD::SBB:                return "X86ISD::SBB";
13205   case X86ISD::SMUL:               return "X86ISD::SMUL";
13206   case X86ISD::UMUL:               return "X86ISD::UMUL";
13207   case X86ISD::INC:                return "X86ISD::INC";
13208   case X86ISD::DEC:                return "X86ISD::DEC";
13209   case X86ISD::OR:                 return "X86ISD::OR";
13210   case X86ISD::XOR:                return "X86ISD::XOR";
13211   case X86ISD::AND:                return "X86ISD::AND";
13212   case X86ISD::BLSI:               return "X86ISD::BLSI";
13213   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
13214   case X86ISD::BLSR:               return "X86ISD::BLSR";
13215   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
13216   case X86ISD::PTEST:              return "X86ISD::PTEST";
13217   case X86ISD::TESTP:              return "X86ISD::TESTP";
13218   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
13219   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
13220   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
13221   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
13222   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
13223   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
13224   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
13225   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
13226   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
13227   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
13228   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
13229   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
13230   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
13231   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
13232   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
13233   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
13234   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
13235   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
13236   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
13237   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
13238   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
13239   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
13240   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
13241   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
13242   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
13243   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
13244   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
13245   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
13246   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
13247   case X86ISD::SAHF:               return "X86ISD::SAHF";
13248   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
13249   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
13250   case X86ISD::FMADD:              return "X86ISD::FMADD";
13251   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
13252   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
13253   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
13254   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
13255   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
13256   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
13257   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
13258   case X86ISD::XTEST:              return "X86ISD::XTEST";
13259   }
13260 }
13261
13262 // isLegalAddressingMode - Return true if the addressing mode represented
13263 // by AM is legal for this target, for a load/store of the specified type.
13264 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
13265                                               Type *Ty) const {
13266   // X86 supports extremely general addressing modes.
13267   CodeModel::Model M = getTargetMachine().getCodeModel();
13268   Reloc::Model R = getTargetMachine().getRelocationModel();
13269
13270   // X86 allows a sign-extended 32-bit immediate field as a displacement.
13271   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
13272     return false;
13273
13274   if (AM.BaseGV) {
13275     unsigned GVFlags =
13276       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
13277
13278     // If a reference to this global requires an extra load, we can't fold it.
13279     if (isGlobalStubReference(GVFlags))
13280       return false;
13281
13282     // If BaseGV requires a register for the PIC base, we cannot also have a
13283     // BaseReg specified.
13284     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
13285       return false;
13286
13287     // If lower 4G is not available, then we must use rip-relative addressing.
13288     if ((M != CodeModel::Small || R != Reloc::Static) &&
13289         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
13290       return false;
13291   }
13292
13293   switch (AM.Scale) {
13294   case 0:
13295   case 1:
13296   case 2:
13297   case 4:
13298   case 8:
13299     // These scales always work.
13300     break;
13301   case 3:
13302   case 5:
13303   case 9:
13304     // These scales are formed with basereg+scalereg.  Only accept if there is
13305     // no basereg yet.
13306     if (AM.HasBaseReg)
13307       return false;
13308     break;
13309   default:  // Other stuff never works.
13310     return false;
13311   }
13312
13313   return true;
13314 }
13315
13316 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13317   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13318     return false;
13319   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13320   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13321   return NumBits1 > NumBits2;
13322 }
13323
13324 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
13325   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13326     return false;
13327
13328   if (!isTypeLegal(EVT::getEVT(Ty1)))
13329     return false;
13330
13331   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
13332
13333   // Assuming the caller doesn't have a zeroext or signext return parameter,
13334   // truncation all the way down to i1 is valid.
13335   return true;
13336 }
13337
13338 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13339   return isInt<32>(Imm);
13340 }
13341
13342 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
13343   // Can also use sub to handle negated immediates.
13344   return isInt<32>(Imm);
13345 }
13346
13347 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13348   if (!VT1.isInteger() || !VT2.isInteger())
13349     return false;
13350   unsigned NumBits1 = VT1.getSizeInBits();
13351   unsigned NumBits2 = VT2.getSizeInBits();
13352   return NumBits1 > NumBits2;
13353 }
13354
13355 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
13356   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13357   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
13358 }
13359
13360 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
13361   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
13362   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
13363 }
13364
13365 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13366   EVT VT1 = Val.getValueType();
13367   if (isZExtFree(VT1, VT2))
13368     return true;
13369
13370   if (Val.getOpcode() != ISD::LOAD)
13371     return false;
13372
13373   if (!VT1.isSimple() || !VT1.isInteger() ||
13374       !VT2.isSimple() || !VT2.isInteger())
13375     return false;
13376
13377   switch (VT1.getSimpleVT().SimpleTy) {
13378   default: break;
13379   case MVT::i8:
13380   case MVT::i16:
13381   case MVT::i32:
13382     // X86 has 8, 16, and 32-bit zero-extending loads.
13383     return true;
13384   }
13385
13386   return false;
13387 }
13388
13389 bool
13390 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13391   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
13392     return false;
13393
13394   VT = VT.getScalarType();
13395
13396   if (!VT.isSimple())
13397     return false;
13398
13399   switch (VT.getSimpleVT().SimpleTy) {
13400   case MVT::f32:
13401   case MVT::f64:
13402     return true;
13403   default:
13404     break;
13405   }
13406
13407   return false;
13408 }
13409
13410 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
13411   // i16 instructions are longer (0x66 prefix) and potentially slower.
13412   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
13413 }
13414
13415 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13416 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13417 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13418 /// are assumed to be legal.
13419 bool
13420 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13421                                       EVT VT) const {
13422   // Very little shuffling can be done for 64-bit vectors right now.
13423   if (VT.getSizeInBits() == 64)
13424     return false;
13425
13426   // FIXME: pshufb, blends, shifts.
13427   return (VT.getVectorNumElements() == 2 ||
13428           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13429           isMOVLMask(M, VT) ||
13430           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
13431           isPSHUFDMask(M, VT) ||
13432           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
13433           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
13434           isPALIGNRMask(M, VT, Subtarget) ||
13435           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
13436           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
13437           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
13438           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13439 }
13440
13441 bool
13442 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13443                                           EVT VT) const {
13444   unsigned NumElts = VT.getVectorNumElements();
13445   // FIXME: This collection of masks seems suspect.
13446   if (NumElts == 2)
13447     return true;
13448   if (NumElts == 4 && VT.is128BitVector()) {
13449     return (isMOVLMask(Mask, VT)  ||
13450             isCommutedMOVLMask(Mask, VT, true) ||
13451             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13452             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13453   }
13454   return false;
13455 }
13456
13457 //===----------------------------------------------------------------------===//
13458 //                           X86 Scheduler Hooks
13459 //===----------------------------------------------------------------------===//
13460
13461 /// Utility function to emit xbegin specifying the start of an RTM region.
13462 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13463                                      const TargetInstrInfo *TII) {
13464   DebugLoc DL = MI->getDebugLoc();
13465
13466   const BasicBlock *BB = MBB->getBasicBlock();
13467   MachineFunction::iterator I = MBB;
13468   ++I;
13469
13470   // For the v = xbegin(), we generate
13471   //
13472   // thisMBB:
13473   //  xbegin sinkMBB
13474   //
13475   // mainMBB:
13476   //  eax = -1
13477   //
13478   // sinkMBB:
13479   //  v = eax
13480
13481   MachineBasicBlock *thisMBB = MBB;
13482   MachineFunction *MF = MBB->getParent();
13483   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13484   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13485   MF->insert(I, mainMBB);
13486   MF->insert(I, sinkMBB);
13487
13488   // Transfer the remainder of BB and its successor edges to sinkMBB.
13489   sinkMBB->splice(sinkMBB->begin(), MBB,
13490                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13491   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13492
13493   // thisMBB:
13494   //  xbegin sinkMBB
13495   //  # fallthrough to mainMBB
13496   //  # abortion to sinkMBB
13497   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13498   thisMBB->addSuccessor(mainMBB);
13499   thisMBB->addSuccessor(sinkMBB);
13500
13501   // mainMBB:
13502   //  EAX = -1
13503   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13504   mainMBB->addSuccessor(sinkMBB);
13505
13506   // sinkMBB:
13507   // EAX is live into the sinkMBB
13508   sinkMBB->addLiveIn(X86::EAX);
13509   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13510           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13511     .addReg(X86::EAX);
13512
13513   MI->eraseFromParent();
13514   return sinkMBB;
13515 }
13516
13517 // Get CMPXCHG opcode for the specified data type.
13518 static unsigned getCmpXChgOpcode(EVT VT) {
13519   switch (VT.getSimpleVT().SimpleTy) {
13520   case MVT::i8:  return X86::LCMPXCHG8;
13521   case MVT::i16: return X86::LCMPXCHG16;
13522   case MVT::i32: return X86::LCMPXCHG32;
13523   case MVT::i64: return X86::LCMPXCHG64;
13524   default:
13525     break;
13526   }
13527   llvm_unreachable("Invalid operand size!");
13528 }
13529
13530 // Get LOAD opcode for the specified data type.
13531 static unsigned getLoadOpcode(EVT VT) {
13532   switch (VT.getSimpleVT().SimpleTy) {
13533   case MVT::i8:  return X86::MOV8rm;
13534   case MVT::i16: return X86::MOV16rm;
13535   case MVT::i32: return X86::MOV32rm;
13536   case MVT::i64: return X86::MOV64rm;
13537   default:
13538     break;
13539   }
13540   llvm_unreachable("Invalid operand size!");
13541 }
13542
13543 // Get opcode of the non-atomic one from the specified atomic instruction.
13544 static unsigned getNonAtomicOpcode(unsigned Opc) {
13545   switch (Opc) {
13546   case X86::ATOMAND8:  return X86::AND8rr;
13547   case X86::ATOMAND16: return X86::AND16rr;
13548   case X86::ATOMAND32: return X86::AND32rr;
13549   case X86::ATOMAND64: return X86::AND64rr;
13550   case X86::ATOMOR8:   return X86::OR8rr;
13551   case X86::ATOMOR16:  return X86::OR16rr;
13552   case X86::ATOMOR32:  return X86::OR32rr;
13553   case X86::ATOMOR64:  return X86::OR64rr;
13554   case X86::ATOMXOR8:  return X86::XOR8rr;
13555   case X86::ATOMXOR16: return X86::XOR16rr;
13556   case X86::ATOMXOR32: return X86::XOR32rr;
13557   case X86::ATOMXOR64: return X86::XOR64rr;
13558   }
13559   llvm_unreachable("Unhandled atomic-load-op opcode!");
13560 }
13561
13562 // Get opcode of the non-atomic one from the specified atomic instruction with
13563 // extra opcode.
13564 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13565                                                unsigned &ExtraOpc) {
13566   switch (Opc) {
13567   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13568   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13569   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13570   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13571   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13572   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13573   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13574   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13575   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13576   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13577   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13578   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13579   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13580   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13581   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13582   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13583   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13584   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13585   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13586   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13587   }
13588   llvm_unreachable("Unhandled atomic-load-op opcode!");
13589 }
13590
13591 // Get opcode of the non-atomic one from the specified atomic instruction for
13592 // 64-bit data type on 32-bit target.
13593 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13594   switch (Opc) {
13595   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13596   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13597   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13598   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13599   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13600   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13601   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13602   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13603   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13604   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13605   }
13606   llvm_unreachable("Unhandled atomic-load-op opcode!");
13607 }
13608
13609 // Get opcode of the non-atomic one from the specified atomic instruction for
13610 // 64-bit data type on 32-bit target with extra opcode.
13611 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13612                                                    unsigned &HiOpc,
13613                                                    unsigned &ExtraOpc) {
13614   switch (Opc) {
13615   case X86::ATOMNAND6432:
13616     ExtraOpc = X86::NOT32r;
13617     HiOpc = X86::AND32rr;
13618     return X86::AND32rr;
13619   }
13620   llvm_unreachable("Unhandled atomic-load-op opcode!");
13621 }
13622
13623 // Get pseudo CMOV opcode from the specified data type.
13624 static unsigned getPseudoCMOVOpc(EVT VT) {
13625   switch (VT.getSimpleVT().SimpleTy) {
13626   case MVT::i8:  return X86::CMOV_GR8;
13627   case MVT::i16: return X86::CMOV_GR16;
13628   case MVT::i32: return X86::CMOV_GR32;
13629   default:
13630     break;
13631   }
13632   llvm_unreachable("Unknown CMOV opcode!");
13633 }
13634
13635 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13636 // They will be translated into a spin-loop or compare-exchange loop from
13637 //
13638 //    ...
13639 //    dst = atomic-fetch-op MI.addr, MI.val
13640 //    ...
13641 //
13642 // to
13643 //
13644 //    ...
13645 //    t1 = LOAD MI.addr
13646 // loop:
13647 //    t4 = phi(t1, t3 / loop)
13648 //    t2 = OP MI.val, t4
13649 //    EAX = t4
13650 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13651 //    t3 = EAX
13652 //    JNE loop
13653 // sink:
13654 //    dst = t3
13655 //    ...
13656 MachineBasicBlock *
13657 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13658                                        MachineBasicBlock *MBB) const {
13659   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13660   DebugLoc DL = MI->getDebugLoc();
13661
13662   MachineFunction *MF = MBB->getParent();
13663   MachineRegisterInfo &MRI = MF->getRegInfo();
13664
13665   const BasicBlock *BB = MBB->getBasicBlock();
13666   MachineFunction::iterator I = MBB;
13667   ++I;
13668
13669   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13670          "Unexpected number of operands");
13671
13672   assert(MI->hasOneMemOperand() &&
13673          "Expected atomic-load-op to have one memoperand");
13674
13675   // Memory Reference
13676   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13677   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13678
13679   unsigned DstReg, SrcReg;
13680   unsigned MemOpndSlot;
13681
13682   unsigned CurOp = 0;
13683
13684   DstReg = MI->getOperand(CurOp++).getReg();
13685   MemOpndSlot = CurOp;
13686   CurOp += X86::AddrNumOperands;
13687   SrcReg = MI->getOperand(CurOp++).getReg();
13688
13689   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13690   MVT::SimpleValueType VT = *RC->vt_begin();
13691   unsigned t1 = MRI.createVirtualRegister(RC);
13692   unsigned t2 = MRI.createVirtualRegister(RC);
13693   unsigned t3 = MRI.createVirtualRegister(RC);
13694   unsigned t4 = MRI.createVirtualRegister(RC);
13695   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13696
13697   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13698   unsigned LOADOpc = getLoadOpcode(VT);
13699
13700   // For the atomic load-arith operator, we generate
13701   //
13702   //  thisMBB:
13703   //    t1 = LOAD [MI.addr]
13704   //  mainMBB:
13705   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13706   //    t1 = OP MI.val, EAX
13707   //    EAX = t4
13708   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13709   //    t3 = EAX
13710   //    JNE mainMBB
13711   //  sinkMBB:
13712   //    dst = t3
13713
13714   MachineBasicBlock *thisMBB = MBB;
13715   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13716   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13717   MF->insert(I, mainMBB);
13718   MF->insert(I, sinkMBB);
13719
13720   MachineInstrBuilder MIB;
13721
13722   // Transfer the remainder of BB and its successor edges to sinkMBB.
13723   sinkMBB->splice(sinkMBB->begin(), MBB,
13724                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13725   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13726
13727   // thisMBB:
13728   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13729   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13730     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13731     if (NewMO.isReg())
13732       NewMO.setIsKill(false);
13733     MIB.addOperand(NewMO);
13734   }
13735   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13736     unsigned flags = (*MMOI)->getFlags();
13737     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13738     MachineMemOperand *MMO =
13739       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13740                                (*MMOI)->getSize(),
13741                                (*MMOI)->getBaseAlignment(),
13742                                (*MMOI)->getTBAAInfo(),
13743                                (*MMOI)->getRanges());
13744     MIB.addMemOperand(MMO);
13745   }
13746
13747   thisMBB->addSuccessor(mainMBB);
13748
13749   // mainMBB:
13750   MachineBasicBlock *origMainMBB = mainMBB;
13751
13752   // Add a PHI.
13753   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13754                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13755
13756   unsigned Opc = MI->getOpcode();
13757   switch (Opc) {
13758   default:
13759     llvm_unreachable("Unhandled atomic-load-op opcode!");
13760   case X86::ATOMAND8:
13761   case X86::ATOMAND16:
13762   case X86::ATOMAND32:
13763   case X86::ATOMAND64:
13764   case X86::ATOMOR8:
13765   case X86::ATOMOR16:
13766   case X86::ATOMOR32:
13767   case X86::ATOMOR64:
13768   case X86::ATOMXOR8:
13769   case X86::ATOMXOR16:
13770   case X86::ATOMXOR32:
13771   case X86::ATOMXOR64: {
13772     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13773     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13774       .addReg(t4);
13775     break;
13776   }
13777   case X86::ATOMNAND8:
13778   case X86::ATOMNAND16:
13779   case X86::ATOMNAND32:
13780   case X86::ATOMNAND64: {
13781     unsigned Tmp = MRI.createVirtualRegister(RC);
13782     unsigned NOTOpc;
13783     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13784     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13785       .addReg(t4);
13786     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13787     break;
13788   }
13789   case X86::ATOMMAX8:
13790   case X86::ATOMMAX16:
13791   case X86::ATOMMAX32:
13792   case X86::ATOMMAX64:
13793   case X86::ATOMMIN8:
13794   case X86::ATOMMIN16:
13795   case X86::ATOMMIN32:
13796   case X86::ATOMMIN64:
13797   case X86::ATOMUMAX8:
13798   case X86::ATOMUMAX16:
13799   case X86::ATOMUMAX32:
13800   case X86::ATOMUMAX64:
13801   case X86::ATOMUMIN8:
13802   case X86::ATOMUMIN16:
13803   case X86::ATOMUMIN32:
13804   case X86::ATOMUMIN64: {
13805     unsigned CMPOpc;
13806     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13807
13808     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13809       .addReg(SrcReg)
13810       .addReg(t4);
13811
13812     if (Subtarget->hasCMov()) {
13813       if (VT != MVT::i8) {
13814         // Native support
13815         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13816           .addReg(SrcReg)
13817           .addReg(t4);
13818       } else {
13819         // Promote i8 to i32 to use CMOV32
13820         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13821         const TargetRegisterClass *RC32 =
13822           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13823         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13824         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13825         unsigned Tmp = MRI.createVirtualRegister(RC32);
13826
13827         unsigned Undef = MRI.createVirtualRegister(RC32);
13828         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13829
13830         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13831           .addReg(Undef)
13832           .addReg(SrcReg)
13833           .addImm(X86::sub_8bit);
13834         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13835           .addReg(Undef)
13836           .addReg(t4)
13837           .addImm(X86::sub_8bit);
13838
13839         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13840           .addReg(SrcReg32)
13841           .addReg(AccReg32);
13842
13843         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13844           .addReg(Tmp, 0, X86::sub_8bit);
13845       }
13846     } else {
13847       // Use pseudo select and lower them.
13848       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13849              "Invalid atomic-load-op transformation!");
13850       unsigned SelOpc = getPseudoCMOVOpc(VT);
13851       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13852       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13853       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13854               .addReg(SrcReg).addReg(t4)
13855               .addImm(CC);
13856       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13857       // Replace the original PHI node as mainMBB is changed after CMOV
13858       // lowering.
13859       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13860         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13861       Phi->eraseFromParent();
13862     }
13863     break;
13864   }
13865   }
13866
13867   // Copy PhyReg back from virtual register.
13868   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13869     .addReg(t4);
13870
13871   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13872   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13873     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13874     if (NewMO.isReg())
13875       NewMO.setIsKill(false);
13876     MIB.addOperand(NewMO);
13877   }
13878   MIB.addReg(t2);
13879   MIB.setMemRefs(MMOBegin, MMOEnd);
13880
13881   // Copy PhyReg back to virtual register.
13882   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13883     .addReg(PhyReg);
13884
13885   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13886
13887   mainMBB->addSuccessor(origMainMBB);
13888   mainMBB->addSuccessor(sinkMBB);
13889
13890   // sinkMBB:
13891   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13892           TII->get(TargetOpcode::COPY), DstReg)
13893     .addReg(t3);
13894
13895   MI->eraseFromParent();
13896   return sinkMBB;
13897 }
13898
13899 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13900 // instructions. They will be translated into a spin-loop or compare-exchange
13901 // loop from
13902 //
13903 //    ...
13904 //    dst = atomic-fetch-op MI.addr, MI.val
13905 //    ...
13906 //
13907 // to
13908 //
13909 //    ...
13910 //    t1L = LOAD [MI.addr + 0]
13911 //    t1H = LOAD [MI.addr + 4]
13912 // loop:
13913 //    t4L = phi(t1L, t3L / loop)
13914 //    t4H = phi(t1H, t3H / loop)
13915 //    t2L = OP MI.val.lo, t4L
13916 //    t2H = OP MI.val.hi, t4H
13917 //    EAX = t4L
13918 //    EDX = t4H
13919 //    EBX = t2L
13920 //    ECX = t2H
13921 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13922 //    t3L = EAX
13923 //    t3H = EDX
13924 //    JNE loop
13925 // sink:
13926 //    dstL = t3L
13927 //    dstH = t3H
13928 //    ...
13929 MachineBasicBlock *
13930 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13931                                            MachineBasicBlock *MBB) const {
13932   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13933   DebugLoc DL = MI->getDebugLoc();
13934
13935   MachineFunction *MF = MBB->getParent();
13936   MachineRegisterInfo &MRI = MF->getRegInfo();
13937
13938   const BasicBlock *BB = MBB->getBasicBlock();
13939   MachineFunction::iterator I = MBB;
13940   ++I;
13941
13942   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13943          "Unexpected number of operands");
13944
13945   assert(MI->hasOneMemOperand() &&
13946          "Expected atomic-load-op32 to have one memoperand");
13947
13948   // Memory Reference
13949   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13950   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13951
13952   unsigned DstLoReg, DstHiReg;
13953   unsigned SrcLoReg, SrcHiReg;
13954   unsigned MemOpndSlot;
13955
13956   unsigned CurOp = 0;
13957
13958   DstLoReg = MI->getOperand(CurOp++).getReg();
13959   DstHiReg = MI->getOperand(CurOp++).getReg();
13960   MemOpndSlot = CurOp;
13961   CurOp += X86::AddrNumOperands;
13962   SrcLoReg = MI->getOperand(CurOp++).getReg();
13963   SrcHiReg = MI->getOperand(CurOp++).getReg();
13964
13965   const TargetRegisterClass *RC = &X86::GR32RegClass;
13966   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13967
13968   unsigned t1L = MRI.createVirtualRegister(RC);
13969   unsigned t1H = MRI.createVirtualRegister(RC);
13970   unsigned t2L = MRI.createVirtualRegister(RC);
13971   unsigned t2H = MRI.createVirtualRegister(RC);
13972   unsigned t3L = MRI.createVirtualRegister(RC);
13973   unsigned t3H = MRI.createVirtualRegister(RC);
13974   unsigned t4L = MRI.createVirtualRegister(RC);
13975   unsigned t4H = MRI.createVirtualRegister(RC);
13976
13977   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13978   unsigned LOADOpc = X86::MOV32rm;
13979
13980   // For the atomic load-arith operator, we generate
13981   //
13982   //  thisMBB:
13983   //    t1L = LOAD [MI.addr + 0]
13984   //    t1H = LOAD [MI.addr + 4]
13985   //  mainMBB:
13986   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13987   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13988   //    t2L = OP MI.val.lo, t4L
13989   //    t2H = OP MI.val.hi, t4H
13990   //    EBX = t2L
13991   //    ECX = t2H
13992   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13993   //    t3L = EAX
13994   //    t3H = EDX
13995   //    JNE loop
13996   //  sinkMBB:
13997   //    dstL = t3L
13998   //    dstH = t3H
13999
14000   MachineBasicBlock *thisMBB = MBB;
14001   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14002   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14003   MF->insert(I, mainMBB);
14004   MF->insert(I, sinkMBB);
14005
14006   MachineInstrBuilder MIB;
14007
14008   // Transfer the remainder of BB and its successor edges to sinkMBB.
14009   sinkMBB->splice(sinkMBB->begin(), MBB,
14010                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14011   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14012
14013   // thisMBB:
14014   // Lo
14015   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
14016   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14017     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14018     if (NewMO.isReg())
14019       NewMO.setIsKill(false);
14020     MIB.addOperand(NewMO);
14021   }
14022   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
14023     unsigned flags = (*MMOI)->getFlags();
14024     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
14025     MachineMemOperand *MMO =
14026       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
14027                                (*MMOI)->getSize(),
14028                                (*MMOI)->getBaseAlignment(),
14029                                (*MMOI)->getTBAAInfo(),
14030                                (*MMOI)->getRanges());
14031     MIB.addMemOperand(MMO);
14032   };
14033   MachineInstr *LowMI = MIB;
14034
14035   // Hi
14036   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
14037   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14038     if (i == X86::AddrDisp) {
14039       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
14040     } else {
14041       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
14042       if (NewMO.isReg())
14043         NewMO.setIsKill(false);
14044       MIB.addOperand(NewMO);
14045     }
14046   }
14047   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
14048
14049   thisMBB->addSuccessor(mainMBB);
14050
14051   // mainMBB:
14052   MachineBasicBlock *origMainMBB = mainMBB;
14053
14054   // Add PHIs.
14055   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
14056                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14057   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
14058                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14059
14060   unsigned Opc = MI->getOpcode();
14061   switch (Opc) {
14062   default:
14063     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
14064   case X86::ATOMAND6432:
14065   case X86::ATOMOR6432:
14066   case X86::ATOMXOR6432:
14067   case X86::ATOMADD6432:
14068   case X86::ATOMSUB6432: {
14069     unsigned HiOpc;
14070     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14071     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
14072       .addReg(SrcLoReg);
14073     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
14074       .addReg(SrcHiReg);
14075     break;
14076   }
14077   case X86::ATOMNAND6432: {
14078     unsigned HiOpc, NOTOpc;
14079     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
14080     unsigned TmpL = MRI.createVirtualRegister(RC);
14081     unsigned TmpH = MRI.createVirtualRegister(RC);
14082     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
14083       .addReg(t4L);
14084     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
14085       .addReg(t4H);
14086     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
14087     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
14088     break;
14089   }
14090   case X86::ATOMMAX6432:
14091   case X86::ATOMMIN6432:
14092   case X86::ATOMUMAX6432:
14093   case X86::ATOMUMIN6432: {
14094     unsigned HiOpc;
14095     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14096     unsigned cL = MRI.createVirtualRegister(RC8);
14097     unsigned cH = MRI.createVirtualRegister(RC8);
14098     unsigned cL32 = MRI.createVirtualRegister(RC);
14099     unsigned cH32 = MRI.createVirtualRegister(RC);
14100     unsigned cc = MRI.createVirtualRegister(RC);
14101     // cl := cmp src_lo, lo
14102     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14103       .addReg(SrcLoReg).addReg(t4L);
14104     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
14105     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
14106     // ch := cmp src_hi, hi
14107     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
14108       .addReg(SrcHiReg).addReg(t4H);
14109     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
14110     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
14111     // cc := if (src_hi == hi) ? cl : ch;
14112     if (Subtarget->hasCMov()) {
14113       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
14114         .addReg(cH32).addReg(cL32);
14115     } else {
14116       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
14117               .addReg(cH32).addReg(cL32)
14118               .addImm(X86::COND_E);
14119       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14120     }
14121     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
14122     if (Subtarget->hasCMov()) {
14123       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
14124         .addReg(SrcLoReg).addReg(t4L);
14125       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
14126         .addReg(SrcHiReg).addReg(t4H);
14127     } else {
14128       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
14129               .addReg(SrcLoReg).addReg(t4L)
14130               .addImm(X86::COND_NE);
14131       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14132       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
14133       // 2nd CMOV lowering.
14134       mainMBB->addLiveIn(X86::EFLAGS);
14135       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
14136               .addReg(SrcHiReg).addReg(t4H)
14137               .addImm(X86::COND_NE);
14138       mainMBB = EmitLoweredSelect(MIB, mainMBB);
14139       // Replace the original PHI node as mainMBB is changed after CMOV
14140       // lowering.
14141       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
14142         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
14143       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
14144         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
14145       PhiL->eraseFromParent();
14146       PhiH->eraseFromParent();
14147     }
14148     break;
14149   }
14150   case X86::ATOMSWAP6432: {
14151     unsigned HiOpc;
14152     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
14153     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
14154     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
14155     break;
14156   }
14157   }
14158
14159   // Copy EDX:EAX back from HiReg:LoReg
14160   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
14161   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
14162   // Copy ECX:EBX from t1H:t1L
14163   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
14164   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
14165
14166   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
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   MIB.setMemRefs(MMOBegin, MMOEnd);
14174
14175   // Copy EDX:EAX back to t3H:t3L
14176   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
14177   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
14178
14179   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
14180
14181   mainMBB->addSuccessor(origMainMBB);
14182   mainMBB->addSuccessor(sinkMBB);
14183
14184   // sinkMBB:
14185   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14186           TII->get(TargetOpcode::COPY), DstLoReg)
14187     .addReg(t3L);
14188   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14189           TII->get(TargetOpcode::COPY), DstHiReg)
14190     .addReg(t3H);
14191
14192   MI->eraseFromParent();
14193   return sinkMBB;
14194 }
14195
14196 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
14197 // or XMM0_V32I8 in AVX all of this code can be replaced with that
14198 // in the .td file.
14199 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
14200                                        const TargetInstrInfo *TII) {
14201   unsigned Opc;
14202   switch (MI->getOpcode()) {
14203   default: llvm_unreachable("illegal opcode!");
14204   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
14205   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
14206   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
14207   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
14208   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
14209   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
14210   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
14211   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
14212   }
14213
14214   DebugLoc dl = MI->getDebugLoc();
14215   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14216
14217   unsigned NumArgs = MI->getNumOperands();
14218   for (unsigned i = 1; i < NumArgs; ++i) {
14219     MachineOperand &Op = MI->getOperand(i);
14220     if (!(Op.isReg() && Op.isImplicit()))
14221       MIB.addOperand(Op);
14222   }
14223   if (MI->hasOneMemOperand())
14224     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14225
14226   BuildMI(*BB, MI, dl,
14227     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14228     .addReg(X86::XMM0);
14229
14230   MI->eraseFromParent();
14231   return BB;
14232 }
14233
14234 // FIXME: Custom handling because TableGen doesn't support multiple implicit
14235 // defs in an instruction pattern
14236 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
14237                                        const TargetInstrInfo *TII) {
14238   unsigned Opc;
14239   switch (MI->getOpcode()) {
14240   default: llvm_unreachable("illegal opcode!");
14241   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
14242   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
14243   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
14244   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
14245   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
14246   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
14247   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
14248   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
14249   }
14250
14251   DebugLoc dl = MI->getDebugLoc();
14252   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
14253
14254   unsigned NumArgs = MI->getNumOperands(); // remove the results
14255   for (unsigned i = 1; i < NumArgs; ++i) {
14256     MachineOperand &Op = MI->getOperand(i);
14257     if (!(Op.isReg() && Op.isImplicit()))
14258       MIB.addOperand(Op);
14259   }
14260   if (MI->hasOneMemOperand())
14261     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
14262
14263   BuildMI(*BB, MI, dl,
14264     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14265     .addReg(X86::ECX);
14266
14267   MI->eraseFromParent();
14268   return BB;
14269 }
14270
14271 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
14272                                        const TargetInstrInfo *TII,
14273                                        const X86Subtarget* Subtarget) {
14274   DebugLoc dl = MI->getDebugLoc();
14275
14276   // Address into RAX/EAX, other two args into ECX, EDX.
14277   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
14278   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
14279   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
14280   for (int i = 0; i < X86::AddrNumOperands; ++i)
14281     MIB.addOperand(MI->getOperand(i));
14282
14283   unsigned ValOps = X86::AddrNumOperands;
14284   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
14285     .addReg(MI->getOperand(ValOps).getReg());
14286   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
14287     .addReg(MI->getOperand(ValOps+1).getReg());
14288
14289   // The instruction doesn't actually take any operands though.
14290   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
14291
14292   MI->eraseFromParent(); // The pseudo is gone now.
14293   return BB;
14294 }
14295
14296 MachineBasicBlock *
14297 X86TargetLowering::EmitVAARG64WithCustomInserter(
14298                    MachineInstr *MI,
14299                    MachineBasicBlock *MBB) const {
14300   // Emit va_arg instruction on X86-64.
14301
14302   // Operands to this pseudo-instruction:
14303   // 0  ) Output        : destination address (reg)
14304   // 1-5) Input         : va_list address (addr, i64mem)
14305   // 6  ) ArgSize       : Size (in bytes) of vararg type
14306   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
14307   // 8  ) Align         : Alignment of type
14308   // 9  ) EFLAGS (implicit-def)
14309
14310   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
14311   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
14312
14313   unsigned DestReg = MI->getOperand(0).getReg();
14314   MachineOperand &Base = MI->getOperand(1);
14315   MachineOperand &Scale = MI->getOperand(2);
14316   MachineOperand &Index = MI->getOperand(3);
14317   MachineOperand &Disp = MI->getOperand(4);
14318   MachineOperand &Segment = MI->getOperand(5);
14319   unsigned ArgSize = MI->getOperand(6).getImm();
14320   unsigned ArgMode = MI->getOperand(7).getImm();
14321   unsigned Align = MI->getOperand(8).getImm();
14322
14323   // Memory Reference
14324   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
14325   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14326   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14327
14328   // Machine Information
14329   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14330   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
14331   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
14332   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
14333   DebugLoc DL = MI->getDebugLoc();
14334
14335   // struct va_list {
14336   //   i32   gp_offset
14337   //   i32   fp_offset
14338   //   i64   overflow_area (address)
14339   //   i64   reg_save_area (address)
14340   // }
14341   // sizeof(va_list) = 24
14342   // alignment(va_list) = 8
14343
14344   unsigned TotalNumIntRegs = 6;
14345   unsigned TotalNumXMMRegs = 8;
14346   bool UseGPOffset = (ArgMode == 1);
14347   bool UseFPOffset = (ArgMode == 2);
14348   unsigned MaxOffset = TotalNumIntRegs * 8 +
14349                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
14350
14351   /* Align ArgSize to a multiple of 8 */
14352   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
14353   bool NeedsAlign = (Align > 8);
14354
14355   MachineBasicBlock *thisMBB = MBB;
14356   MachineBasicBlock *overflowMBB;
14357   MachineBasicBlock *offsetMBB;
14358   MachineBasicBlock *endMBB;
14359
14360   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
14361   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
14362   unsigned OffsetReg = 0;
14363
14364   if (!UseGPOffset && !UseFPOffset) {
14365     // If we only pull from the overflow region, we don't create a branch.
14366     // We don't need to alter control flow.
14367     OffsetDestReg = 0; // unused
14368     OverflowDestReg = DestReg;
14369
14370     offsetMBB = NULL;
14371     overflowMBB = thisMBB;
14372     endMBB = thisMBB;
14373   } else {
14374     // First emit code to check if gp_offset (or fp_offset) is below the bound.
14375     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
14376     // If not, pull from overflow_area. (branch to overflowMBB)
14377     //
14378     //       thisMBB
14379     //         |     .
14380     //         |        .
14381     //     offsetMBB   overflowMBB
14382     //         |        .
14383     //         |     .
14384     //        endMBB
14385
14386     // Registers for the PHI in endMBB
14387     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
14388     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
14389
14390     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14391     MachineFunction *MF = MBB->getParent();
14392     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14393     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14394     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14395
14396     MachineFunction::iterator MBBIter = MBB;
14397     ++MBBIter;
14398
14399     // Insert the new basic blocks
14400     MF->insert(MBBIter, offsetMBB);
14401     MF->insert(MBBIter, overflowMBB);
14402     MF->insert(MBBIter, endMBB);
14403
14404     // Transfer the remainder of MBB and its successor edges to endMBB.
14405     endMBB->splice(endMBB->begin(), thisMBB,
14406                     llvm::next(MachineBasicBlock::iterator(MI)),
14407                     thisMBB->end());
14408     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
14409
14410     // Make offsetMBB and overflowMBB successors of thisMBB
14411     thisMBB->addSuccessor(offsetMBB);
14412     thisMBB->addSuccessor(overflowMBB);
14413
14414     // endMBB is a successor of both offsetMBB and overflowMBB
14415     offsetMBB->addSuccessor(endMBB);
14416     overflowMBB->addSuccessor(endMBB);
14417
14418     // Load the offset value into a register
14419     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14420     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14421       .addOperand(Base)
14422       .addOperand(Scale)
14423       .addOperand(Index)
14424       .addDisp(Disp, UseFPOffset ? 4 : 0)
14425       .addOperand(Segment)
14426       .setMemRefs(MMOBegin, MMOEnd);
14427
14428     // Check if there is enough room left to pull this argument.
14429     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14430       .addReg(OffsetReg)
14431       .addImm(MaxOffset + 8 - ArgSizeA8);
14432
14433     // Branch to "overflowMBB" if offset >= max
14434     // Fall through to "offsetMBB" otherwise
14435     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14436       .addMBB(overflowMBB);
14437   }
14438
14439   // In offsetMBB, emit code to use the reg_save_area.
14440   if (offsetMBB) {
14441     assert(OffsetReg != 0);
14442
14443     // Read the reg_save_area address.
14444     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14445     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14446       .addOperand(Base)
14447       .addOperand(Scale)
14448       .addOperand(Index)
14449       .addDisp(Disp, 16)
14450       .addOperand(Segment)
14451       .setMemRefs(MMOBegin, MMOEnd);
14452
14453     // Zero-extend the offset
14454     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14455       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14456         .addImm(0)
14457         .addReg(OffsetReg)
14458         .addImm(X86::sub_32bit);
14459
14460     // Add the offset to the reg_save_area to get the final address.
14461     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14462       .addReg(OffsetReg64)
14463       .addReg(RegSaveReg);
14464
14465     // Compute the offset for the next argument
14466     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14467     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14468       .addReg(OffsetReg)
14469       .addImm(UseFPOffset ? 16 : 8);
14470
14471     // Store it back into the va_list.
14472     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14473       .addOperand(Base)
14474       .addOperand(Scale)
14475       .addOperand(Index)
14476       .addDisp(Disp, UseFPOffset ? 4 : 0)
14477       .addOperand(Segment)
14478       .addReg(NextOffsetReg)
14479       .setMemRefs(MMOBegin, MMOEnd);
14480
14481     // Jump to endMBB
14482     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14483       .addMBB(endMBB);
14484   }
14485
14486   //
14487   // Emit code to use overflow area
14488   //
14489
14490   // Load the overflow_area address into a register.
14491   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14492   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14493     .addOperand(Base)
14494     .addOperand(Scale)
14495     .addOperand(Index)
14496     .addDisp(Disp, 8)
14497     .addOperand(Segment)
14498     .setMemRefs(MMOBegin, MMOEnd);
14499
14500   // If we need to align it, do so. Otherwise, just copy the address
14501   // to OverflowDestReg.
14502   if (NeedsAlign) {
14503     // Align the overflow address
14504     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14505     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14506
14507     // aligned_addr = (addr + (align-1)) & ~(align-1)
14508     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14509       .addReg(OverflowAddrReg)
14510       .addImm(Align-1);
14511
14512     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14513       .addReg(TmpReg)
14514       .addImm(~(uint64_t)(Align-1));
14515   } else {
14516     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14517       .addReg(OverflowAddrReg);
14518   }
14519
14520   // Compute the next overflow address after this argument.
14521   // (the overflow address should be kept 8-byte aligned)
14522   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14523   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14524     .addReg(OverflowDestReg)
14525     .addImm(ArgSizeA8);
14526
14527   // Store the new overflow address.
14528   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14529     .addOperand(Base)
14530     .addOperand(Scale)
14531     .addOperand(Index)
14532     .addDisp(Disp, 8)
14533     .addOperand(Segment)
14534     .addReg(NextAddrReg)
14535     .setMemRefs(MMOBegin, MMOEnd);
14536
14537   // If we branched, emit the PHI to the front of endMBB.
14538   if (offsetMBB) {
14539     BuildMI(*endMBB, endMBB->begin(), DL,
14540             TII->get(X86::PHI), DestReg)
14541       .addReg(OffsetDestReg).addMBB(offsetMBB)
14542       .addReg(OverflowDestReg).addMBB(overflowMBB);
14543   }
14544
14545   // Erase the pseudo instruction
14546   MI->eraseFromParent();
14547
14548   return endMBB;
14549 }
14550
14551 MachineBasicBlock *
14552 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14553                                                  MachineInstr *MI,
14554                                                  MachineBasicBlock *MBB) const {
14555   // Emit code to save XMM registers to the stack. The ABI says that the
14556   // number of registers to save is given in %al, so it's theoretically
14557   // possible to do an indirect jump trick to avoid saving all of them,
14558   // however this code takes a simpler approach and just executes all
14559   // of the stores if %al is non-zero. It's less code, and it's probably
14560   // easier on the hardware branch predictor, and stores aren't all that
14561   // expensive anyway.
14562
14563   // Create the new basic blocks. One block contains all the XMM stores,
14564   // and one block is the final destination regardless of whether any
14565   // stores were performed.
14566   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14567   MachineFunction *F = MBB->getParent();
14568   MachineFunction::iterator MBBIter = MBB;
14569   ++MBBIter;
14570   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14571   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14572   F->insert(MBBIter, XMMSaveMBB);
14573   F->insert(MBBIter, EndMBB);
14574
14575   // Transfer the remainder of MBB and its successor edges to EndMBB.
14576   EndMBB->splice(EndMBB->begin(), MBB,
14577                  llvm::next(MachineBasicBlock::iterator(MI)),
14578                  MBB->end());
14579   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14580
14581   // The original block will now fall through to the XMM save block.
14582   MBB->addSuccessor(XMMSaveMBB);
14583   // The XMMSaveMBB will fall through to the end block.
14584   XMMSaveMBB->addSuccessor(EndMBB);
14585
14586   // Now add the instructions.
14587   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14588   DebugLoc DL = MI->getDebugLoc();
14589
14590   unsigned CountReg = MI->getOperand(0).getReg();
14591   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14592   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14593
14594   if (!Subtarget->isTargetWin64()) {
14595     // If %al is 0, branch around the XMM save block.
14596     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14597     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14598     MBB->addSuccessor(EndMBB);
14599   }
14600
14601   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14602   // In the XMM save block, save all the XMM argument registers.
14603   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14604     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14605     MachineMemOperand *MMO =
14606       F->getMachineMemOperand(
14607           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14608         MachineMemOperand::MOStore,
14609         /*Size=*/16, /*Align=*/16);
14610     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14611       .addFrameIndex(RegSaveFrameIndex)
14612       .addImm(/*Scale=*/1)
14613       .addReg(/*IndexReg=*/0)
14614       .addImm(/*Disp=*/Offset)
14615       .addReg(/*Segment=*/0)
14616       .addReg(MI->getOperand(i).getReg())
14617       .addMemOperand(MMO);
14618   }
14619
14620   MI->eraseFromParent();   // The pseudo instruction is gone now.
14621
14622   return EndMBB;
14623 }
14624
14625 // The EFLAGS operand of SelectItr might be missing a kill marker
14626 // because there were multiple uses of EFLAGS, and ISel didn't know
14627 // which to mark. Figure out whether SelectItr should have had a
14628 // kill marker, and set it if it should. Returns the correct kill
14629 // marker value.
14630 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14631                                      MachineBasicBlock* BB,
14632                                      const TargetRegisterInfo* TRI) {
14633   // Scan forward through BB for a use/def of EFLAGS.
14634   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14635   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14636     const MachineInstr& mi = *miI;
14637     if (mi.readsRegister(X86::EFLAGS))
14638       return false;
14639     if (mi.definesRegister(X86::EFLAGS))
14640       break; // Should have kill-flag - update below.
14641   }
14642
14643   // If we hit the end of the block, check whether EFLAGS is live into a
14644   // successor.
14645   if (miI == BB->end()) {
14646     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14647                                           sEnd = BB->succ_end();
14648          sItr != sEnd; ++sItr) {
14649       MachineBasicBlock* succ = *sItr;
14650       if (succ->isLiveIn(X86::EFLAGS))
14651         return false;
14652     }
14653   }
14654
14655   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14656   // out. SelectMI should have a kill flag on EFLAGS.
14657   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14658   return true;
14659 }
14660
14661 MachineBasicBlock *
14662 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14663                                      MachineBasicBlock *BB) const {
14664   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14665   DebugLoc DL = MI->getDebugLoc();
14666
14667   // To "insert" a SELECT_CC instruction, we actually have to insert the
14668   // diamond control-flow pattern.  The incoming instruction knows the
14669   // destination vreg to set, the condition code register to branch on, the
14670   // true/false values to select between, and a branch opcode to use.
14671   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14672   MachineFunction::iterator It = BB;
14673   ++It;
14674
14675   //  thisMBB:
14676   //  ...
14677   //   TrueVal = ...
14678   //   cmpTY ccX, r1, r2
14679   //   bCC copy1MBB
14680   //   fallthrough --> copy0MBB
14681   MachineBasicBlock *thisMBB = BB;
14682   MachineFunction *F = BB->getParent();
14683   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14684   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14685   F->insert(It, copy0MBB);
14686   F->insert(It, sinkMBB);
14687
14688   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14689   // live into the sink and copy blocks.
14690   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14691   if (!MI->killsRegister(X86::EFLAGS) &&
14692       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14693     copy0MBB->addLiveIn(X86::EFLAGS);
14694     sinkMBB->addLiveIn(X86::EFLAGS);
14695   }
14696
14697   // Transfer the remainder of BB and its successor edges to sinkMBB.
14698   sinkMBB->splice(sinkMBB->begin(), BB,
14699                   llvm::next(MachineBasicBlock::iterator(MI)),
14700                   BB->end());
14701   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14702
14703   // Add the true and fallthrough blocks as its successors.
14704   BB->addSuccessor(copy0MBB);
14705   BB->addSuccessor(sinkMBB);
14706
14707   // Create the conditional branch instruction.
14708   unsigned Opc =
14709     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14710   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14711
14712   //  copy0MBB:
14713   //   %FalseValue = ...
14714   //   # fallthrough to sinkMBB
14715   copy0MBB->addSuccessor(sinkMBB);
14716
14717   //  sinkMBB:
14718   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14719   //  ...
14720   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14721           TII->get(X86::PHI), MI->getOperand(0).getReg())
14722     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14723     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14724
14725   MI->eraseFromParent();   // The pseudo instruction is gone now.
14726   return sinkMBB;
14727 }
14728
14729 MachineBasicBlock *
14730 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14731                                         bool Is64Bit) const {
14732   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14733   DebugLoc DL = MI->getDebugLoc();
14734   MachineFunction *MF = BB->getParent();
14735   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14736
14737   assert(getTargetMachine().Options.EnableSegmentedStacks);
14738
14739   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14740   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14741
14742   // BB:
14743   //  ... [Till the alloca]
14744   // If stacklet is not large enough, jump to mallocMBB
14745   //
14746   // bumpMBB:
14747   //  Allocate by subtracting from RSP
14748   //  Jump to continueMBB
14749   //
14750   // mallocMBB:
14751   //  Allocate by call to runtime
14752   //
14753   // continueMBB:
14754   //  ...
14755   //  [rest of original BB]
14756   //
14757
14758   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14759   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14760   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14761
14762   MachineRegisterInfo &MRI = MF->getRegInfo();
14763   const TargetRegisterClass *AddrRegClass =
14764     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14765
14766   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14767     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14768     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14769     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14770     sizeVReg = MI->getOperand(1).getReg(),
14771     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14772
14773   MachineFunction::iterator MBBIter = BB;
14774   ++MBBIter;
14775
14776   MF->insert(MBBIter, bumpMBB);
14777   MF->insert(MBBIter, mallocMBB);
14778   MF->insert(MBBIter, continueMBB);
14779
14780   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14781                       (MachineBasicBlock::iterator(MI)), BB->end());
14782   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14783
14784   // Add code to the main basic block to check if the stack limit has been hit,
14785   // and if so, jump to mallocMBB otherwise to bumpMBB.
14786   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14787   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14788     .addReg(tmpSPVReg).addReg(sizeVReg);
14789   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14790     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14791     .addReg(SPLimitVReg);
14792   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14793
14794   // bumpMBB simply decreases the stack pointer, since we know the current
14795   // stacklet has enough space.
14796   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14797     .addReg(SPLimitVReg);
14798   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14799     .addReg(SPLimitVReg);
14800   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14801
14802   // Calls into a routine in libgcc to allocate more space from the heap.
14803   const uint32_t *RegMask =
14804     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14805   if (Is64Bit) {
14806     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14807       .addReg(sizeVReg);
14808     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14809       .addExternalSymbol("__morestack_allocate_stack_space")
14810       .addRegMask(RegMask)
14811       .addReg(X86::RDI, RegState::Implicit)
14812       .addReg(X86::RAX, RegState::ImplicitDefine);
14813   } else {
14814     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14815       .addImm(12);
14816     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14817     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14818       .addExternalSymbol("__morestack_allocate_stack_space")
14819       .addRegMask(RegMask)
14820       .addReg(X86::EAX, RegState::ImplicitDefine);
14821   }
14822
14823   if (!Is64Bit)
14824     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14825       .addImm(16);
14826
14827   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14828     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14829   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14830
14831   // Set up the CFG correctly.
14832   BB->addSuccessor(bumpMBB);
14833   BB->addSuccessor(mallocMBB);
14834   mallocMBB->addSuccessor(continueMBB);
14835   bumpMBB->addSuccessor(continueMBB);
14836
14837   // Take care of the PHI nodes.
14838   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14839           MI->getOperand(0).getReg())
14840     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14841     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14842
14843   // Delete the original pseudo instruction.
14844   MI->eraseFromParent();
14845
14846   // And we're done.
14847   return continueMBB;
14848 }
14849
14850 MachineBasicBlock *
14851 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14852                                           MachineBasicBlock *BB) const {
14853   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14854   DebugLoc DL = MI->getDebugLoc();
14855
14856   assert(!Subtarget->isTargetEnvMacho());
14857
14858   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14859   // non-trivial part is impdef of ESP.
14860
14861   if (Subtarget->isTargetWin64()) {
14862     if (Subtarget->isTargetCygMing()) {
14863       // ___chkstk(Mingw64):
14864       // Clobbers R10, R11, RAX and EFLAGS.
14865       // Updates RSP.
14866       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14867         .addExternalSymbol("___chkstk")
14868         .addReg(X86::RAX, RegState::Implicit)
14869         .addReg(X86::RSP, RegState::Implicit)
14870         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14871         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14872         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14873     } else {
14874       // __chkstk(MSVCRT): does not update stack pointer.
14875       // Clobbers R10, R11 and EFLAGS.
14876       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14877         .addExternalSymbol("__chkstk")
14878         .addReg(X86::RAX, RegState::Implicit)
14879         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14880       // RAX has the offset to be subtracted from RSP.
14881       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14882         .addReg(X86::RSP)
14883         .addReg(X86::RAX);
14884     }
14885   } else {
14886     const char *StackProbeSymbol =
14887       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14888
14889     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14890       .addExternalSymbol(StackProbeSymbol)
14891       .addReg(X86::EAX, RegState::Implicit)
14892       .addReg(X86::ESP, RegState::Implicit)
14893       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14894       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14895       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14896   }
14897
14898   MI->eraseFromParent();   // The pseudo instruction is gone now.
14899   return BB;
14900 }
14901
14902 MachineBasicBlock *
14903 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14904                                       MachineBasicBlock *BB) const {
14905   // This is pretty easy.  We're taking the value that we received from
14906   // our load from the relocation, sticking it in either RDI (x86-64)
14907   // or EAX and doing an indirect call.  The return value will then
14908   // be in the normal return register.
14909   const X86InstrInfo *TII
14910     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14911   DebugLoc DL = MI->getDebugLoc();
14912   MachineFunction *F = BB->getParent();
14913
14914   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14915   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14916
14917   // Get a register mask for the lowered call.
14918   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14919   // proper register mask.
14920   const uint32_t *RegMask =
14921     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14922   if (Subtarget->is64Bit()) {
14923     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14924                                       TII->get(X86::MOV64rm), X86::RDI)
14925     .addReg(X86::RIP)
14926     .addImm(0).addReg(0)
14927     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14928                       MI->getOperand(3).getTargetFlags())
14929     .addReg(0);
14930     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14931     addDirectMem(MIB, X86::RDI);
14932     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14933   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14934     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14935                                       TII->get(X86::MOV32rm), X86::EAX)
14936     .addReg(0)
14937     .addImm(0).addReg(0)
14938     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14939                       MI->getOperand(3).getTargetFlags())
14940     .addReg(0);
14941     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14942     addDirectMem(MIB, X86::EAX);
14943     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14944   } else {
14945     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14946                                       TII->get(X86::MOV32rm), X86::EAX)
14947     .addReg(TII->getGlobalBaseReg(F))
14948     .addImm(0).addReg(0)
14949     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14950                       MI->getOperand(3).getTargetFlags())
14951     .addReg(0);
14952     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14953     addDirectMem(MIB, X86::EAX);
14954     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14955   }
14956
14957   MI->eraseFromParent(); // The pseudo instruction is gone now.
14958   return BB;
14959 }
14960
14961 MachineBasicBlock *
14962 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14963                                     MachineBasicBlock *MBB) const {
14964   DebugLoc DL = MI->getDebugLoc();
14965   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14966
14967   MachineFunction *MF = MBB->getParent();
14968   MachineRegisterInfo &MRI = MF->getRegInfo();
14969
14970   const BasicBlock *BB = MBB->getBasicBlock();
14971   MachineFunction::iterator I = MBB;
14972   ++I;
14973
14974   // Memory Reference
14975   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14976   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14977
14978   unsigned DstReg;
14979   unsigned MemOpndSlot = 0;
14980
14981   unsigned CurOp = 0;
14982
14983   DstReg = MI->getOperand(CurOp++).getReg();
14984   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14985   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14986   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14987   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14988
14989   MemOpndSlot = CurOp;
14990
14991   MVT PVT = getPointerTy();
14992   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14993          "Invalid Pointer Size!");
14994
14995   // For v = setjmp(buf), we generate
14996   //
14997   // thisMBB:
14998   //  buf[LabelOffset] = restoreMBB
14999   //  SjLjSetup restoreMBB
15000   //
15001   // mainMBB:
15002   //  v_main = 0
15003   //
15004   // sinkMBB:
15005   //  v = phi(main, restore)
15006   //
15007   // restoreMBB:
15008   //  v_restore = 1
15009
15010   MachineBasicBlock *thisMBB = MBB;
15011   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15012   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15013   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
15014   MF->insert(I, mainMBB);
15015   MF->insert(I, sinkMBB);
15016   MF->push_back(restoreMBB);
15017
15018   MachineInstrBuilder MIB;
15019
15020   // Transfer the remainder of BB and its successor edges to sinkMBB.
15021   sinkMBB->splice(sinkMBB->begin(), MBB,
15022                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
15023   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15024
15025   // thisMBB:
15026   unsigned PtrStoreOpc = 0;
15027   unsigned LabelReg = 0;
15028   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15029   Reloc::Model RM = getTargetMachine().getRelocationModel();
15030   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
15031                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
15032
15033   // Prepare IP either in reg or imm.
15034   if (!UseImmLabel) {
15035     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
15036     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
15037     LabelReg = MRI.createVirtualRegister(PtrRC);
15038     if (Subtarget->is64Bit()) {
15039       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
15040               .addReg(X86::RIP)
15041               .addImm(0)
15042               .addReg(0)
15043               .addMBB(restoreMBB)
15044               .addReg(0);
15045     } else {
15046       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
15047       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
15048               .addReg(XII->getGlobalBaseReg(MF))
15049               .addImm(0)
15050               .addReg(0)
15051               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
15052               .addReg(0);
15053     }
15054   } else
15055     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
15056   // Store IP
15057   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
15058   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15059     if (i == X86::AddrDisp)
15060       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
15061     else
15062       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
15063   }
15064   if (!UseImmLabel)
15065     MIB.addReg(LabelReg);
15066   else
15067     MIB.addMBB(restoreMBB);
15068   MIB.setMemRefs(MMOBegin, MMOEnd);
15069   // Setup
15070   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
15071           .addMBB(restoreMBB);
15072
15073   const X86RegisterInfo *RegInfo =
15074     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15075   MIB.addRegMask(RegInfo->getNoPreservedMask());
15076   thisMBB->addSuccessor(mainMBB);
15077   thisMBB->addSuccessor(restoreMBB);
15078
15079   // mainMBB:
15080   //  EAX = 0
15081   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
15082   mainMBB->addSuccessor(sinkMBB);
15083
15084   // sinkMBB:
15085   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15086           TII->get(X86::PHI), DstReg)
15087     .addReg(mainDstReg).addMBB(mainMBB)
15088     .addReg(restoreDstReg).addMBB(restoreMBB);
15089
15090   // restoreMBB:
15091   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
15092   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
15093   restoreMBB->addSuccessor(sinkMBB);
15094
15095   MI->eraseFromParent();
15096   return sinkMBB;
15097 }
15098
15099 MachineBasicBlock *
15100 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
15101                                      MachineBasicBlock *MBB) const {
15102   DebugLoc DL = MI->getDebugLoc();
15103   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15104
15105   MachineFunction *MF = MBB->getParent();
15106   MachineRegisterInfo &MRI = MF->getRegInfo();
15107
15108   // Memory Reference
15109   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15110   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15111
15112   MVT PVT = getPointerTy();
15113   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
15114          "Invalid Pointer Size!");
15115
15116   const TargetRegisterClass *RC =
15117     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
15118   unsigned Tmp = MRI.createVirtualRegister(RC);
15119   // Since FP is only updated here but NOT referenced, it's treated as GPR.
15120   const X86RegisterInfo *RegInfo =
15121     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
15122   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
15123   unsigned SP = RegInfo->getStackRegister();
15124
15125   MachineInstrBuilder MIB;
15126
15127   const int64_t LabelOffset = 1 * PVT.getStoreSize();
15128   const int64_t SPOffset = 2 * PVT.getStoreSize();
15129
15130   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
15131   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
15132
15133   // Reload FP
15134   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
15135   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
15136     MIB.addOperand(MI->getOperand(i));
15137   MIB.setMemRefs(MMOBegin, MMOEnd);
15138   // Reload IP
15139   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
15140   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15141     if (i == X86::AddrDisp)
15142       MIB.addDisp(MI->getOperand(i), LabelOffset);
15143     else
15144       MIB.addOperand(MI->getOperand(i));
15145   }
15146   MIB.setMemRefs(MMOBegin, MMOEnd);
15147   // Reload SP
15148   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
15149   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15150     if (i == X86::AddrDisp)
15151       MIB.addDisp(MI->getOperand(i), SPOffset);
15152     else
15153       MIB.addOperand(MI->getOperand(i));
15154   }
15155   MIB.setMemRefs(MMOBegin, MMOEnd);
15156   // Jump
15157   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
15158
15159   MI->eraseFromParent();
15160   return MBB;
15161 }
15162
15163 MachineBasicBlock *
15164 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
15165                                                MachineBasicBlock *BB) const {
15166   switch (MI->getOpcode()) {
15167   default: llvm_unreachable("Unexpected instr type to insert");
15168   case X86::TAILJMPd64:
15169   case X86::TAILJMPr64:
15170   case X86::TAILJMPm64:
15171     llvm_unreachable("TAILJMP64 would not be touched here.");
15172   case X86::TCRETURNdi64:
15173   case X86::TCRETURNri64:
15174   case X86::TCRETURNmi64:
15175     return BB;
15176   case X86::WIN_ALLOCA:
15177     return EmitLoweredWinAlloca(MI, BB);
15178   case X86::SEG_ALLOCA_32:
15179     return EmitLoweredSegAlloca(MI, BB, false);
15180   case X86::SEG_ALLOCA_64:
15181     return EmitLoweredSegAlloca(MI, BB, true);
15182   case X86::TLSCall_32:
15183   case X86::TLSCall_64:
15184     return EmitLoweredTLSCall(MI, BB);
15185   case X86::CMOV_GR8:
15186   case X86::CMOV_FR32:
15187   case X86::CMOV_FR64:
15188   case X86::CMOV_V4F32:
15189   case X86::CMOV_V2F64:
15190   case X86::CMOV_V2I64:
15191   case X86::CMOV_V8F32:
15192   case X86::CMOV_V4F64:
15193   case X86::CMOV_V4I64:
15194   case X86::CMOV_GR16:
15195   case X86::CMOV_GR32:
15196   case X86::CMOV_RFP32:
15197   case X86::CMOV_RFP64:
15198   case X86::CMOV_RFP80:
15199     return EmitLoweredSelect(MI, BB);
15200
15201   case X86::FP32_TO_INT16_IN_MEM:
15202   case X86::FP32_TO_INT32_IN_MEM:
15203   case X86::FP32_TO_INT64_IN_MEM:
15204   case X86::FP64_TO_INT16_IN_MEM:
15205   case X86::FP64_TO_INT32_IN_MEM:
15206   case X86::FP64_TO_INT64_IN_MEM:
15207   case X86::FP80_TO_INT16_IN_MEM:
15208   case X86::FP80_TO_INT32_IN_MEM:
15209   case X86::FP80_TO_INT64_IN_MEM: {
15210     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15211     DebugLoc DL = MI->getDebugLoc();
15212
15213     // Change the floating point control register to use "round towards zero"
15214     // mode when truncating to an integer value.
15215     MachineFunction *F = BB->getParent();
15216     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
15217     addFrameReference(BuildMI(*BB, MI, DL,
15218                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
15219
15220     // Load the old value of the high byte of the control word...
15221     unsigned OldCW =
15222       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
15223     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
15224                       CWFrameIdx);
15225
15226     // Set the high part to be round to zero...
15227     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
15228       .addImm(0xC7F);
15229
15230     // Reload the modified control word now...
15231     addFrameReference(BuildMI(*BB, MI, DL,
15232                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15233
15234     // Restore the memory image of control word to original value
15235     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
15236       .addReg(OldCW);
15237
15238     // Get the X86 opcode to use.
15239     unsigned Opc;
15240     switch (MI->getOpcode()) {
15241     default: llvm_unreachable("illegal opcode!");
15242     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
15243     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
15244     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
15245     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
15246     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
15247     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
15248     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
15249     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
15250     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
15251     }
15252
15253     X86AddressMode AM;
15254     MachineOperand &Op = MI->getOperand(0);
15255     if (Op.isReg()) {
15256       AM.BaseType = X86AddressMode::RegBase;
15257       AM.Base.Reg = Op.getReg();
15258     } else {
15259       AM.BaseType = X86AddressMode::FrameIndexBase;
15260       AM.Base.FrameIndex = Op.getIndex();
15261     }
15262     Op = MI->getOperand(1);
15263     if (Op.isImm())
15264       AM.Scale = Op.getImm();
15265     Op = MI->getOperand(2);
15266     if (Op.isImm())
15267       AM.IndexReg = Op.getImm();
15268     Op = MI->getOperand(3);
15269     if (Op.isGlobal()) {
15270       AM.GV = Op.getGlobal();
15271     } else {
15272       AM.Disp = Op.getImm();
15273     }
15274     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
15275                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
15276
15277     // Reload the original control word now.
15278     addFrameReference(BuildMI(*BB, MI, DL,
15279                               TII->get(X86::FLDCW16m)), CWFrameIdx);
15280
15281     MI->eraseFromParent();   // The pseudo instruction is gone now.
15282     return BB;
15283   }
15284     // String/text processing lowering.
15285   case X86::PCMPISTRM128REG:
15286   case X86::VPCMPISTRM128REG:
15287   case X86::PCMPISTRM128MEM:
15288   case X86::VPCMPISTRM128MEM:
15289   case X86::PCMPESTRM128REG:
15290   case X86::VPCMPESTRM128REG:
15291   case X86::PCMPESTRM128MEM:
15292   case X86::VPCMPESTRM128MEM:
15293     assert(Subtarget->hasSSE42() &&
15294            "Target must have SSE4.2 or AVX features enabled");
15295     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
15296
15297   // String/text processing lowering.
15298   case X86::PCMPISTRIREG:
15299   case X86::VPCMPISTRIREG:
15300   case X86::PCMPISTRIMEM:
15301   case X86::VPCMPISTRIMEM:
15302   case X86::PCMPESTRIREG:
15303   case X86::VPCMPESTRIREG:
15304   case X86::PCMPESTRIMEM:
15305   case X86::VPCMPESTRIMEM:
15306     assert(Subtarget->hasSSE42() &&
15307            "Target must have SSE4.2 or AVX features enabled");
15308     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
15309
15310   // Thread synchronization.
15311   case X86::MONITOR:
15312     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
15313
15314   // xbegin
15315   case X86::XBEGIN:
15316     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
15317
15318   // Atomic Lowering.
15319   case X86::ATOMAND8:
15320   case X86::ATOMAND16:
15321   case X86::ATOMAND32:
15322   case X86::ATOMAND64:
15323     // Fall through
15324   case X86::ATOMOR8:
15325   case X86::ATOMOR16:
15326   case X86::ATOMOR32:
15327   case X86::ATOMOR64:
15328     // Fall through
15329   case X86::ATOMXOR16:
15330   case X86::ATOMXOR8:
15331   case X86::ATOMXOR32:
15332   case X86::ATOMXOR64:
15333     // Fall through
15334   case X86::ATOMNAND8:
15335   case X86::ATOMNAND16:
15336   case X86::ATOMNAND32:
15337   case X86::ATOMNAND64:
15338     // Fall through
15339   case X86::ATOMMAX8:
15340   case X86::ATOMMAX16:
15341   case X86::ATOMMAX32:
15342   case X86::ATOMMAX64:
15343     // Fall through
15344   case X86::ATOMMIN8:
15345   case X86::ATOMMIN16:
15346   case X86::ATOMMIN32:
15347   case X86::ATOMMIN64:
15348     // Fall through
15349   case X86::ATOMUMAX8:
15350   case X86::ATOMUMAX16:
15351   case X86::ATOMUMAX32:
15352   case X86::ATOMUMAX64:
15353     // Fall through
15354   case X86::ATOMUMIN8:
15355   case X86::ATOMUMIN16:
15356   case X86::ATOMUMIN32:
15357   case X86::ATOMUMIN64:
15358     return EmitAtomicLoadArith(MI, BB);
15359
15360   // This group does 64-bit operations on a 32-bit host.
15361   case X86::ATOMAND6432:
15362   case X86::ATOMOR6432:
15363   case X86::ATOMXOR6432:
15364   case X86::ATOMNAND6432:
15365   case X86::ATOMADD6432:
15366   case X86::ATOMSUB6432:
15367   case X86::ATOMMAX6432:
15368   case X86::ATOMMIN6432:
15369   case X86::ATOMUMAX6432:
15370   case X86::ATOMUMIN6432:
15371   case X86::ATOMSWAP6432:
15372     return EmitAtomicLoadArith6432(MI, BB);
15373
15374   case X86::VASTART_SAVE_XMM_REGS:
15375     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
15376
15377   case X86::VAARG_64:
15378     return EmitVAARG64WithCustomInserter(MI, BB);
15379
15380   case X86::EH_SjLj_SetJmp32:
15381   case X86::EH_SjLj_SetJmp64:
15382     return emitEHSjLjSetJmp(MI, BB);
15383
15384   case X86::EH_SjLj_LongJmp32:
15385   case X86::EH_SjLj_LongJmp64:
15386     return emitEHSjLjLongJmp(MI, BB);
15387   }
15388 }
15389
15390 //===----------------------------------------------------------------------===//
15391 //                           X86 Optimization Hooks
15392 //===----------------------------------------------------------------------===//
15393
15394 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
15395                                                        APInt &KnownZero,
15396                                                        APInt &KnownOne,
15397                                                        const SelectionDAG &DAG,
15398                                                        unsigned Depth) const {
15399   unsigned BitWidth = KnownZero.getBitWidth();
15400   unsigned Opc = Op.getOpcode();
15401   assert((Opc >= ISD::BUILTIN_OP_END ||
15402           Opc == ISD::INTRINSIC_WO_CHAIN ||
15403           Opc == ISD::INTRINSIC_W_CHAIN ||
15404           Opc == ISD::INTRINSIC_VOID) &&
15405          "Should use MaskedValueIsZero if you don't know whether Op"
15406          " is a target node!");
15407
15408   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
15409   switch (Opc) {
15410   default: break;
15411   case X86ISD::ADD:
15412   case X86ISD::SUB:
15413   case X86ISD::ADC:
15414   case X86ISD::SBB:
15415   case X86ISD::SMUL:
15416   case X86ISD::UMUL:
15417   case X86ISD::INC:
15418   case X86ISD::DEC:
15419   case X86ISD::OR:
15420   case X86ISD::XOR:
15421   case X86ISD::AND:
15422     // These nodes' second result is a boolean.
15423     if (Op.getResNo() == 0)
15424       break;
15425     // Fallthrough
15426   case X86ISD::SETCC:
15427     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15428     break;
15429   case ISD::INTRINSIC_WO_CHAIN: {
15430     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15431     unsigned NumLoBits = 0;
15432     switch (IntId) {
15433     default: break;
15434     case Intrinsic::x86_sse_movmsk_ps:
15435     case Intrinsic::x86_avx_movmsk_ps_256:
15436     case Intrinsic::x86_sse2_movmsk_pd:
15437     case Intrinsic::x86_avx_movmsk_pd_256:
15438     case Intrinsic::x86_mmx_pmovmskb:
15439     case Intrinsic::x86_sse2_pmovmskb_128:
15440     case Intrinsic::x86_avx2_pmovmskb: {
15441       // High bits of movmskp{s|d}, pmovmskb are known zero.
15442       switch (IntId) {
15443         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15444         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
15445         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
15446         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
15447         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
15448         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
15449         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
15450         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
15451       }
15452       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15453       break;
15454     }
15455     }
15456     break;
15457   }
15458   }
15459 }
15460
15461 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15462                                                          unsigned Depth) const {
15463   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15464   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15465     return Op.getValueType().getScalarType().getSizeInBits();
15466
15467   // Fallback case.
15468   return 1;
15469 }
15470
15471 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15472 /// node is a GlobalAddress + offset.
15473 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15474                                        const GlobalValue* &GA,
15475                                        int64_t &Offset) const {
15476   if (N->getOpcode() == X86ISD::Wrapper) {
15477     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15478       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15479       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15480       return true;
15481     }
15482   }
15483   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15484 }
15485
15486 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15487 /// same as extracting the high 128-bit part of 256-bit vector and then
15488 /// inserting the result into the low part of a new 256-bit vector
15489 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15490   EVT VT = SVOp->getValueType(0);
15491   unsigned NumElems = VT.getVectorNumElements();
15492
15493   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15494   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15495     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15496         SVOp->getMaskElt(j) >= 0)
15497       return false;
15498
15499   return true;
15500 }
15501
15502 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15503 /// same as extracting the low 128-bit part of 256-bit vector and then
15504 /// inserting the result into the high part of a new 256-bit vector
15505 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15506   EVT VT = SVOp->getValueType(0);
15507   unsigned NumElems = VT.getVectorNumElements();
15508
15509   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15510   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15511     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15512         SVOp->getMaskElt(j) >= 0)
15513       return false;
15514
15515   return true;
15516 }
15517
15518 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15519 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15520                                         TargetLowering::DAGCombinerInfo &DCI,
15521                                         const X86Subtarget* Subtarget) {
15522   SDLoc dl(N);
15523   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15524   SDValue V1 = SVOp->getOperand(0);
15525   SDValue V2 = SVOp->getOperand(1);
15526   EVT VT = SVOp->getValueType(0);
15527   unsigned NumElems = VT.getVectorNumElements();
15528
15529   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15530       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15531     //
15532     //                   0,0,0,...
15533     //                      |
15534     //    V      UNDEF    BUILD_VECTOR    UNDEF
15535     //     \      /           \           /
15536     //  CONCAT_VECTOR         CONCAT_VECTOR
15537     //         \                  /
15538     //          \                /
15539     //          RESULT: V + zero extended
15540     //
15541     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15542         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15543         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15544       return SDValue();
15545
15546     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15547       return SDValue();
15548
15549     // To match the shuffle mask, the first half of the mask should
15550     // be exactly the first vector, and all the rest a splat with the
15551     // first element of the second one.
15552     for (unsigned i = 0; i != NumElems/2; ++i)
15553       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15554           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15555         return SDValue();
15556
15557     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15558     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15559       if (Ld->hasNUsesOfValue(1, 0)) {
15560         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15561         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15562         SDValue ResNode =
15563           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15564                                   array_lengthof(Ops),
15565                                   Ld->getMemoryVT(),
15566                                   Ld->getPointerInfo(),
15567                                   Ld->getAlignment(),
15568                                   false/*isVolatile*/, true/*ReadMem*/,
15569                                   false/*WriteMem*/);
15570
15571         // Make sure the newly-created LOAD is in the same position as Ld in
15572         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15573         // and update uses of Ld's output chain to use the TokenFactor.
15574         if (Ld->hasAnyUseOfValue(1)) {
15575           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15576                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15577           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15578           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15579                                  SDValue(ResNode.getNode(), 1));
15580         }
15581
15582         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15583       }
15584     }
15585
15586     // Emit a zeroed vector and insert the desired subvector on its
15587     // first half.
15588     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15589     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15590     return DCI.CombineTo(N, InsV);
15591   }
15592
15593   //===--------------------------------------------------------------------===//
15594   // Combine some shuffles into subvector extracts and inserts:
15595   //
15596
15597   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15598   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15599     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15600     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15601     return DCI.CombineTo(N, InsV);
15602   }
15603
15604   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15605   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15606     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15607     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15608     return DCI.CombineTo(N, InsV);
15609   }
15610
15611   return SDValue();
15612 }
15613
15614 /// PerformShuffleCombine - Performs several different shuffle combines.
15615 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15616                                      TargetLowering::DAGCombinerInfo &DCI,
15617                                      const X86Subtarget *Subtarget) {
15618   SDLoc dl(N);
15619   EVT VT = N->getValueType(0);
15620
15621   // Don't create instructions with illegal types after legalize types has run.
15622   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15623   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15624     return SDValue();
15625
15626   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15627   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15628       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15629     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15630
15631   // Only handle 128 wide vector from here on.
15632   if (!VT.is128BitVector())
15633     return SDValue();
15634
15635   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15636   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15637   // consecutive, non-overlapping, and in the right order.
15638   SmallVector<SDValue, 16> Elts;
15639   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15640     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15641
15642   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15643 }
15644
15645 /// PerformTruncateCombine - Converts truncate operation to
15646 /// a sequence of vector shuffle operations.
15647 /// It is possible when we truncate 256-bit vector to 128-bit vector
15648 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15649                                       TargetLowering::DAGCombinerInfo &DCI,
15650                                       const X86Subtarget *Subtarget)  {
15651   return SDValue();
15652 }
15653
15654 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15655 /// specific shuffle of a load can be folded into a single element load.
15656 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15657 /// shuffles have been customed lowered so we need to handle those here.
15658 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15659                                          TargetLowering::DAGCombinerInfo &DCI) {
15660   if (DCI.isBeforeLegalizeOps())
15661     return SDValue();
15662
15663   SDValue InVec = N->getOperand(0);
15664   SDValue EltNo = N->getOperand(1);
15665
15666   if (!isa<ConstantSDNode>(EltNo))
15667     return SDValue();
15668
15669   EVT VT = InVec.getValueType();
15670
15671   bool HasShuffleIntoBitcast = false;
15672   if (InVec.getOpcode() == ISD::BITCAST) {
15673     // Don't duplicate a load with other uses.
15674     if (!InVec.hasOneUse())
15675       return SDValue();
15676     EVT BCVT = InVec.getOperand(0).getValueType();
15677     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15678       return SDValue();
15679     InVec = InVec.getOperand(0);
15680     HasShuffleIntoBitcast = true;
15681   }
15682
15683   if (!isTargetShuffle(InVec.getOpcode()))
15684     return SDValue();
15685
15686   // Don't duplicate a load with other uses.
15687   if (!InVec.hasOneUse())
15688     return SDValue();
15689
15690   SmallVector<int, 16> ShuffleMask;
15691   bool UnaryShuffle;
15692   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15693                             UnaryShuffle))
15694     return SDValue();
15695
15696   // Select the input vector, guarding against out of range extract vector.
15697   unsigned NumElems = VT.getVectorNumElements();
15698   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15699   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15700   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15701                                          : InVec.getOperand(1);
15702
15703   // If inputs to shuffle are the same for both ops, then allow 2 uses
15704   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15705
15706   if (LdNode.getOpcode() == ISD::BITCAST) {
15707     // Don't duplicate a load with other uses.
15708     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15709       return SDValue();
15710
15711     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15712     LdNode = LdNode.getOperand(0);
15713   }
15714
15715   if (!ISD::isNormalLoad(LdNode.getNode()))
15716     return SDValue();
15717
15718   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15719
15720   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15721     return SDValue();
15722
15723   if (HasShuffleIntoBitcast) {
15724     // If there's a bitcast before the shuffle, check if the load type and
15725     // alignment is valid.
15726     unsigned Align = LN0->getAlignment();
15727     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15728     unsigned NewAlign = TLI.getDataLayout()->
15729       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15730
15731     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15732       return SDValue();
15733   }
15734
15735   // All checks match so transform back to vector_shuffle so that DAG combiner
15736   // can finish the job
15737   SDLoc dl(N);
15738
15739   // Create shuffle node taking into account the case that its a unary shuffle
15740   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15741   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15742                                  InVec.getOperand(0), Shuffle,
15743                                  &ShuffleMask[0]);
15744   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15745   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15746                      EltNo);
15747 }
15748
15749 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15750 /// generation and convert it from being a bunch of shuffles and extracts
15751 /// to a simple store and scalar loads to extract the elements.
15752 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15753                                          TargetLowering::DAGCombinerInfo &DCI) {
15754   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15755   if (NewOp.getNode())
15756     return NewOp;
15757
15758   SDValue InputVector = N->getOperand(0);
15759   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15760   // from mmx to v2i32 has a single usage.
15761   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15762       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15763       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15764     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15765                        N->getValueType(0),
15766                        InputVector.getNode()->getOperand(0));
15767
15768   // Only operate on vectors of 4 elements, where the alternative shuffling
15769   // gets to be more expensive.
15770   if (InputVector.getValueType() != MVT::v4i32)
15771     return SDValue();
15772
15773   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15774   // single use which is a sign-extend or zero-extend, and all elements are
15775   // used.
15776   SmallVector<SDNode *, 4> Uses;
15777   unsigned ExtractedElements = 0;
15778   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15779        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15780     if (UI.getUse().getResNo() != InputVector.getResNo())
15781       return SDValue();
15782
15783     SDNode *Extract = *UI;
15784     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15785       return SDValue();
15786
15787     if (Extract->getValueType(0) != MVT::i32)
15788       return SDValue();
15789     if (!Extract->hasOneUse())
15790       return SDValue();
15791     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15792         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15793       return SDValue();
15794     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15795       return SDValue();
15796
15797     // Record which element was extracted.
15798     ExtractedElements |=
15799       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15800
15801     Uses.push_back(Extract);
15802   }
15803
15804   // If not all the elements were used, this may not be worthwhile.
15805   if (ExtractedElements != 15)
15806     return SDValue();
15807
15808   // Ok, we've now decided to do the transformation.
15809   SDLoc dl(InputVector);
15810
15811   // Store the value to a temporary stack slot.
15812   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15813   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15814                             MachinePointerInfo(), false, false, 0);
15815
15816   // Replace each use (extract) with a load of the appropriate element.
15817   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15818        UE = Uses.end(); UI != UE; ++UI) {
15819     SDNode *Extract = *UI;
15820
15821     // cOMpute the element's address.
15822     SDValue Idx = Extract->getOperand(1);
15823     unsigned EltSize =
15824         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15825     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15826     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15827     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15828
15829     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15830                                      StackPtr, OffsetVal);
15831
15832     // Load the scalar.
15833     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15834                                      ScalarAddr, MachinePointerInfo(),
15835                                      false, false, false, 0);
15836
15837     // Replace the exact with the load.
15838     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15839   }
15840
15841   // The replacement was made in place; don't return anything.
15842   return SDValue();
15843 }
15844
15845 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15846 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15847                                    SDValue RHS, SelectionDAG &DAG,
15848                                    const X86Subtarget *Subtarget) {
15849   if (!VT.isVector())
15850     return 0;
15851
15852   switch (VT.getSimpleVT().SimpleTy) {
15853   default: return 0;
15854   case MVT::v32i8:
15855   case MVT::v16i16:
15856   case MVT::v8i32:
15857     if (!Subtarget->hasAVX2())
15858       return 0;
15859   case MVT::v16i8:
15860   case MVT::v8i16:
15861   case MVT::v4i32:
15862     if (!Subtarget->hasSSE2())
15863       return 0;
15864   }
15865
15866   // SSE2 has only a small subset of the operations.
15867   bool hasUnsigned = Subtarget->hasSSE41() ||
15868                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15869   bool hasSigned = Subtarget->hasSSE41() ||
15870                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15871
15872   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15873
15874   // Check for x CC y ? x : y.
15875   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15876       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15877     switch (CC) {
15878     default: break;
15879     case ISD::SETULT:
15880     case ISD::SETULE:
15881       return hasUnsigned ? X86ISD::UMIN : 0;
15882     case ISD::SETUGT:
15883     case ISD::SETUGE:
15884       return hasUnsigned ? X86ISD::UMAX : 0;
15885     case ISD::SETLT:
15886     case ISD::SETLE:
15887       return hasSigned ? X86ISD::SMIN : 0;
15888     case ISD::SETGT:
15889     case ISD::SETGE:
15890       return hasSigned ? X86ISD::SMAX : 0;
15891     }
15892   // Check for x CC y ? y : x -- a min/max with reversed arms.
15893   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15894              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15895     switch (CC) {
15896     default: break;
15897     case ISD::SETULT:
15898     case ISD::SETULE:
15899       return hasUnsigned ? X86ISD::UMAX : 0;
15900     case ISD::SETUGT:
15901     case ISD::SETUGE:
15902       return hasUnsigned ? X86ISD::UMIN : 0;
15903     case ISD::SETLT:
15904     case ISD::SETLE:
15905       return hasSigned ? X86ISD::SMAX : 0;
15906     case ISD::SETGT:
15907     case ISD::SETGE:
15908       return hasSigned ? X86ISD::SMIN : 0;
15909     }
15910   }
15911
15912   return 0;
15913 }
15914
15915 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15916 /// nodes.
15917 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15918                                     TargetLowering::DAGCombinerInfo &DCI,
15919                                     const X86Subtarget *Subtarget) {
15920   SDLoc DL(N);
15921   SDValue Cond = N->getOperand(0);
15922   // Get the LHS/RHS of the select.
15923   SDValue LHS = N->getOperand(1);
15924   SDValue RHS = N->getOperand(2);
15925   EVT VT = LHS.getValueType();
15926
15927   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15928   // instructions match the semantics of the common C idiom x<y?x:y but not
15929   // x<=y?x:y, because of how they handle negative zero (which can be
15930   // ignored in unsafe-math mode).
15931   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15932       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15933       (Subtarget->hasSSE2() ||
15934        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15935     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15936
15937     unsigned Opcode = 0;
15938     // Check for x CC y ? x : y.
15939     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15940         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15941       switch (CC) {
15942       default: break;
15943       case ISD::SETULT:
15944         // Converting this to a min would handle NaNs incorrectly, and swapping
15945         // the operands would cause it to handle comparisons between positive
15946         // and negative zero incorrectly.
15947         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15948           if (!DAG.getTarget().Options.UnsafeFPMath &&
15949               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15950             break;
15951           std::swap(LHS, RHS);
15952         }
15953         Opcode = X86ISD::FMIN;
15954         break;
15955       case ISD::SETOLE:
15956         // Converting this to a min would handle comparisons between positive
15957         // and negative zero incorrectly.
15958         if (!DAG.getTarget().Options.UnsafeFPMath &&
15959             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15960           break;
15961         Opcode = X86ISD::FMIN;
15962         break;
15963       case ISD::SETULE:
15964         // Converting this to a min would handle both negative zeros and NaNs
15965         // incorrectly, but we can swap the operands to fix both.
15966         std::swap(LHS, RHS);
15967       case ISD::SETOLT:
15968       case ISD::SETLT:
15969       case ISD::SETLE:
15970         Opcode = X86ISD::FMIN;
15971         break;
15972
15973       case ISD::SETOGE:
15974         // Converting this to a max would handle comparisons between positive
15975         // and negative zero incorrectly.
15976         if (!DAG.getTarget().Options.UnsafeFPMath &&
15977             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15978           break;
15979         Opcode = X86ISD::FMAX;
15980         break;
15981       case ISD::SETUGT:
15982         // Converting this to a max would handle NaNs incorrectly, and swapping
15983         // the operands would cause it to handle comparisons between positive
15984         // and negative zero incorrectly.
15985         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15986           if (!DAG.getTarget().Options.UnsafeFPMath &&
15987               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15988             break;
15989           std::swap(LHS, RHS);
15990         }
15991         Opcode = X86ISD::FMAX;
15992         break;
15993       case ISD::SETUGE:
15994         // Converting this to a max would handle both negative zeros and NaNs
15995         // incorrectly, but we can swap the operands to fix both.
15996         std::swap(LHS, RHS);
15997       case ISD::SETOGT:
15998       case ISD::SETGT:
15999       case ISD::SETGE:
16000         Opcode = X86ISD::FMAX;
16001         break;
16002       }
16003     // Check for x CC y ? y : x -- a min/max with reversed arms.
16004     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
16005                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
16006       switch (CC) {
16007       default: break;
16008       case ISD::SETOGE:
16009         // Converting this to a min would handle comparisons between positive
16010         // and negative zero incorrectly, and swapping the operands would
16011         // cause it to handle NaNs incorrectly.
16012         if (!DAG.getTarget().Options.UnsafeFPMath &&
16013             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
16014           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16015             break;
16016           std::swap(LHS, RHS);
16017         }
16018         Opcode = X86ISD::FMIN;
16019         break;
16020       case ISD::SETUGT:
16021         // Converting this to a min would handle NaNs incorrectly.
16022         if (!DAG.getTarget().Options.UnsafeFPMath &&
16023             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
16024           break;
16025         Opcode = X86ISD::FMIN;
16026         break;
16027       case ISD::SETUGE:
16028         // Converting this to a min would handle both negative zeros and NaNs
16029         // incorrectly, but we can swap the operands to fix both.
16030         std::swap(LHS, RHS);
16031       case ISD::SETOGT:
16032       case ISD::SETGT:
16033       case ISD::SETGE:
16034         Opcode = X86ISD::FMIN;
16035         break;
16036
16037       case ISD::SETULT:
16038         // Converting this to a max would handle NaNs incorrectly.
16039         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16040           break;
16041         Opcode = X86ISD::FMAX;
16042         break;
16043       case ISD::SETOLE:
16044         // Converting this to a max would handle comparisons between positive
16045         // and negative zero incorrectly, and swapping the operands would
16046         // cause it to handle NaNs incorrectly.
16047         if (!DAG.getTarget().Options.UnsafeFPMath &&
16048             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
16049           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
16050             break;
16051           std::swap(LHS, RHS);
16052         }
16053         Opcode = X86ISD::FMAX;
16054         break;
16055       case ISD::SETULE:
16056         // Converting this to a max would handle both negative zeros and NaNs
16057         // incorrectly, but we can swap the operands to fix both.
16058         std::swap(LHS, RHS);
16059       case ISD::SETOLT:
16060       case ISD::SETLT:
16061       case ISD::SETLE:
16062         Opcode = X86ISD::FMAX;
16063         break;
16064       }
16065     }
16066
16067     if (Opcode)
16068       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
16069   }
16070
16071   // If this is a select between two integer constants, try to do some
16072   // optimizations.
16073   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
16074     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
16075       // Don't do this for crazy integer types.
16076       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
16077         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
16078         // so that TrueC (the true value) is larger than FalseC.
16079         bool NeedsCondInvert = false;
16080
16081         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
16082             // Efficiently invertible.
16083             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
16084              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
16085               isa<ConstantSDNode>(Cond.getOperand(1))))) {
16086           NeedsCondInvert = true;
16087           std::swap(TrueC, FalseC);
16088         }
16089
16090         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
16091         if (FalseC->getAPIntValue() == 0 &&
16092             TrueC->getAPIntValue().isPowerOf2()) {
16093           if (NeedsCondInvert) // Invert the condition if needed.
16094             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16095                                DAG.getConstant(1, Cond.getValueType()));
16096
16097           // Zero extend the condition if needed.
16098           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
16099
16100           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16101           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
16102                              DAG.getConstant(ShAmt, MVT::i8));
16103         }
16104
16105         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
16106         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16107           if (NeedsCondInvert) // Invert the condition if needed.
16108             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16109                                DAG.getConstant(1, Cond.getValueType()));
16110
16111           // Zero extend the condition if needed.
16112           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16113                              FalseC->getValueType(0), Cond);
16114           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16115                              SDValue(FalseC, 0));
16116         }
16117
16118         // Optimize cases that will turn into an LEA instruction.  This requires
16119         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16120         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16121           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16122           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16123
16124           bool isFastMultiplier = false;
16125           if (Diff < 10) {
16126             switch ((unsigned char)Diff) {
16127               default: break;
16128               case 1:  // result = add base, cond
16129               case 2:  // result = lea base(    , cond*2)
16130               case 3:  // result = lea base(cond, cond*2)
16131               case 4:  // result = lea base(    , cond*4)
16132               case 5:  // result = lea base(cond, cond*4)
16133               case 8:  // result = lea base(    , cond*8)
16134               case 9:  // result = lea base(cond, cond*8)
16135                 isFastMultiplier = true;
16136                 break;
16137             }
16138           }
16139
16140           if (isFastMultiplier) {
16141             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16142             if (NeedsCondInvert) // Invert the condition if needed.
16143               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
16144                                  DAG.getConstant(1, Cond.getValueType()));
16145
16146             // Zero extend the condition if needed.
16147             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16148                                Cond);
16149             // Scale the condition by the difference.
16150             if (Diff != 1)
16151               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16152                                  DAG.getConstant(Diff, Cond.getValueType()));
16153
16154             // Add the base if non-zero.
16155             if (FalseC->getAPIntValue() != 0)
16156               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16157                                  SDValue(FalseC, 0));
16158             return Cond;
16159           }
16160         }
16161       }
16162   }
16163
16164   // Canonicalize max and min:
16165   // (x > y) ? x : y -> (x >= y) ? x : y
16166   // (x < y) ? x : y -> (x <= y) ? x : y
16167   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
16168   // the need for an extra compare
16169   // against zero. e.g.
16170   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
16171   // subl   %esi, %edi
16172   // testl  %edi, %edi
16173   // movl   $0, %eax
16174   // cmovgl %edi, %eax
16175   // =>
16176   // xorl   %eax, %eax
16177   // subl   %esi, $edi
16178   // cmovsl %eax, %edi
16179   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
16180       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
16181       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
16182     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16183     switch (CC) {
16184     default: break;
16185     case ISD::SETLT:
16186     case ISD::SETGT: {
16187       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
16188       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
16189                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
16190       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
16191     }
16192     }
16193   }
16194
16195   // Match VSELECTs into subs with unsigned saturation.
16196   if (!DCI.isBeforeLegalize() &&
16197       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
16198       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
16199       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
16200        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
16201     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16202
16203     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
16204     // left side invert the predicate to simplify logic below.
16205     SDValue Other;
16206     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
16207       Other = RHS;
16208       CC = ISD::getSetCCInverse(CC, true);
16209     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
16210       Other = LHS;
16211     }
16212
16213     if (Other.getNode() && Other->getNumOperands() == 2 &&
16214         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
16215       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
16216       SDValue CondRHS = Cond->getOperand(1);
16217
16218       // Look for a general sub with unsigned saturation first.
16219       // x >= y ? x-y : 0 --> subus x, y
16220       // x >  y ? x-y : 0 --> subus x, y
16221       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
16222           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
16223         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16224
16225       // If the RHS is a constant we have to reverse the const canonicalization.
16226       // x > C-1 ? x+-C : 0 --> subus x, C
16227       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
16228           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
16229         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16230         if (CondRHS.getConstantOperandVal(0) == -A-1)
16231           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
16232                              DAG.getConstant(-A, VT));
16233       }
16234
16235       // Another special case: If C was a sign bit, the sub has been
16236       // canonicalized into a xor.
16237       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
16238       //        it's safe to decanonicalize the xor?
16239       // x s< 0 ? x^C : 0 --> subus x, C
16240       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
16241           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
16242           isSplatVector(OpRHS.getNode())) {
16243         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
16244         if (A.isSignBit())
16245           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
16246       }
16247     }
16248   }
16249
16250   // Try to match a min/max vector operation.
16251   if (!DCI.isBeforeLegalize() &&
16252       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
16253     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
16254       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
16255
16256   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
16257   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
16258       Cond.getOpcode() == ISD::SETCC) {
16259
16260     assert(Cond.getValueType().isVector() &&
16261            "vector select expects a vector selector!");
16262
16263     EVT IntVT = Cond.getValueType();
16264     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
16265     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
16266
16267     if (!TValIsAllOnes && !FValIsAllZeros) {
16268       // Try invert the condition if true value is not all 1s and false value
16269       // is not all 0s.
16270       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
16271       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
16272
16273       if (TValIsAllZeros || FValIsAllOnes) {
16274         SDValue CC = Cond.getOperand(2);
16275         ISD::CondCode NewCC =
16276           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
16277                                Cond.getOperand(0).getValueType().isInteger());
16278         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
16279         std::swap(LHS, RHS);
16280         TValIsAllOnes = FValIsAllOnes;
16281         FValIsAllZeros = TValIsAllZeros;
16282       }
16283     }
16284
16285     if (TValIsAllOnes || FValIsAllZeros) {
16286       SDValue Ret;
16287
16288       if (TValIsAllOnes && FValIsAllZeros)
16289         Ret = Cond;
16290       else if (TValIsAllOnes)
16291         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
16292                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
16293       else if (FValIsAllZeros)
16294         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
16295                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
16296
16297       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
16298     }
16299   }
16300
16301   // If we know that this node is legal then we know that it is going to be
16302   // matched by one of the SSE/AVX BLEND instructions. These instructions only
16303   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
16304   // to simplify previous instructions.
16305   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16306   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
16307       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
16308     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
16309
16310     // Don't optimize vector selects that map to mask-registers.
16311     if (BitWidth == 1)
16312       return SDValue();
16313
16314     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
16315     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
16316
16317     APInt KnownZero, KnownOne;
16318     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
16319                                           DCI.isBeforeLegalizeOps());
16320     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
16321         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
16322       DCI.CommitTargetLoweringOpt(TLO);
16323   }
16324
16325   return SDValue();
16326 }
16327
16328 // Check whether a boolean test is testing a boolean value generated by
16329 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
16330 // code.
16331 //
16332 // Simplify the following patterns:
16333 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
16334 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
16335 // to (Op EFLAGS Cond)
16336 //
16337 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
16338 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
16339 // to (Op EFLAGS !Cond)
16340 //
16341 // where Op could be BRCOND or CMOV.
16342 //
16343 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
16344   // Quit if not CMP and SUB with its value result used.
16345   if (Cmp.getOpcode() != X86ISD::CMP &&
16346       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
16347       return SDValue();
16348
16349   // Quit if not used as a boolean value.
16350   if (CC != X86::COND_E && CC != X86::COND_NE)
16351     return SDValue();
16352
16353   // Check CMP operands. One of them should be 0 or 1 and the other should be
16354   // an SetCC or extended from it.
16355   SDValue Op1 = Cmp.getOperand(0);
16356   SDValue Op2 = Cmp.getOperand(1);
16357
16358   SDValue SetCC;
16359   const ConstantSDNode* C = 0;
16360   bool needOppositeCond = (CC == X86::COND_E);
16361   bool checkAgainstTrue = false; // Is it a comparison against 1?
16362
16363   if ((C = dyn_cast<ConstantSDNode>(Op1)))
16364     SetCC = Op2;
16365   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
16366     SetCC = Op1;
16367   else // Quit if all operands are not constants.
16368     return SDValue();
16369
16370   if (C->getZExtValue() == 1) {
16371     needOppositeCond = !needOppositeCond;
16372     checkAgainstTrue = true;
16373   } else if (C->getZExtValue() != 0)
16374     // Quit if the constant is neither 0 or 1.
16375     return SDValue();
16376
16377   bool truncatedToBoolWithAnd = false;
16378   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
16379   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
16380          SetCC.getOpcode() == ISD::TRUNCATE ||
16381          SetCC.getOpcode() == ISD::AND) {
16382     if (SetCC.getOpcode() == ISD::AND) {
16383       int OpIdx = -1;
16384       ConstantSDNode *CS;
16385       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
16386           CS->getZExtValue() == 1)
16387         OpIdx = 1;
16388       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
16389           CS->getZExtValue() == 1)
16390         OpIdx = 0;
16391       if (OpIdx == -1)
16392         break;
16393       SetCC = SetCC.getOperand(OpIdx);
16394       truncatedToBoolWithAnd = true;
16395     } else
16396       SetCC = SetCC.getOperand(0);
16397   }
16398
16399   switch (SetCC.getOpcode()) {
16400   case X86ISD::SETCC_CARRY:
16401     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
16402     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
16403     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
16404     // truncated to i1 using 'and'.
16405     if (checkAgainstTrue && !truncatedToBoolWithAnd)
16406       break;
16407     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
16408            "Invalid use of SETCC_CARRY!");
16409     // FALL THROUGH
16410   case X86ISD::SETCC:
16411     // Set the condition code or opposite one if necessary.
16412     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
16413     if (needOppositeCond)
16414       CC = X86::GetOppositeBranchCondition(CC);
16415     return SetCC.getOperand(1);
16416   case X86ISD::CMOV: {
16417     // Check whether false/true value has canonical one, i.e. 0 or 1.
16418     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16419     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16420     // Quit if true value is not a constant.
16421     if (!TVal)
16422       return SDValue();
16423     // Quit if false value is not a constant.
16424     if (!FVal) {
16425       SDValue Op = SetCC.getOperand(0);
16426       // Skip 'zext' or 'trunc' node.
16427       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16428           Op.getOpcode() == ISD::TRUNCATE)
16429         Op = Op.getOperand(0);
16430       // A special case for rdrand/rdseed, where 0 is set if false cond is
16431       // found.
16432       if ((Op.getOpcode() != X86ISD::RDRAND &&
16433            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16434         return SDValue();
16435     }
16436     // Quit if false value is not the constant 0 or 1.
16437     bool FValIsFalse = true;
16438     if (FVal && FVal->getZExtValue() != 0) {
16439       if (FVal->getZExtValue() != 1)
16440         return SDValue();
16441       // If FVal is 1, opposite cond is needed.
16442       needOppositeCond = !needOppositeCond;
16443       FValIsFalse = false;
16444     }
16445     // Quit if TVal is not the constant opposite of FVal.
16446     if (FValIsFalse && TVal->getZExtValue() != 1)
16447       return SDValue();
16448     if (!FValIsFalse && TVal->getZExtValue() != 0)
16449       return SDValue();
16450     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16451     if (needOppositeCond)
16452       CC = X86::GetOppositeBranchCondition(CC);
16453     return SetCC.getOperand(3);
16454   }
16455   }
16456
16457   return SDValue();
16458 }
16459
16460 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16461 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16462                                   TargetLowering::DAGCombinerInfo &DCI,
16463                                   const X86Subtarget *Subtarget) {
16464   SDLoc DL(N);
16465
16466   // If the flag operand isn't dead, don't touch this CMOV.
16467   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16468     return SDValue();
16469
16470   SDValue FalseOp = N->getOperand(0);
16471   SDValue TrueOp = N->getOperand(1);
16472   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16473   SDValue Cond = N->getOperand(3);
16474
16475   if (CC == X86::COND_E || CC == X86::COND_NE) {
16476     switch (Cond.getOpcode()) {
16477     default: break;
16478     case X86ISD::BSR:
16479     case X86ISD::BSF:
16480       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16481       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16482         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16483     }
16484   }
16485
16486   SDValue Flags;
16487
16488   Flags = checkBoolTestSetCCCombine(Cond, CC);
16489   if (Flags.getNode() &&
16490       // Extra check as FCMOV only supports a subset of X86 cond.
16491       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16492     SDValue Ops[] = { FalseOp, TrueOp,
16493                       DAG.getConstant(CC, MVT::i8), Flags };
16494     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16495                        Ops, array_lengthof(Ops));
16496   }
16497
16498   // If this is a select between two integer constants, try to do some
16499   // optimizations.  Note that the operands are ordered the opposite of SELECT
16500   // operands.
16501   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16502     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16503       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16504       // larger than FalseC (the false value).
16505       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16506         CC = X86::GetOppositeBranchCondition(CC);
16507         std::swap(TrueC, FalseC);
16508         std::swap(TrueOp, FalseOp);
16509       }
16510
16511       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16512       // This is efficient for any integer data type (including i8/i16) and
16513       // shift amount.
16514       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16515         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16516                            DAG.getConstant(CC, MVT::i8), Cond);
16517
16518         // Zero extend the condition if needed.
16519         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16520
16521         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16522         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16523                            DAG.getConstant(ShAmt, MVT::i8));
16524         if (N->getNumValues() == 2)  // Dead flag value?
16525           return DCI.CombineTo(N, Cond, SDValue());
16526         return Cond;
16527       }
16528
16529       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16530       // for any integer data type, including i8/i16.
16531       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16532         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16533                            DAG.getConstant(CC, MVT::i8), Cond);
16534
16535         // Zero extend the condition if needed.
16536         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16537                            FalseC->getValueType(0), Cond);
16538         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16539                            SDValue(FalseC, 0));
16540
16541         if (N->getNumValues() == 2)  // Dead flag value?
16542           return DCI.CombineTo(N, Cond, SDValue());
16543         return Cond;
16544       }
16545
16546       // Optimize cases that will turn into an LEA instruction.  This requires
16547       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16548       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16549         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16550         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16551
16552         bool isFastMultiplier = false;
16553         if (Diff < 10) {
16554           switch ((unsigned char)Diff) {
16555           default: break;
16556           case 1:  // result = add base, cond
16557           case 2:  // result = lea base(    , cond*2)
16558           case 3:  // result = lea base(cond, cond*2)
16559           case 4:  // result = lea base(    , cond*4)
16560           case 5:  // result = lea base(cond, cond*4)
16561           case 8:  // result = lea base(    , cond*8)
16562           case 9:  // result = lea base(cond, cond*8)
16563             isFastMultiplier = true;
16564             break;
16565           }
16566         }
16567
16568         if (isFastMultiplier) {
16569           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16570           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16571                              DAG.getConstant(CC, MVT::i8), Cond);
16572           // Zero extend the condition if needed.
16573           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16574                              Cond);
16575           // Scale the condition by the difference.
16576           if (Diff != 1)
16577             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16578                                DAG.getConstant(Diff, Cond.getValueType()));
16579
16580           // Add the base if non-zero.
16581           if (FalseC->getAPIntValue() != 0)
16582             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16583                                SDValue(FalseC, 0));
16584           if (N->getNumValues() == 2)  // Dead flag value?
16585             return DCI.CombineTo(N, Cond, SDValue());
16586           return Cond;
16587         }
16588       }
16589     }
16590   }
16591
16592   // Handle these cases:
16593   //   (select (x != c), e, c) -> select (x != c), e, x),
16594   //   (select (x == c), c, e) -> select (x == c), x, e)
16595   // where the c is an integer constant, and the "select" is the combination
16596   // of CMOV and CMP.
16597   //
16598   // The rationale for this change is that the conditional-move from a constant
16599   // needs two instructions, however, conditional-move from a register needs
16600   // only one instruction.
16601   //
16602   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16603   //  some instruction-combining opportunities. This opt needs to be
16604   //  postponed as late as possible.
16605   //
16606   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16607     // the DCI.xxxx conditions are provided to postpone the optimization as
16608     // late as possible.
16609
16610     ConstantSDNode *CmpAgainst = 0;
16611     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16612         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16613         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16614
16615       if (CC == X86::COND_NE &&
16616           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16617         CC = X86::GetOppositeBranchCondition(CC);
16618         std::swap(TrueOp, FalseOp);
16619       }
16620
16621       if (CC == X86::COND_E &&
16622           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16623         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16624                           DAG.getConstant(CC, MVT::i8), Cond };
16625         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16626                            array_lengthof(Ops));
16627       }
16628     }
16629   }
16630
16631   return SDValue();
16632 }
16633
16634 /// PerformMulCombine - Optimize a single multiply with constant into two
16635 /// in order to implement it with two cheaper instructions, e.g.
16636 /// LEA + SHL, LEA + LEA.
16637 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16638                                  TargetLowering::DAGCombinerInfo &DCI) {
16639   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16640     return SDValue();
16641
16642   EVT VT = N->getValueType(0);
16643   if (VT != MVT::i64)
16644     return SDValue();
16645
16646   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16647   if (!C)
16648     return SDValue();
16649   uint64_t MulAmt = C->getZExtValue();
16650   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16651     return SDValue();
16652
16653   uint64_t MulAmt1 = 0;
16654   uint64_t MulAmt2 = 0;
16655   if ((MulAmt % 9) == 0) {
16656     MulAmt1 = 9;
16657     MulAmt2 = MulAmt / 9;
16658   } else if ((MulAmt % 5) == 0) {
16659     MulAmt1 = 5;
16660     MulAmt2 = MulAmt / 5;
16661   } else if ((MulAmt % 3) == 0) {
16662     MulAmt1 = 3;
16663     MulAmt2 = MulAmt / 3;
16664   }
16665   if (MulAmt2 &&
16666       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16667     SDLoc DL(N);
16668
16669     if (isPowerOf2_64(MulAmt2) &&
16670         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16671       // If second multiplifer is pow2, issue it first. We want the multiply by
16672       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16673       // is an add.
16674       std::swap(MulAmt1, MulAmt2);
16675
16676     SDValue NewMul;
16677     if (isPowerOf2_64(MulAmt1))
16678       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16679                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16680     else
16681       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16682                            DAG.getConstant(MulAmt1, VT));
16683
16684     if (isPowerOf2_64(MulAmt2))
16685       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16686                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16687     else
16688       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16689                            DAG.getConstant(MulAmt2, VT));
16690
16691     // Do not add new nodes to DAG combiner worklist.
16692     DCI.CombineTo(N, NewMul, false);
16693   }
16694   return SDValue();
16695 }
16696
16697 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16698   SDValue N0 = N->getOperand(0);
16699   SDValue N1 = N->getOperand(1);
16700   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16701   EVT VT = N0.getValueType();
16702
16703   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16704   // since the result of setcc_c is all zero's or all ones.
16705   if (VT.isInteger() && !VT.isVector() &&
16706       N1C && N0.getOpcode() == ISD::AND &&
16707       N0.getOperand(1).getOpcode() == ISD::Constant) {
16708     SDValue N00 = N0.getOperand(0);
16709     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16710         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16711           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16712          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16713       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16714       APInt ShAmt = N1C->getAPIntValue();
16715       Mask = Mask.shl(ShAmt);
16716       if (Mask != 0)
16717         return DAG.getNode(ISD::AND, SDLoc(N), VT,
16718                            N00, DAG.getConstant(Mask, VT));
16719     }
16720   }
16721
16722   // Hardware support for vector shifts is sparse which makes us scalarize the
16723   // vector operations in many cases. Also, on sandybridge ADD is faster than
16724   // shl.
16725   // (shl V, 1) -> add V,V
16726   if (isSplatVector(N1.getNode())) {
16727     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16728     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16729     // We shift all of the values by one. In many cases we do not have
16730     // hardware support for this operation. This is better expressed as an ADD
16731     // of two values.
16732     if (N1C && (1 == N1C->getZExtValue())) {
16733       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16734     }
16735   }
16736
16737   return SDValue();
16738 }
16739
16740 /// \brief Returns a vector of 0s if the node in input is a vector logical
16741 /// shift by a constant amount which is known to be bigger than or equal 
16742 /// to the vector element size in bits.
16743 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
16744                                       const X86Subtarget *Subtarget) {
16745   EVT VT = N->getValueType(0);
16746
16747   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
16748       (!Subtarget->hasInt256() ||
16749        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
16750     return SDValue();
16751
16752   SDValue Amt = N->getOperand(1);
16753   SDLoc DL(N);
16754   if (isSplatVector(Amt.getNode())) {
16755     SDValue SclrAmt = Amt->getOperand(0);
16756     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
16757       APInt ShiftAmt = C->getAPIntValue();
16758       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
16759
16760       // SSE2/AVX2 logical shifts always return a vector of 0s
16761       // if the shift amount is bigger than or equal to 
16762       // the element size. The constant shift amount will be
16763       // encoded as a 8-bit immediate.
16764       if (ShiftAmt.trunc(8).uge(MaxAmount))
16765         return getZeroVector(VT, Subtarget, DAG, DL);
16766     }
16767   }
16768
16769   return SDValue();
16770 }
16771
16772 /// PerformShiftCombine - Combine shifts.
16773 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16774                                    TargetLowering::DAGCombinerInfo &DCI,
16775                                    const X86Subtarget *Subtarget) {
16776   if (N->getOpcode() == ISD::SHL) {
16777     SDValue V = PerformSHLCombine(N, DAG);
16778     if (V.getNode()) return V;
16779   }
16780
16781   if (N->getOpcode() != ISD::SRA) {
16782     // Try to fold this logical shift into a zero vector.
16783     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
16784     if (V.getNode()) return V;
16785   }
16786
16787   return SDValue();
16788 }
16789
16790 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16791 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16792 // and friends.  Likewise for OR -> CMPNEQSS.
16793 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16794                             TargetLowering::DAGCombinerInfo &DCI,
16795                             const X86Subtarget *Subtarget) {
16796   unsigned opcode;
16797
16798   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16799   // we're requiring SSE2 for both.
16800   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16801     SDValue N0 = N->getOperand(0);
16802     SDValue N1 = N->getOperand(1);
16803     SDValue CMP0 = N0->getOperand(1);
16804     SDValue CMP1 = N1->getOperand(1);
16805     SDLoc DL(N);
16806
16807     // The SETCCs should both refer to the same CMP.
16808     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16809       return SDValue();
16810
16811     SDValue CMP00 = CMP0->getOperand(0);
16812     SDValue CMP01 = CMP0->getOperand(1);
16813     EVT     VT    = CMP00.getValueType();
16814
16815     if (VT == MVT::f32 || VT == MVT::f64) {
16816       bool ExpectingFlags = false;
16817       // Check for any users that want flags:
16818       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16819            !ExpectingFlags && UI != UE; ++UI)
16820         switch (UI->getOpcode()) {
16821         default:
16822         case ISD::BR_CC:
16823         case ISD::BRCOND:
16824         case ISD::SELECT:
16825           ExpectingFlags = true;
16826           break;
16827         case ISD::CopyToReg:
16828         case ISD::SIGN_EXTEND:
16829         case ISD::ZERO_EXTEND:
16830         case ISD::ANY_EXTEND:
16831           break;
16832         }
16833
16834       if (!ExpectingFlags) {
16835         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16836         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16837
16838         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16839           X86::CondCode tmp = cc0;
16840           cc0 = cc1;
16841           cc1 = tmp;
16842         }
16843
16844         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16845             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16846           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16847           X86ISD::NodeType NTOperator = is64BitFP ?
16848             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16849           // FIXME: need symbolic constants for these magic numbers.
16850           // See X86ATTInstPrinter.cpp:printSSECC().
16851           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16852           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16853                                               DAG.getConstant(x86cc, MVT::i8));
16854           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16855                                               OnesOrZeroesF);
16856           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16857                                       DAG.getConstant(1, MVT::i32));
16858           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16859           return OneBitOfTruth;
16860         }
16861       }
16862     }
16863   }
16864   return SDValue();
16865 }
16866
16867 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16868 /// so it can be folded inside ANDNP.
16869 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16870   EVT VT = N->getValueType(0);
16871
16872   // Match direct AllOnes for 128 and 256-bit vectors
16873   if (ISD::isBuildVectorAllOnes(N))
16874     return true;
16875
16876   // Look through a bit convert.
16877   if (N->getOpcode() == ISD::BITCAST)
16878     N = N->getOperand(0).getNode();
16879
16880   // Sometimes the operand may come from a insert_subvector building a 256-bit
16881   // allones vector
16882   if (VT.is256BitVector() &&
16883       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16884     SDValue V1 = N->getOperand(0);
16885     SDValue V2 = N->getOperand(1);
16886
16887     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16888         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16889         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16890         ISD::isBuildVectorAllOnes(V2.getNode()))
16891       return true;
16892   }
16893
16894   return false;
16895 }
16896
16897 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16898 // register. In most cases we actually compare or select YMM-sized registers
16899 // and mixing the two types creates horrible code. This method optimizes
16900 // some of the transition sequences.
16901 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16902                                  TargetLowering::DAGCombinerInfo &DCI,
16903                                  const X86Subtarget *Subtarget) {
16904   EVT VT = N->getValueType(0);
16905   if (!VT.is256BitVector())
16906     return SDValue();
16907
16908   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16909           N->getOpcode() == ISD::ZERO_EXTEND ||
16910           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16911
16912   SDValue Narrow = N->getOperand(0);
16913   EVT NarrowVT = Narrow->getValueType(0);
16914   if (!NarrowVT.is128BitVector())
16915     return SDValue();
16916
16917   if (Narrow->getOpcode() != ISD::XOR &&
16918       Narrow->getOpcode() != ISD::AND &&
16919       Narrow->getOpcode() != ISD::OR)
16920     return SDValue();
16921
16922   SDValue N0  = Narrow->getOperand(0);
16923   SDValue N1  = Narrow->getOperand(1);
16924   SDLoc DL(Narrow);
16925
16926   // The Left side has to be a trunc.
16927   if (N0.getOpcode() != ISD::TRUNCATE)
16928     return SDValue();
16929
16930   // The type of the truncated inputs.
16931   EVT WideVT = N0->getOperand(0)->getValueType(0);
16932   if (WideVT != VT)
16933     return SDValue();
16934
16935   // The right side has to be a 'trunc' or a constant vector.
16936   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16937   bool RHSConst = (isSplatVector(N1.getNode()) &&
16938                    isa<ConstantSDNode>(N1->getOperand(0)));
16939   if (!RHSTrunc && !RHSConst)
16940     return SDValue();
16941
16942   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16943
16944   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16945     return SDValue();
16946
16947   // Set N0 and N1 to hold the inputs to the new wide operation.
16948   N0 = N0->getOperand(0);
16949   if (RHSConst) {
16950     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16951                      N1->getOperand(0));
16952     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16953     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16954   } else if (RHSTrunc) {
16955     N1 = N1->getOperand(0);
16956   }
16957
16958   // Generate the wide operation.
16959   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16960   unsigned Opcode = N->getOpcode();
16961   switch (Opcode) {
16962   case ISD::ANY_EXTEND:
16963     return Op;
16964   case ISD::ZERO_EXTEND: {
16965     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16966     APInt Mask = APInt::getAllOnesValue(InBits);
16967     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16968     return DAG.getNode(ISD::AND, DL, VT,
16969                        Op, DAG.getConstant(Mask, VT));
16970   }
16971   case ISD::SIGN_EXTEND:
16972     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16973                        Op, DAG.getValueType(NarrowVT));
16974   default:
16975     llvm_unreachable("Unexpected opcode");
16976   }
16977 }
16978
16979 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16980                                  TargetLowering::DAGCombinerInfo &DCI,
16981                                  const X86Subtarget *Subtarget) {
16982   EVT VT = N->getValueType(0);
16983   if (DCI.isBeforeLegalizeOps())
16984     return SDValue();
16985
16986   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16987   if (R.getNode())
16988     return R;
16989
16990   // Create BLSI, and BLSR instructions
16991   // BLSI is X & (-X)
16992   // BLSR is X & (X-1)
16993   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16994     SDValue N0 = N->getOperand(0);
16995     SDValue N1 = N->getOperand(1);
16996     SDLoc DL(N);
16997
16998     // Check LHS for neg
16999     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
17000         isZero(N0.getOperand(0)))
17001       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
17002
17003     // Check RHS for neg
17004     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
17005         isZero(N1.getOperand(0)))
17006       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
17007
17008     // Check LHS for X-1
17009     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17010         isAllOnes(N0.getOperand(1)))
17011       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
17012
17013     // Check RHS for X-1
17014     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17015         isAllOnes(N1.getOperand(1)))
17016       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
17017
17018     return SDValue();
17019   }
17020
17021   // Want to form ANDNP nodes:
17022   // 1) In the hopes of then easily combining them with OR and AND nodes
17023   //    to form PBLEND/PSIGN.
17024   // 2) To match ANDN packed intrinsics
17025   if (VT != MVT::v2i64 && VT != MVT::v4i64)
17026     return SDValue();
17027
17028   SDValue N0 = N->getOperand(0);
17029   SDValue N1 = N->getOperand(1);
17030   SDLoc DL(N);
17031
17032   // Check LHS for vnot
17033   if (N0.getOpcode() == ISD::XOR &&
17034       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
17035       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
17036     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
17037
17038   // Check RHS for vnot
17039   if (N1.getOpcode() == ISD::XOR &&
17040       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
17041       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
17042     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
17043
17044   return SDValue();
17045 }
17046
17047 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
17048                                 TargetLowering::DAGCombinerInfo &DCI,
17049                                 const X86Subtarget *Subtarget) {
17050   EVT VT = N->getValueType(0);
17051   if (DCI.isBeforeLegalizeOps())
17052     return SDValue();
17053
17054   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
17055   if (R.getNode())
17056     return R;
17057
17058   SDValue N0 = N->getOperand(0);
17059   SDValue N1 = N->getOperand(1);
17060
17061   // look for psign/blend
17062   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
17063     if (!Subtarget->hasSSSE3() ||
17064         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
17065       return SDValue();
17066
17067     // Canonicalize pandn to RHS
17068     if (N0.getOpcode() == X86ISD::ANDNP)
17069       std::swap(N0, N1);
17070     // or (and (m, y), (pandn m, x))
17071     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
17072       SDValue Mask = N1.getOperand(0);
17073       SDValue X    = N1.getOperand(1);
17074       SDValue Y;
17075       if (N0.getOperand(0) == Mask)
17076         Y = N0.getOperand(1);
17077       if (N0.getOperand(1) == Mask)
17078         Y = N0.getOperand(0);
17079
17080       // Check to see if the mask appeared in both the AND and ANDNP and
17081       if (!Y.getNode())
17082         return SDValue();
17083
17084       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
17085       // Look through mask bitcast.
17086       if (Mask.getOpcode() == ISD::BITCAST)
17087         Mask = Mask.getOperand(0);
17088       if (X.getOpcode() == ISD::BITCAST)
17089         X = X.getOperand(0);
17090       if (Y.getOpcode() == ISD::BITCAST)
17091         Y = Y.getOperand(0);
17092
17093       EVT MaskVT = Mask.getValueType();
17094
17095       // Validate that the Mask operand is a vector sra node.
17096       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
17097       // there is no psrai.b
17098       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
17099       unsigned SraAmt = ~0;
17100       if (Mask.getOpcode() == ISD::SRA) {
17101         SDValue Amt = Mask.getOperand(1);
17102         if (isSplatVector(Amt.getNode())) {
17103           SDValue SclrAmt = Amt->getOperand(0);
17104           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
17105             SraAmt = C->getZExtValue();
17106         }
17107       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
17108         SDValue SraC = Mask.getOperand(1);
17109         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
17110       }
17111       if ((SraAmt + 1) != EltBits)
17112         return SDValue();
17113
17114       SDLoc DL(N);
17115
17116       // Now we know we at least have a plendvb with the mask val.  See if
17117       // we can form a psignb/w/d.
17118       // psign = x.type == y.type == mask.type && y = sub(0, x);
17119       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
17120           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
17121           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
17122         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
17123                "Unsupported VT for PSIGN");
17124         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
17125         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17126       }
17127       // PBLENDVB only available on SSE 4.1
17128       if (!Subtarget->hasSSE41())
17129         return SDValue();
17130
17131       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
17132
17133       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
17134       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
17135       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
17136       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
17137       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
17138     }
17139   }
17140
17141   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
17142     return SDValue();
17143
17144   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
17145   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
17146     std::swap(N0, N1);
17147   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
17148     return SDValue();
17149   if (!N0.hasOneUse() || !N1.hasOneUse())
17150     return SDValue();
17151
17152   SDValue ShAmt0 = N0.getOperand(1);
17153   if (ShAmt0.getValueType() != MVT::i8)
17154     return SDValue();
17155   SDValue ShAmt1 = N1.getOperand(1);
17156   if (ShAmt1.getValueType() != MVT::i8)
17157     return SDValue();
17158   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
17159     ShAmt0 = ShAmt0.getOperand(0);
17160   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
17161     ShAmt1 = ShAmt1.getOperand(0);
17162
17163   SDLoc DL(N);
17164   unsigned Opc = X86ISD::SHLD;
17165   SDValue Op0 = N0.getOperand(0);
17166   SDValue Op1 = N1.getOperand(0);
17167   if (ShAmt0.getOpcode() == ISD::SUB) {
17168     Opc = X86ISD::SHRD;
17169     std::swap(Op0, Op1);
17170     std::swap(ShAmt0, ShAmt1);
17171   }
17172
17173   unsigned Bits = VT.getSizeInBits();
17174   if (ShAmt1.getOpcode() == ISD::SUB) {
17175     SDValue Sum = ShAmt1.getOperand(0);
17176     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
17177       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
17178       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
17179         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
17180       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
17181         return DAG.getNode(Opc, DL, VT,
17182                            Op0, Op1,
17183                            DAG.getNode(ISD::TRUNCATE, DL,
17184                                        MVT::i8, ShAmt0));
17185     }
17186   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
17187     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
17188     if (ShAmt0C &&
17189         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
17190       return DAG.getNode(Opc, DL, VT,
17191                          N0.getOperand(0), N1.getOperand(0),
17192                          DAG.getNode(ISD::TRUNCATE, DL,
17193                                        MVT::i8, ShAmt0));
17194   }
17195
17196   return SDValue();
17197 }
17198
17199 // Generate NEG and CMOV for integer abs.
17200 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
17201   EVT VT = N->getValueType(0);
17202
17203   // Since X86 does not have CMOV for 8-bit integer, we don't convert
17204   // 8-bit integer abs to NEG and CMOV.
17205   if (VT.isInteger() && VT.getSizeInBits() == 8)
17206     return SDValue();
17207
17208   SDValue N0 = N->getOperand(0);
17209   SDValue N1 = N->getOperand(1);
17210   SDLoc DL(N);
17211
17212   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
17213   // and change it to SUB and CMOV.
17214   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
17215       N0.getOpcode() == ISD::ADD &&
17216       N0.getOperand(1) == N1 &&
17217       N1.getOpcode() == ISD::SRA &&
17218       N1.getOperand(0) == N0.getOperand(0))
17219     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
17220       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
17221         // Generate SUB & CMOV.
17222         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
17223                                   DAG.getConstant(0, VT), N0.getOperand(0));
17224
17225         SDValue Ops[] = { N0.getOperand(0), Neg,
17226                           DAG.getConstant(X86::COND_GE, MVT::i8),
17227                           SDValue(Neg.getNode(), 1) };
17228         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
17229                            Ops, array_lengthof(Ops));
17230       }
17231   return SDValue();
17232 }
17233
17234 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
17235 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
17236                                  TargetLowering::DAGCombinerInfo &DCI,
17237                                  const X86Subtarget *Subtarget) {
17238   EVT VT = N->getValueType(0);
17239   if (DCI.isBeforeLegalizeOps())
17240     return SDValue();
17241
17242   if (Subtarget->hasCMov()) {
17243     SDValue RV = performIntegerAbsCombine(N, DAG);
17244     if (RV.getNode())
17245       return RV;
17246   }
17247
17248   // Try forming BMI if it is available.
17249   if (!Subtarget->hasBMI())
17250     return SDValue();
17251
17252   if (VT != MVT::i32 && VT != MVT::i64)
17253     return SDValue();
17254
17255   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
17256
17257   // Create BLSMSK instructions by finding X ^ (X-1)
17258   SDValue N0 = N->getOperand(0);
17259   SDValue N1 = N->getOperand(1);
17260   SDLoc DL(N);
17261
17262   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
17263       isAllOnes(N0.getOperand(1)))
17264     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
17265
17266   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
17267       isAllOnes(N1.getOperand(1)))
17268     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
17269
17270   return SDValue();
17271 }
17272
17273 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
17274 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
17275                                   TargetLowering::DAGCombinerInfo &DCI,
17276                                   const X86Subtarget *Subtarget) {
17277   LoadSDNode *Ld = cast<LoadSDNode>(N);
17278   EVT RegVT = Ld->getValueType(0);
17279   EVT MemVT = Ld->getMemoryVT();
17280   SDLoc dl(Ld);
17281   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17282   unsigned RegSz = RegVT.getSizeInBits();
17283
17284   // On Sandybridge unaligned 256bit loads are inefficient.
17285   ISD::LoadExtType Ext = Ld->getExtensionType();
17286   unsigned Alignment = Ld->getAlignment();
17287   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
17288   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
17289       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
17290     unsigned NumElems = RegVT.getVectorNumElements();
17291     if (NumElems < 2)
17292       return SDValue();
17293
17294     SDValue Ptr = Ld->getBasePtr();
17295     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
17296
17297     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17298                                   NumElems/2);
17299     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17300                                 Ld->getPointerInfo(), Ld->isVolatile(),
17301                                 Ld->isNonTemporal(), Ld->isInvariant(),
17302                                 Alignment);
17303     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17304     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
17305                                 Ld->getPointerInfo(), Ld->isVolatile(),
17306                                 Ld->isNonTemporal(), Ld->isInvariant(),
17307                                 std::min(16U, Alignment));
17308     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17309                              Load1.getValue(1),
17310                              Load2.getValue(1));
17311
17312     SDValue NewVec = DAG.getUNDEF(RegVT);
17313     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
17314     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
17315     return DCI.CombineTo(N, NewVec, TF, true);
17316   }
17317
17318   // If this is a vector EXT Load then attempt to optimize it using a
17319   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
17320   // expansion is still better than scalar code.
17321   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
17322   // emit a shuffle and a arithmetic shift.
17323   // TODO: It is possible to support ZExt by zeroing the undef values
17324   // during the shuffle phase or after the shuffle.
17325   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
17326       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
17327     assert(MemVT != RegVT && "Cannot extend to the same type");
17328     assert(MemVT.isVector() && "Must load a vector from memory");
17329
17330     unsigned NumElems = RegVT.getVectorNumElements();
17331     unsigned MemSz = MemVT.getSizeInBits();
17332     assert(RegSz > MemSz && "Register size must be greater than the mem size");
17333
17334     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
17335       return SDValue();
17336
17337     // All sizes must be a power of two.
17338     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
17339       return SDValue();
17340
17341     // Attempt to load the original value using scalar loads.
17342     // Find the largest scalar type that divides the total loaded size.
17343     MVT SclrLoadTy = MVT::i8;
17344     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17345          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17346       MVT Tp = (MVT::SimpleValueType)tp;
17347       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
17348         SclrLoadTy = Tp;
17349       }
17350     }
17351
17352     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17353     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
17354         (64 <= MemSz))
17355       SclrLoadTy = MVT::f64;
17356
17357     // Calculate the number of scalar loads that we need to perform
17358     // in order to load our vector from memory.
17359     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
17360     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
17361       return SDValue();
17362
17363     unsigned loadRegZize = RegSz;
17364     if (Ext == ISD::SEXTLOAD && RegSz == 256)
17365       loadRegZize /= 2;
17366
17367     // Represent our vector as a sequence of elements which are the
17368     // largest scalar that we can load.
17369     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
17370       loadRegZize/SclrLoadTy.getSizeInBits());
17371
17372     // Represent the data using the same element type that is stored in
17373     // memory. In practice, we ''widen'' MemVT.
17374     EVT WideVecVT =
17375           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
17376                        loadRegZize/MemVT.getScalarType().getSizeInBits());
17377
17378     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
17379       "Invalid vector type");
17380
17381     // We can't shuffle using an illegal type.
17382     if (!TLI.isTypeLegal(WideVecVT))
17383       return SDValue();
17384
17385     SmallVector<SDValue, 8> Chains;
17386     SDValue Ptr = Ld->getBasePtr();
17387     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
17388                                         TLI.getPointerTy());
17389     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
17390
17391     for (unsigned i = 0; i < NumLoads; ++i) {
17392       // Perform a single load.
17393       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
17394                                        Ptr, Ld->getPointerInfo(),
17395                                        Ld->isVolatile(), Ld->isNonTemporal(),
17396                                        Ld->isInvariant(), Ld->getAlignment());
17397       Chains.push_back(ScalarLoad.getValue(1));
17398       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
17399       // another round of DAGCombining.
17400       if (i == 0)
17401         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
17402       else
17403         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
17404                           ScalarLoad, DAG.getIntPtrConstant(i));
17405
17406       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17407     }
17408
17409     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17410                                Chains.size());
17411
17412     // Bitcast the loaded value to a vector of the original element type, in
17413     // the size of the target vector type.
17414     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
17415     unsigned SizeRatio = RegSz/MemSz;
17416
17417     if (Ext == ISD::SEXTLOAD) {
17418       // If we have SSE4.1 we can directly emit a VSEXT node.
17419       if (Subtarget->hasSSE41()) {
17420         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
17421         return DCI.CombineTo(N, Sext, TF, true);
17422       }
17423
17424       // Otherwise we'll shuffle the small elements in the high bits of the
17425       // larger type and perform an arithmetic shift. If the shift is not legal
17426       // it's better to scalarize.
17427       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
17428         return SDValue();
17429
17430       // Redistribute the loaded elements into the different locations.
17431       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17432       for (unsigned i = 0; i != NumElems; ++i)
17433         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
17434
17435       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17436                                            DAG.getUNDEF(WideVecVT),
17437                                            &ShuffleVec[0]);
17438
17439       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17440
17441       // Build the arithmetic shift.
17442       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
17443                      MemVT.getVectorElementType().getSizeInBits();
17444       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
17445                           DAG.getConstant(Amt, RegVT));
17446
17447       return DCI.CombineTo(N, Shuff, TF, true);
17448     }
17449
17450     // Redistribute the loaded elements into the different locations.
17451     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17452     for (unsigned i = 0; i != NumElems; ++i)
17453       ShuffleVec[i*SizeRatio] = i;
17454
17455     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17456                                          DAG.getUNDEF(WideVecVT),
17457                                          &ShuffleVec[0]);
17458
17459     // Bitcast to the requested type.
17460     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17461     // Replace the original load with the new sequence
17462     // and return the new chain.
17463     return DCI.CombineTo(N, Shuff, TF, true);
17464   }
17465
17466   return SDValue();
17467 }
17468
17469 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17470 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17471                                    const X86Subtarget *Subtarget) {
17472   StoreSDNode *St = cast<StoreSDNode>(N);
17473   EVT VT = St->getValue().getValueType();
17474   EVT StVT = St->getMemoryVT();
17475   SDLoc dl(St);
17476   SDValue StoredVal = St->getOperand(1);
17477   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17478
17479   // If we are saving a concatenation of two XMM registers, perform two stores.
17480   // On Sandy Bridge, 256-bit memory operations are executed by two
17481   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17482   // memory  operation.
17483   unsigned Alignment = St->getAlignment();
17484   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17485   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17486       StVT == VT && !IsAligned) {
17487     unsigned NumElems = VT.getVectorNumElements();
17488     if (NumElems < 2)
17489       return SDValue();
17490
17491     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17492     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17493
17494     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17495     SDValue Ptr0 = St->getBasePtr();
17496     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17497
17498     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17499                                 St->getPointerInfo(), St->isVolatile(),
17500                                 St->isNonTemporal(), Alignment);
17501     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17502                                 St->getPointerInfo(), St->isVolatile(),
17503                                 St->isNonTemporal(),
17504                                 std::min(16U, Alignment));
17505     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17506   }
17507
17508   // Optimize trunc store (of multiple scalars) to shuffle and store.
17509   // First, pack all of the elements in one place. Next, store to memory
17510   // in fewer chunks.
17511   if (St->isTruncatingStore() && VT.isVector()) {
17512     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17513     unsigned NumElems = VT.getVectorNumElements();
17514     assert(StVT != VT && "Cannot truncate to the same type");
17515     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17516     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17517
17518     // From, To sizes and ElemCount must be pow of two
17519     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17520     // We are going to use the original vector elt for storing.
17521     // Accumulated smaller vector elements must be a multiple of the store size.
17522     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17523
17524     unsigned SizeRatio  = FromSz / ToSz;
17525
17526     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17527
17528     // Create a type on which we perform the shuffle
17529     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17530             StVT.getScalarType(), NumElems*SizeRatio);
17531
17532     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17533
17534     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17535     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17536     for (unsigned i = 0; i != NumElems; ++i)
17537       ShuffleVec[i] = i * SizeRatio;
17538
17539     // Can't shuffle using an illegal type.
17540     if (!TLI.isTypeLegal(WideVecVT))
17541       return SDValue();
17542
17543     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17544                                          DAG.getUNDEF(WideVecVT),
17545                                          &ShuffleVec[0]);
17546     // At this point all of the data is stored at the bottom of the
17547     // register. We now need to save it to mem.
17548
17549     // Find the largest store unit
17550     MVT StoreType = MVT::i8;
17551     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17552          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17553       MVT Tp = (MVT::SimpleValueType)tp;
17554       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17555         StoreType = Tp;
17556     }
17557
17558     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17559     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17560         (64 <= NumElems * ToSz))
17561       StoreType = MVT::f64;
17562
17563     // Bitcast the original vector into a vector of store-size units
17564     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17565             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17566     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17567     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17568     SmallVector<SDValue, 8> Chains;
17569     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17570                                         TLI.getPointerTy());
17571     SDValue Ptr = St->getBasePtr();
17572
17573     // Perform one or more big stores into memory.
17574     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17575       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17576                                    StoreType, ShuffWide,
17577                                    DAG.getIntPtrConstant(i));
17578       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17579                                 St->getPointerInfo(), St->isVolatile(),
17580                                 St->isNonTemporal(), St->getAlignment());
17581       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17582       Chains.push_back(Ch);
17583     }
17584
17585     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17586                                Chains.size());
17587   }
17588
17589   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17590   // the FP state in cases where an emms may be missing.
17591   // A preferable solution to the general problem is to figure out the right
17592   // places to insert EMMS.  This qualifies as a quick hack.
17593
17594   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17595   if (VT.getSizeInBits() != 64)
17596     return SDValue();
17597
17598   const Function *F = DAG.getMachineFunction().getFunction();
17599   bool NoImplicitFloatOps = F->getAttributes().
17600     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17601   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17602                      && Subtarget->hasSSE2();
17603   if ((VT.isVector() ||
17604        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17605       isa<LoadSDNode>(St->getValue()) &&
17606       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17607       St->getChain().hasOneUse() && !St->isVolatile()) {
17608     SDNode* LdVal = St->getValue().getNode();
17609     LoadSDNode *Ld = 0;
17610     int TokenFactorIndex = -1;
17611     SmallVector<SDValue, 8> Ops;
17612     SDNode* ChainVal = St->getChain().getNode();
17613     // Must be a store of a load.  We currently handle two cases:  the load
17614     // is a direct child, and it's under an intervening TokenFactor.  It is
17615     // possible to dig deeper under nested TokenFactors.
17616     if (ChainVal == LdVal)
17617       Ld = cast<LoadSDNode>(St->getChain());
17618     else if (St->getValue().hasOneUse() &&
17619              ChainVal->getOpcode() == ISD::TokenFactor) {
17620       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17621         if (ChainVal->getOperand(i).getNode() == LdVal) {
17622           TokenFactorIndex = i;
17623           Ld = cast<LoadSDNode>(St->getValue());
17624         } else
17625           Ops.push_back(ChainVal->getOperand(i));
17626       }
17627     }
17628
17629     if (!Ld || !ISD::isNormalLoad(Ld))
17630       return SDValue();
17631
17632     // If this is not the MMX case, i.e. we are just turning i64 load/store
17633     // into f64 load/store, avoid the transformation if there are multiple
17634     // uses of the loaded value.
17635     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17636       return SDValue();
17637
17638     SDLoc LdDL(Ld);
17639     SDLoc StDL(N);
17640     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17641     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17642     // pair instead.
17643     if (Subtarget->is64Bit() || F64IsLegal) {
17644       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17645       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17646                                   Ld->getPointerInfo(), Ld->isVolatile(),
17647                                   Ld->isNonTemporal(), Ld->isInvariant(),
17648                                   Ld->getAlignment());
17649       SDValue NewChain = NewLd.getValue(1);
17650       if (TokenFactorIndex != -1) {
17651         Ops.push_back(NewChain);
17652         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17653                                Ops.size());
17654       }
17655       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17656                           St->getPointerInfo(),
17657                           St->isVolatile(), St->isNonTemporal(),
17658                           St->getAlignment());
17659     }
17660
17661     // Otherwise, lower to two pairs of 32-bit loads / stores.
17662     SDValue LoAddr = Ld->getBasePtr();
17663     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17664                                  DAG.getConstant(4, MVT::i32));
17665
17666     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17667                                Ld->getPointerInfo(),
17668                                Ld->isVolatile(), Ld->isNonTemporal(),
17669                                Ld->isInvariant(), Ld->getAlignment());
17670     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17671                                Ld->getPointerInfo().getWithOffset(4),
17672                                Ld->isVolatile(), Ld->isNonTemporal(),
17673                                Ld->isInvariant(),
17674                                MinAlign(Ld->getAlignment(), 4));
17675
17676     SDValue NewChain = LoLd.getValue(1);
17677     if (TokenFactorIndex != -1) {
17678       Ops.push_back(LoLd);
17679       Ops.push_back(HiLd);
17680       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17681                              Ops.size());
17682     }
17683
17684     LoAddr = St->getBasePtr();
17685     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17686                          DAG.getConstant(4, MVT::i32));
17687
17688     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17689                                 St->getPointerInfo(),
17690                                 St->isVolatile(), St->isNonTemporal(),
17691                                 St->getAlignment());
17692     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17693                                 St->getPointerInfo().getWithOffset(4),
17694                                 St->isVolatile(),
17695                                 St->isNonTemporal(),
17696                                 MinAlign(St->getAlignment(), 4));
17697     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17698   }
17699   return SDValue();
17700 }
17701
17702 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17703 /// and return the operands for the horizontal operation in LHS and RHS.  A
17704 /// horizontal operation performs the binary operation on successive elements
17705 /// of its first operand, then on successive elements of its second operand,
17706 /// returning the resulting values in a vector.  For example, if
17707 ///   A = < float a0, float a1, float a2, float a3 >
17708 /// and
17709 ///   B = < float b0, float b1, float b2, float b3 >
17710 /// then the result of doing a horizontal operation on A and B is
17711 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17712 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17713 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17714 /// set to A, RHS to B, and the routine returns 'true'.
17715 /// Note that the binary operation should have the property that if one of the
17716 /// operands is UNDEF then the result is UNDEF.
17717 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17718   // Look for the following pattern: if
17719   //   A = < float a0, float a1, float a2, float a3 >
17720   //   B = < float b0, float b1, float b2, float b3 >
17721   // and
17722   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17723   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17724   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17725   // which is A horizontal-op B.
17726
17727   // At least one of the operands should be a vector shuffle.
17728   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17729       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17730     return false;
17731
17732   MVT VT = LHS.getValueType().getSimpleVT();
17733
17734   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17735          "Unsupported vector type for horizontal add/sub");
17736
17737   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17738   // operate independently on 128-bit lanes.
17739   unsigned NumElts = VT.getVectorNumElements();
17740   unsigned NumLanes = VT.getSizeInBits()/128;
17741   unsigned NumLaneElts = NumElts / NumLanes;
17742   assert((NumLaneElts % 2 == 0) &&
17743          "Vector type should have an even number of elements in each lane");
17744   unsigned HalfLaneElts = NumLaneElts/2;
17745
17746   // View LHS in the form
17747   //   LHS = VECTOR_SHUFFLE A, B, LMask
17748   // If LHS is not a shuffle then pretend it is the shuffle
17749   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17750   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17751   // type VT.
17752   SDValue A, B;
17753   SmallVector<int, 16> LMask(NumElts);
17754   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17755     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17756       A = LHS.getOperand(0);
17757     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17758       B = LHS.getOperand(1);
17759     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17760     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17761   } else {
17762     if (LHS.getOpcode() != ISD::UNDEF)
17763       A = LHS;
17764     for (unsigned i = 0; i != NumElts; ++i)
17765       LMask[i] = i;
17766   }
17767
17768   // Likewise, view RHS in the form
17769   //   RHS = VECTOR_SHUFFLE C, D, RMask
17770   SDValue C, D;
17771   SmallVector<int, 16> RMask(NumElts);
17772   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17773     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17774       C = RHS.getOperand(0);
17775     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17776       D = RHS.getOperand(1);
17777     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17778     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17779   } else {
17780     if (RHS.getOpcode() != ISD::UNDEF)
17781       C = RHS;
17782     for (unsigned i = 0; i != NumElts; ++i)
17783       RMask[i] = i;
17784   }
17785
17786   // Check that the shuffles are both shuffling the same vectors.
17787   if (!(A == C && B == D) && !(A == D && B == C))
17788     return false;
17789
17790   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17791   if (!A.getNode() && !B.getNode())
17792     return false;
17793
17794   // If A and B occur in reverse order in RHS, then "swap" them (which means
17795   // rewriting the mask).
17796   if (A != C)
17797     CommuteVectorShuffleMask(RMask, NumElts);
17798
17799   // At this point LHS and RHS are equivalent to
17800   //   LHS = VECTOR_SHUFFLE A, B, LMask
17801   //   RHS = VECTOR_SHUFFLE A, B, RMask
17802   // Check that the masks correspond to performing a horizontal operation.
17803   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
17804     for (unsigned i = 0; i != NumLaneElts; ++i) {
17805       int LIdx = LMask[i+l], RIdx = RMask[i+l];
17806
17807       // Ignore any UNDEF components.
17808       if (LIdx < 0 || RIdx < 0 ||
17809           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17810           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17811         continue;
17812
17813       // Check that successive elements are being operated on.  If not, this is
17814       // not a horizontal operation.
17815       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
17816       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
17817       if (!(LIdx == Index && RIdx == Index + 1) &&
17818           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17819         return false;
17820     }
17821   }
17822
17823   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17824   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17825   return true;
17826 }
17827
17828 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17829 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17830                                   const X86Subtarget *Subtarget) {
17831   EVT VT = N->getValueType(0);
17832   SDValue LHS = N->getOperand(0);
17833   SDValue RHS = N->getOperand(1);
17834
17835   // Try to synthesize horizontal adds from adds of shuffles.
17836   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17837        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17838       isHorizontalBinOp(LHS, RHS, true))
17839     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17840   return SDValue();
17841 }
17842
17843 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17844 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17845                                   const X86Subtarget *Subtarget) {
17846   EVT VT = N->getValueType(0);
17847   SDValue LHS = N->getOperand(0);
17848   SDValue RHS = N->getOperand(1);
17849
17850   // Try to synthesize horizontal subs from subs of shuffles.
17851   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17852        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17853       isHorizontalBinOp(LHS, RHS, false))
17854     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17855   return SDValue();
17856 }
17857
17858 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17859 /// X86ISD::FXOR nodes.
17860 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17861   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17862   // F[X]OR(0.0, x) -> x
17863   // F[X]OR(x, 0.0) -> x
17864   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17865     if (C->getValueAPF().isPosZero())
17866       return N->getOperand(1);
17867   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17868     if (C->getValueAPF().isPosZero())
17869       return N->getOperand(0);
17870   return SDValue();
17871 }
17872
17873 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17874 /// X86ISD::FMAX nodes.
17875 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17876   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17877
17878   // Only perform optimizations if UnsafeMath is used.
17879   if (!DAG.getTarget().Options.UnsafeFPMath)
17880     return SDValue();
17881
17882   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17883   // into FMINC and FMAXC, which are Commutative operations.
17884   unsigned NewOp = 0;
17885   switch (N->getOpcode()) {
17886     default: llvm_unreachable("unknown opcode");
17887     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17888     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17889   }
17890
17891   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
17892                      N->getOperand(0), N->getOperand(1));
17893 }
17894
17895 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17896 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17897   // FAND(0.0, x) -> 0.0
17898   // FAND(x, 0.0) -> 0.0
17899   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17900     if (C->getValueAPF().isPosZero())
17901       return N->getOperand(0);
17902   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17903     if (C->getValueAPF().isPosZero())
17904       return N->getOperand(1);
17905   return SDValue();
17906 }
17907
17908 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
17909 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
17910   // FANDN(x, 0.0) -> 0.0
17911   // FANDN(0.0, x) -> x
17912   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17913     if (C->getValueAPF().isPosZero())
17914       return N->getOperand(1);
17915   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17916     if (C->getValueAPF().isPosZero())
17917       return N->getOperand(1);
17918   return SDValue();
17919 }
17920
17921 static SDValue PerformBTCombine(SDNode *N,
17922                                 SelectionDAG &DAG,
17923                                 TargetLowering::DAGCombinerInfo &DCI) {
17924   // BT ignores high bits in the bit index operand.
17925   SDValue Op1 = N->getOperand(1);
17926   if (Op1.hasOneUse()) {
17927     unsigned BitWidth = Op1.getValueSizeInBits();
17928     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17929     APInt KnownZero, KnownOne;
17930     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17931                                           !DCI.isBeforeLegalizeOps());
17932     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17933     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17934         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17935       DCI.CommitTargetLoweringOpt(TLO);
17936   }
17937   return SDValue();
17938 }
17939
17940 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17941   SDValue Op = N->getOperand(0);
17942   if (Op.getOpcode() == ISD::BITCAST)
17943     Op = Op.getOperand(0);
17944   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17945   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17946       VT.getVectorElementType().getSizeInBits() ==
17947       OpVT.getVectorElementType().getSizeInBits()) {
17948     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
17949   }
17950   return SDValue();
17951 }
17952
17953 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17954                                                const X86Subtarget *Subtarget) {
17955   EVT VT = N->getValueType(0);
17956   if (!VT.isVector())
17957     return SDValue();
17958
17959   SDValue N0 = N->getOperand(0);
17960   SDValue N1 = N->getOperand(1);
17961   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17962   SDLoc dl(N);
17963
17964   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17965   // both SSE and AVX2 since there is no sign-extended shift right
17966   // operation on a vector with 64-bit elements.
17967   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17968   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17969   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17970       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17971     SDValue N00 = N0.getOperand(0);
17972
17973     // EXTLOAD has a better solution on AVX2,
17974     // it may be replaced with X86ISD::VSEXT node.
17975     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17976       if (!ISD::isNormalLoad(N00.getNode()))
17977         return SDValue();
17978
17979     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17980         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17981                                   N00, N1);
17982       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17983     }
17984   }
17985   return SDValue();
17986 }
17987
17988 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17989                                   TargetLowering::DAGCombinerInfo &DCI,
17990                                   const X86Subtarget *Subtarget) {
17991   if (!DCI.isBeforeLegalizeOps())
17992     return SDValue();
17993
17994   if (!Subtarget->hasFp256())
17995     return SDValue();
17996
17997   EVT VT = N->getValueType(0);
17998   if (VT.isVector() && VT.getSizeInBits() == 256) {
17999     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18000     if (R.getNode())
18001       return R;
18002   }
18003
18004   return SDValue();
18005 }
18006
18007 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
18008                                  const X86Subtarget* Subtarget) {
18009   SDLoc dl(N);
18010   EVT VT = N->getValueType(0);
18011
18012   // Let legalize expand this if it isn't a legal type yet.
18013   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18014     return SDValue();
18015
18016   EVT ScalarVT = VT.getScalarType();
18017   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
18018       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
18019     return SDValue();
18020
18021   SDValue A = N->getOperand(0);
18022   SDValue B = N->getOperand(1);
18023   SDValue C = N->getOperand(2);
18024
18025   bool NegA = (A.getOpcode() == ISD::FNEG);
18026   bool NegB = (B.getOpcode() == ISD::FNEG);
18027   bool NegC = (C.getOpcode() == ISD::FNEG);
18028
18029   // Negative multiplication when NegA xor NegB
18030   bool NegMul = (NegA != NegB);
18031   if (NegA)
18032     A = A.getOperand(0);
18033   if (NegB)
18034     B = B.getOperand(0);
18035   if (NegC)
18036     C = C.getOperand(0);
18037
18038   unsigned Opcode;
18039   if (!NegMul)
18040     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
18041   else
18042     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
18043
18044   return DAG.getNode(Opcode, dl, VT, A, B, C);
18045 }
18046
18047 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
18048                                   TargetLowering::DAGCombinerInfo &DCI,
18049                                   const X86Subtarget *Subtarget) {
18050   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
18051   //           (and (i32 x86isd::setcc_carry), 1)
18052   // This eliminates the zext. This transformation is necessary because
18053   // ISD::SETCC is always legalized to i8.
18054   SDLoc dl(N);
18055   SDValue N0 = N->getOperand(0);
18056   EVT VT = N->getValueType(0);
18057
18058   if (N0.getOpcode() == ISD::AND &&
18059       N0.hasOneUse() &&
18060       N0.getOperand(0).hasOneUse()) {
18061     SDValue N00 = N0.getOperand(0);
18062     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
18063       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18064       if (!C || C->getZExtValue() != 1)
18065         return SDValue();
18066       return DAG.getNode(ISD::AND, dl, VT,
18067                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
18068                                      N00.getOperand(0), N00.getOperand(1)),
18069                          DAG.getConstant(1, VT));
18070     }
18071   }
18072
18073   if (VT.is256BitVector()) {
18074     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
18075     if (R.getNode())
18076       return R;
18077   }
18078
18079   return SDValue();
18080 }
18081
18082 // Optimize x == -y --> x+y == 0
18083 //          x != -y --> x+y != 0
18084 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
18085   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
18086   SDValue LHS = N->getOperand(0);
18087   SDValue RHS = N->getOperand(1);
18088
18089   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
18090     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
18091       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
18092         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18093                                    LHS.getValueType(), RHS, LHS.getOperand(1));
18094         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18095                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18096       }
18097   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
18098     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
18099       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
18100         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
18101                                    RHS.getValueType(), LHS, RHS.getOperand(1));
18102         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
18103                             addV, DAG.getConstant(0, addV.getValueType()), CC);
18104       }
18105   return SDValue();
18106 }
18107
18108 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
18109 // as "sbb reg,reg", since it can be extended without zext and produces
18110 // an all-ones bit which is more useful than 0/1 in some cases.
18111 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
18112   return DAG.getNode(ISD::AND, DL, MVT::i8,
18113                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
18114                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
18115                      DAG.getConstant(1, MVT::i8));
18116 }
18117
18118 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
18119 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
18120                                    TargetLowering::DAGCombinerInfo &DCI,
18121                                    const X86Subtarget *Subtarget) {
18122   SDLoc DL(N);
18123   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
18124   SDValue EFLAGS = N->getOperand(1);
18125
18126   if (CC == X86::COND_A) {
18127     // Try to convert COND_A into COND_B in an attempt to facilitate
18128     // materializing "setb reg".
18129     //
18130     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
18131     // cannot take an immediate as its first operand.
18132     //
18133     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
18134         EFLAGS.getValueType().isInteger() &&
18135         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
18136       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
18137                                    EFLAGS.getNode()->getVTList(),
18138                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
18139       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
18140       return MaterializeSETB(DL, NewEFLAGS, DAG);
18141     }
18142   }
18143
18144   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
18145   // a zext and produces an all-ones bit which is more useful than 0/1 in some
18146   // cases.
18147   if (CC == X86::COND_B)
18148     return MaterializeSETB(DL, EFLAGS, DAG);
18149
18150   SDValue Flags;
18151
18152   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18153   if (Flags.getNode()) {
18154     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18155     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
18156   }
18157
18158   return SDValue();
18159 }
18160
18161 // Optimize branch condition evaluation.
18162 //
18163 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
18164                                     TargetLowering::DAGCombinerInfo &DCI,
18165                                     const X86Subtarget *Subtarget) {
18166   SDLoc DL(N);
18167   SDValue Chain = N->getOperand(0);
18168   SDValue Dest = N->getOperand(1);
18169   SDValue EFLAGS = N->getOperand(3);
18170   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
18171
18172   SDValue Flags;
18173
18174   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
18175   if (Flags.getNode()) {
18176     SDValue Cond = DAG.getConstant(CC, MVT::i8);
18177     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
18178                        Flags);
18179   }
18180
18181   return SDValue();
18182 }
18183
18184 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
18185                                         const X86TargetLowering *XTLI) {
18186   SDValue Op0 = N->getOperand(0);
18187   EVT InVT = Op0->getValueType(0);
18188
18189   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
18190   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
18191     SDLoc dl(N);
18192     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
18193     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
18194     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
18195   }
18196
18197   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
18198   // a 32-bit target where SSE doesn't support i64->FP operations.
18199   if (Op0.getOpcode() == ISD::LOAD) {
18200     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
18201     EVT VT = Ld->getValueType(0);
18202     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
18203         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
18204         !XTLI->getSubtarget()->is64Bit() &&
18205         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18206       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
18207                                           Ld->getChain(), Op0, DAG);
18208       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
18209       return FILDChain;
18210     }
18211   }
18212   return SDValue();
18213 }
18214
18215 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
18216 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
18217                                  X86TargetLowering::DAGCombinerInfo &DCI) {
18218   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
18219   // the result is either zero or one (depending on the input carry bit).
18220   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
18221   if (X86::isZeroNode(N->getOperand(0)) &&
18222       X86::isZeroNode(N->getOperand(1)) &&
18223       // We don't have a good way to replace an EFLAGS use, so only do this when
18224       // dead right now.
18225       SDValue(N, 1).use_empty()) {
18226     SDLoc DL(N);
18227     EVT VT = N->getValueType(0);
18228     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
18229     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
18230                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
18231                                            DAG.getConstant(X86::COND_B,MVT::i8),
18232                                            N->getOperand(2)),
18233                                DAG.getConstant(1, VT));
18234     return DCI.CombineTo(N, Res1, CarryOut);
18235   }
18236
18237   return SDValue();
18238 }
18239
18240 // fold (add Y, (sete  X, 0)) -> adc  0, Y
18241 //      (add Y, (setne X, 0)) -> sbb -1, Y
18242 //      (sub (sete  X, 0), Y) -> sbb  0, Y
18243 //      (sub (setne X, 0), Y) -> adc -1, Y
18244 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
18245   SDLoc DL(N);
18246
18247   // Look through ZExts.
18248   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
18249   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
18250     return SDValue();
18251
18252   SDValue SetCC = Ext.getOperand(0);
18253   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
18254     return SDValue();
18255
18256   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
18257   if (CC != X86::COND_E && CC != X86::COND_NE)
18258     return SDValue();
18259
18260   SDValue Cmp = SetCC.getOperand(1);
18261   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
18262       !X86::isZeroNode(Cmp.getOperand(1)) ||
18263       !Cmp.getOperand(0).getValueType().isInteger())
18264     return SDValue();
18265
18266   SDValue CmpOp0 = Cmp.getOperand(0);
18267   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
18268                                DAG.getConstant(1, CmpOp0.getValueType()));
18269
18270   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
18271   if (CC == X86::COND_NE)
18272     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
18273                        DL, OtherVal.getValueType(), OtherVal,
18274                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
18275   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
18276                      DL, OtherVal.getValueType(), OtherVal,
18277                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
18278 }
18279
18280 /// PerformADDCombine - Do target-specific dag combines on integer adds.
18281 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
18282                                  const X86Subtarget *Subtarget) {
18283   EVT VT = N->getValueType(0);
18284   SDValue Op0 = N->getOperand(0);
18285   SDValue Op1 = N->getOperand(1);
18286
18287   // Try to synthesize horizontal adds from adds of shuffles.
18288   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18289        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18290       isHorizontalBinOp(Op0, Op1, true))
18291     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
18292
18293   return OptimizeConditionalInDecrement(N, DAG);
18294 }
18295
18296 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
18297                                  const X86Subtarget *Subtarget) {
18298   SDValue Op0 = N->getOperand(0);
18299   SDValue Op1 = N->getOperand(1);
18300
18301   // X86 can't encode an immediate LHS of a sub. See if we can push the
18302   // negation into a preceding instruction.
18303   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
18304     // If the RHS of the sub is a XOR with one use and a constant, invert the
18305     // immediate. Then add one to the LHS of the sub so we can turn
18306     // X-Y -> X+~Y+1, saving one register.
18307     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
18308         isa<ConstantSDNode>(Op1.getOperand(1))) {
18309       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
18310       EVT VT = Op0.getValueType();
18311       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
18312                                    Op1.getOperand(0),
18313                                    DAG.getConstant(~XorC, VT));
18314       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
18315                          DAG.getConstant(C->getAPIntValue()+1, VT));
18316     }
18317   }
18318
18319   // Try to synthesize horizontal adds from adds of shuffles.
18320   EVT VT = N->getValueType(0);
18321   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
18322        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
18323       isHorizontalBinOp(Op0, Op1, true))
18324     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
18325
18326   return OptimizeConditionalInDecrement(N, DAG);
18327 }
18328
18329 /// performVZEXTCombine - Performs build vector combines
18330 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
18331                                         TargetLowering::DAGCombinerInfo &DCI,
18332                                         const X86Subtarget *Subtarget) {
18333   // (vzext (bitcast (vzext (x)) -> (vzext x)
18334   SDValue In = N->getOperand(0);
18335   while (In.getOpcode() == ISD::BITCAST)
18336     In = In.getOperand(0);
18337
18338   if (In.getOpcode() != X86ISD::VZEXT)
18339     return SDValue();
18340
18341   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
18342                      In.getOperand(0));
18343 }
18344
18345 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
18346                                              DAGCombinerInfo &DCI) const {
18347   SelectionDAG &DAG = DCI.DAG;
18348   switch (N->getOpcode()) {
18349   default: break;
18350   case ISD::EXTRACT_VECTOR_ELT:
18351     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
18352   case ISD::VSELECT:
18353   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
18354   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
18355   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
18356   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
18357   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
18358   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
18359   case ISD::SHL:
18360   case ISD::SRA:
18361   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
18362   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
18363   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
18364   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
18365   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
18366   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
18367   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
18368   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
18369   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
18370   case X86ISD::FXOR:
18371   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
18372   case X86ISD::FMIN:
18373   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
18374   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
18375   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
18376   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
18377   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
18378   case ISD::ANY_EXTEND:
18379   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
18380   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
18381   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
18382   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
18383   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
18384   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
18385   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
18386   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
18387   case X86ISD::SHUFP:       // Handle all target specific shuffles
18388   case X86ISD::PALIGNR:
18389   case X86ISD::UNPCKH:
18390   case X86ISD::UNPCKL:
18391   case X86ISD::MOVHLPS:
18392   case X86ISD::MOVLHPS:
18393   case X86ISD::PSHUFD:
18394   case X86ISD::PSHUFHW:
18395   case X86ISD::PSHUFLW:
18396   case X86ISD::MOVSS:
18397   case X86ISD::MOVSD:
18398   case X86ISD::VPERMILP:
18399   case X86ISD::VPERM2X128:
18400   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
18401   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
18402   }
18403
18404   return SDValue();
18405 }
18406
18407 /// isTypeDesirableForOp - Return true if the target has native support for
18408 /// the specified value type and it is 'desirable' to use the type for the
18409 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
18410 /// instruction encodings are longer and some i16 instructions are slow.
18411 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
18412   if (!isTypeLegal(VT))
18413     return false;
18414   if (VT != MVT::i16)
18415     return true;
18416
18417   switch (Opc) {
18418   default:
18419     return true;
18420   case ISD::LOAD:
18421   case ISD::SIGN_EXTEND:
18422   case ISD::ZERO_EXTEND:
18423   case ISD::ANY_EXTEND:
18424   case ISD::SHL:
18425   case ISD::SRL:
18426   case ISD::SUB:
18427   case ISD::ADD:
18428   case ISD::MUL:
18429   case ISD::AND:
18430   case ISD::OR:
18431   case ISD::XOR:
18432     return false;
18433   }
18434 }
18435
18436 /// IsDesirableToPromoteOp - This method query the target whether it is
18437 /// beneficial for dag combiner to promote the specified node. If true, it
18438 /// should return the desired promotion type by reference.
18439 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
18440   EVT VT = Op.getValueType();
18441   if (VT != MVT::i16)
18442     return false;
18443
18444   bool Promote = false;
18445   bool Commute = false;
18446   switch (Op.getOpcode()) {
18447   default: break;
18448   case ISD::LOAD: {
18449     LoadSDNode *LD = cast<LoadSDNode>(Op);
18450     // If the non-extending load has a single use and it's not live out, then it
18451     // might be folded.
18452     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
18453                                                      Op.hasOneUse()*/) {
18454       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18455              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
18456         // The only case where we'd want to promote LOAD (rather then it being
18457         // promoted as an operand is when it's only use is liveout.
18458         if (UI->getOpcode() != ISD::CopyToReg)
18459           return false;
18460       }
18461     }
18462     Promote = true;
18463     break;
18464   }
18465   case ISD::SIGN_EXTEND:
18466   case ISD::ZERO_EXTEND:
18467   case ISD::ANY_EXTEND:
18468     Promote = true;
18469     break;
18470   case ISD::SHL:
18471   case ISD::SRL: {
18472     SDValue N0 = Op.getOperand(0);
18473     // Look out for (store (shl (load), x)).
18474     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
18475       return false;
18476     Promote = true;
18477     break;
18478   }
18479   case ISD::ADD:
18480   case ISD::MUL:
18481   case ISD::AND:
18482   case ISD::OR:
18483   case ISD::XOR:
18484     Commute = true;
18485     // fallthrough
18486   case ISD::SUB: {
18487     SDValue N0 = Op.getOperand(0);
18488     SDValue N1 = Op.getOperand(1);
18489     if (!Commute && MayFoldLoad(N1))
18490       return false;
18491     // Avoid disabling potential load folding opportunities.
18492     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18493       return false;
18494     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18495       return false;
18496     Promote = true;
18497   }
18498   }
18499
18500   PVT = MVT::i32;
18501   return Promote;
18502 }
18503
18504 //===----------------------------------------------------------------------===//
18505 //                           X86 Inline Assembly Support
18506 //===----------------------------------------------------------------------===//
18507
18508 namespace {
18509   // Helper to match a string separated by whitespace.
18510   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18511     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18512
18513     for (unsigned i = 0, e = args.size(); i != e; ++i) {
18514       StringRef piece(*args[i]);
18515       if (!s.startswith(piece)) // Check if the piece matches.
18516         return false;
18517
18518       s = s.substr(piece.size());
18519       StringRef::size_type pos = s.find_first_not_of(" \t");
18520       if (pos == 0) // We matched a prefix.
18521         return false;
18522
18523       s = s.substr(pos);
18524     }
18525
18526     return s.empty();
18527   }
18528   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18529 }
18530
18531 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18532   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18533
18534   std::string AsmStr = IA->getAsmString();
18535
18536   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18537   if (!Ty || Ty->getBitWidth() % 16 != 0)
18538     return false;
18539
18540   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18541   SmallVector<StringRef, 4> AsmPieces;
18542   SplitString(AsmStr, AsmPieces, ";\n");
18543
18544   switch (AsmPieces.size()) {
18545   default: return false;
18546   case 1:
18547     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18548     // we will turn this bswap into something that will be lowered to logical
18549     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18550     // lower so don't worry about this.
18551     // bswap $0
18552     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18553         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18554         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18555         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18556         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18557         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18558       // No need to check constraints, nothing other than the equivalent of
18559       // "=r,0" would be valid here.
18560       return IntrinsicLowering::LowerToByteSwap(CI);
18561     }
18562
18563     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18564     if (CI->getType()->isIntegerTy(16) &&
18565         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18566         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18567          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18568       AsmPieces.clear();
18569       const std::string &ConstraintsStr = IA->getConstraintString();
18570       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18571       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18572       if (AsmPieces.size() == 4 &&
18573           AsmPieces[0] == "~{cc}" &&
18574           AsmPieces[1] == "~{dirflag}" &&
18575           AsmPieces[2] == "~{flags}" &&
18576           AsmPieces[3] == "~{fpsr}")
18577       return IntrinsicLowering::LowerToByteSwap(CI);
18578     }
18579     break;
18580   case 3:
18581     if (CI->getType()->isIntegerTy(32) &&
18582         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18583         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18584         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18585         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18586       AsmPieces.clear();
18587       const std::string &ConstraintsStr = IA->getConstraintString();
18588       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18589       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18590       if (AsmPieces.size() == 4 &&
18591           AsmPieces[0] == "~{cc}" &&
18592           AsmPieces[1] == "~{dirflag}" &&
18593           AsmPieces[2] == "~{flags}" &&
18594           AsmPieces[3] == "~{fpsr}")
18595         return IntrinsicLowering::LowerToByteSwap(CI);
18596     }
18597
18598     if (CI->getType()->isIntegerTy(64)) {
18599       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18600       if (Constraints.size() >= 2 &&
18601           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18602           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18603         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18604         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18605             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18606             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18607           return IntrinsicLowering::LowerToByteSwap(CI);
18608       }
18609     }
18610     break;
18611   }
18612   return false;
18613 }
18614
18615 /// getConstraintType - Given a constraint letter, return the type of
18616 /// constraint it is for this target.
18617 X86TargetLowering::ConstraintType
18618 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18619   if (Constraint.size() == 1) {
18620     switch (Constraint[0]) {
18621     case 'R':
18622     case 'q':
18623     case 'Q':
18624     case 'f':
18625     case 't':
18626     case 'u':
18627     case 'y':
18628     case 'x':
18629     case 'Y':
18630     case 'l':
18631       return C_RegisterClass;
18632     case 'a':
18633     case 'b':
18634     case 'c':
18635     case 'd':
18636     case 'S':
18637     case 'D':
18638     case 'A':
18639       return C_Register;
18640     case 'I':
18641     case 'J':
18642     case 'K':
18643     case 'L':
18644     case 'M':
18645     case 'N':
18646     case 'G':
18647     case 'C':
18648     case 'e':
18649     case 'Z':
18650       return C_Other;
18651     default:
18652       break;
18653     }
18654   }
18655   return TargetLowering::getConstraintType(Constraint);
18656 }
18657
18658 /// Examine constraint type and operand type and determine a weight value.
18659 /// This object must already have been set up with the operand type
18660 /// and the current alternative constraint selected.
18661 TargetLowering::ConstraintWeight
18662   X86TargetLowering::getSingleConstraintMatchWeight(
18663     AsmOperandInfo &info, const char *constraint) const {
18664   ConstraintWeight weight = CW_Invalid;
18665   Value *CallOperandVal = info.CallOperandVal;
18666     // If we don't have a value, we can't do a match,
18667     // but allow it at the lowest weight.
18668   if (CallOperandVal == NULL)
18669     return CW_Default;
18670   Type *type = CallOperandVal->getType();
18671   // Look at the constraint type.
18672   switch (*constraint) {
18673   default:
18674     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18675   case 'R':
18676   case 'q':
18677   case 'Q':
18678   case 'a':
18679   case 'b':
18680   case 'c':
18681   case 'd':
18682   case 'S':
18683   case 'D':
18684   case 'A':
18685     if (CallOperandVal->getType()->isIntegerTy())
18686       weight = CW_SpecificReg;
18687     break;
18688   case 'f':
18689   case 't':
18690   case 'u':
18691     if (type->isFloatingPointTy())
18692       weight = CW_SpecificReg;
18693     break;
18694   case 'y':
18695     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18696       weight = CW_SpecificReg;
18697     break;
18698   case 'x':
18699   case 'Y':
18700     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18701         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18702       weight = CW_Register;
18703     break;
18704   case 'I':
18705     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18706       if (C->getZExtValue() <= 31)
18707         weight = CW_Constant;
18708     }
18709     break;
18710   case 'J':
18711     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18712       if (C->getZExtValue() <= 63)
18713         weight = CW_Constant;
18714     }
18715     break;
18716   case 'K':
18717     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18718       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18719         weight = CW_Constant;
18720     }
18721     break;
18722   case 'L':
18723     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18724       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18725         weight = CW_Constant;
18726     }
18727     break;
18728   case 'M':
18729     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18730       if (C->getZExtValue() <= 3)
18731         weight = CW_Constant;
18732     }
18733     break;
18734   case 'N':
18735     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18736       if (C->getZExtValue() <= 0xff)
18737         weight = CW_Constant;
18738     }
18739     break;
18740   case 'G':
18741   case 'C':
18742     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18743       weight = CW_Constant;
18744     }
18745     break;
18746   case 'e':
18747     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18748       if ((C->getSExtValue() >= -0x80000000LL) &&
18749           (C->getSExtValue() <= 0x7fffffffLL))
18750         weight = CW_Constant;
18751     }
18752     break;
18753   case 'Z':
18754     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18755       if (C->getZExtValue() <= 0xffffffff)
18756         weight = CW_Constant;
18757     }
18758     break;
18759   }
18760   return weight;
18761 }
18762
18763 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18764 /// with another that has more specific requirements based on the type of the
18765 /// corresponding operand.
18766 const char *X86TargetLowering::
18767 LowerXConstraint(EVT ConstraintVT) const {
18768   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18769   // 'f' like normal targets.
18770   if (ConstraintVT.isFloatingPoint()) {
18771     if (Subtarget->hasSSE2())
18772       return "Y";
18773     if (Subtarget->hasSSE1())
18774       return "x";
18775   }
18776
18777   return TargetLowering::LowerXConstraint(ConstraintVT);
18778 }
18779
18780 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18781 /// vector.  If it is invalid, don't add anything to Ops.
18782 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18783                                                      std::string &Constraint,
18784                                                      std::vector<SDValue>&Ops,
18785                                                      SelectionDAG &DAG) const {
18786   SDValue Result(0, 0);
18787
18788   // Only support length 1 constraints for now.
18789   if (Constraint.length() > 1) return;
18790
18791   char ConstraintLetter = Constraint[0];
18792   switch (ConstraintLetter) {
18793   default: break;
18794   case 'I':
18795     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18796       if (C->getZExtValue() <= 31) {
18797         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18798         break;
18799       }
18800     }
18801     return;
18802   case 'J':
18803     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18804       if (C->getZExtValue() <= 63) {
18805         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18806         break;
18807       }
18808     }
18809     return;
18810   case 'K':
18811     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18812       if (isInt<8>(C->getSExtValue())) {
18813         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18814         break;
18815       }
18816     }
18817     return;
18818   case 'N':
18819     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18820       if (C->getZExtValue() <= 255) {
18821         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18822         break;
18823       }
18824     }
18825     return;
18826   case 'e': {
18827     // 32-bit signed value
18828     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18829       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18830                                            C->getSExtValue())) {
18831         // Widen to 64 bits here to get it sign extended.
18832         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18833         break;
18834       }
18835     // FIXME gcc accepts some relocatable values here too, but only in certain
18836     // memory models; it's complicated.
18837     }
18838     return;
18839   }
18840   case 'Z': {
18841     // 32-bit unsigned value
18842     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18843       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18844                                            C->getZExtValue())) {
18845         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18846         break;
18847       }
18848     }
18849     // FIXME gcc accepts some relocatable values here too, but only in certain
18850     // memory models; it's complicated.
18851     return;
18852   }
18853   case 'i': {
18854     // Literal immediates are always ok.
18855     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18856       // Widen to 64 bits here to get it sign extended.
18857       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18858       break;
18859     }
18860
18861     // In any sort of PIC mode addresses need to be computed at runtime by
18862     // adding in a register or some sort of table lookup.  These can't
18863     // be used as immediates.
18864     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18865       return;
18866
18867     // If we are in non-pic codegen mode, we allow the address of a global (with
18868     // an optional displacement) to be used with 'i'.
18869     GlobalAddressSDNode *GA = 0;
18870     int64_t Offset = 0;
18871
18872     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18873     while (1) {
18874       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18875         Offset += GA->getOffset();
18876         break;
18877       } else if (Op.getOpcode() == ISD::ADD) {
18878         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18879           Offset += C->getZExtValue();
18880           Op = Op.getOperand(0);
18881           continue;
18882         }
18883       } else if (Op.getOpcode() == ISD::SUB) {
18884         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18885           Offset += -C->getZExtValue();
18886           Op = Op.getOperand(0);
18887           continue;
18888         }
18889       }
18890
18891       // Otherwise, this isn't something we can handle, reject it.
18892       return;
18893     }
18894
18895     const GlobalValue *GV = GA->getGlobal();
18896     // If we require an extra load to get this address, as in PIC mode, we
18897     // can't accept it.
18898     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18899                                                         getTargetMachine())))
18900       return;
18901
18902     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
18903                                         GA->getValueType(0), Offset);
18904     break;
18905   }
18906   }
18907
18908   if (Result.getNode()) {
18909     Ops.push_back(Result);
18910     return;
18911   }
18912   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18913 }
18914
18915 std::pair<unsigned, const TargetRegisterClass*>
18916 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18917                                                 MVT VT) const {
18918   // First, see if this is a constraint that directly corresponds to an LLVM
18919   // register class.
18920   if (Constraint.size() == 1) {
18921     // GCC Constraint Letters
18922     switch (Constraint[0]) {
18923     default: break;
18924       // TODO: Slight differences here in allocation order and leaving
18925       // RIP in the class. Do they matter any more here than they do
18926       // in the normal allocation?
18927     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18928       if (Subtarget->is64Bit()) {
18929         if (VT == MVT::i32 || VT == MVT::f32)
18930           return std::make_pair(0U, &X86::GR32RegClass);
18931         if (VT == MVT::i16)
18932           return std::make_pair(0U, &X86::GR16RegClass);
18933         if (VT == MVT::i8 || VT == MVT::i1)
18934           return std::make_pair(0U, &X86::GR8RegClass);
18935         if (VT == MVT::i64 || VT == MVT::f64)
18936           return std::make_pair(0U, &X86::GR64RegClass);
18937         break;
18938       }
18939       // 32-bit fallthrough
18940     case 'Q':   // Q_REGS
18941       if (VT == MVT::i32 || VT == MVT::f32)
18942         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18943       if (VT == MVT::i16)
18944         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18945       if (VT == MVT::i8 || VT == MVT::i1)
18946         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18947       if (VT == MVT::i64)
18948         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18949       break;
18950     case 'r':   // GENERAL_REGS
18951     case 'l':   // INDEX_REGS
18952       if (VT == MVT::i8 || VT == MVT::i1)
18953         return std::make_pair(0U, &X86::GR8RegClass);
18954       if (VT == MVT::i16)
18955         return std::make_pair(0U, &X86::GR16RegClass);
18956       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18957         return std::make_pair(0U, &X86::GR32RegClass);
18958       return std::make_pair(0U, &X86::GR64RegClass);
18959     case 'R':   // LEGACY_REGS
18960       if (VT == MVT::i8 || VT == MVT::i1)
18961         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18962       if (VT == MVT::i16)
18963         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18964       if (VT == MVT::i32 || !Subtarget->is64Bit())
18965         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18966       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18967     case 'f':  // FP Stack registers.
18968       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18969       // value to the correct fpstack register class.
18970       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18971         return std::make_pair(0U, &X86::RFP32RegClass);
18972       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18973         return std::make_pair(0U, &X86::RFP64RegClass);
18974       return std::make_pair(0U, &X86::RFP80RegClass);
18975     case 'y':   // MMX_REGS if MMX allowed.
18976       if (!Subtarget->hasMMX()) break;
18977       return std::make_pair(0U, &X86::VR64RegClass);
18978     case 'Y':   // SSE_REGS if SSE2 allowed
18979       if (!Subtarget->hasSSE2()) break;
18980       // FALL THROUGH.
18981     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18982       if (!Subtarget->hasSSE1()) break;
18983
18984       switch (VT.SimpleTy) {
18985       default: break;
18986       // Scalar SSE types.
18987       case MVT::f32:
18988       case MVT::i32:
18989         return std::make_pair(0U, &X86::FR32RegClass);
18990       case MVT::f64:
18991       case MVT::i64:
18992         return std::make_pair(0U, &X86::FR64RegClass);
18993       // Vector types.
18994       case MVT::v16i8:
18995       case MVT::v8i16:
18996       case MVT::v4i32:
18997       case MVT::v2i64:
18998       case MVT::v4f32:
18999       case MVT::v2f64:
19000         return std::make_pair(0U, &X86::VR128RegClass);
19001       // AVX types.
19002       case MVT::v32i8:
19003       case MVT::v16i16:
19004       case MVT::v8i32:
19005       case MVT::v4i64:
19006       case MVT::v8f32:
19007       case MVT::v4f64:
19008         return std::make_pair(0U, &X86::VR256RegClass);
19009       case MVT::v8f64:
19010       case MVT::v16f32:
19011       case MVT::v16i32:
19012       case MVT::v8i64:
19013         return std::make_pair(0U, &X86::VR512RegClass);
19014       }
19015       break;
19016     }
19017   }
19018
19019   // Use the default implementation in TargetLowering to convert the register
19020   // constraint into a member of a register class.
19021   std::pair<unsigned, const TargetRegisterClass*> Res;
19022   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
19023
19024   // Not found as a standard register?
19025   if (Res.second == 0) {
19026     // Map st(0) -> st(7) -> ST0
19027     if (Constraint.size() == 7 && Constraint[0] == '{' &&
19028         tolower(Constraint[1]) == 's' &&
19029         tolower(Constraint[2]) == 't' &&
19030         Constraint[3] == '(' &&
19031         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
19032         Constraint[5] == ')' &&
19033         Constraint[6] == '}') {
19034
19035       Res.first = X86::ST0+Constraint[4]-'0';
19036       Res.second = &X86::RFP80RegClass;
19037       return Res;
19038     }
19039
19040     // GCC allows "st(0)" to be called just plain "st".
19041     if (StringRef("{st}").equals_lower(Constraint)) {
19042       Res.first = X86::ST0;
19043       Res.second = &X86::RFP80RegClass;
19044       return Res;
19045     }
19046
19047     // flags -> EFLAGS
19048     if (StringRef("{flags}").equals_lower(Constraint)) {
19049       Res.first = X86::EFLAGS;
19050       Res.second = &X86::CCRRegClass;
19051       return Res;
19052     }
19053
19054     // 'A' means EAX + EDX.
19055     if (Constraint == "A") {
19056       Res.first = X86::EAX;
19057       Res.second = &X86::GR32_ADRegClass;
19058       return Res;
19059     }
19060     return Res;
19061   }
19062
19063   // Otherwise, check to see if this is a register class of the wrong value
19064   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
19065   // turn into {ax},{dx}.
19066   if (Res.second->hasType(VT))
19067     return Res;   // Correct type already, nothing to do.
19068
19069   // All of the single-register GCC register classes map their values onto
19070   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
19071   // really want an 8-bit or 32-bit register, map to the appropriate register
19072   // class and return the appropriate register.
19073   if (Res.second == &X86::GR16RegClass) {
19074     if (VT == MVT::i8 || VT == MVT::i1) {
19075       unsigned DestReg = 0;
19076       switch (Res.first) {
19077       default: break;
19078       case X86::AX: DestReg = X86::AL; break;
19079       case X86::DX: DestReg = X86::DL; break;
19080       case X86::CX: DestReg = X86::CL; break;
19081       case X86::BX: DestReg = X86::BL; break;
19082       }
19083       if (DestReg) {
19084         Res.first = DestReg;
19085         Res.second = &X86::GR8RegClass;
19086       }
19087     } else if (VT == MVT::i32 || VT == MVT::f32) {
19088       unsigned DestReg = 0;
19089       switch (Res.first) {
19090       default: break;
19091       case X86::AX: DestReg = X86::EAX; break;
19092       case X86::DX: DestReg = X86::EDX; break;
19093       case X86::CX: DestReg = X86::ECX; break;
19094       case X86::BX: DestReg = X86::EBX; break;
19095       case X86::SI: DestReg = X86::ESI; break;
19096       case X86::DI: DestReg = X86::EDI; break;
19097       case X86::BP: DestReg = X86::EBP; break;
19098       case X86::SP: DestReg = X86::ESP; break;
19099       }
19100       if (DestReg) {
19101         Res.first = DestReg;
19102         Res.second = &X86::GR32RegClass;
19103       }
19104     } else if (VT == MVT::i64 || VT == MVT::f64) {
19105       unsigned DestReg = 0;
19106       switch (Res.first) {
19107       default: break;
19108       case X86::AX: DestReg = X86::RAX; break;
19109       case X86::DX: DestReg = X86::RDX; break;
19110       case X86::CX: DestReg = X86::RCX; break;
19111       case X86::BX: DestReg = X86::RBX; break;
19112       case X86::SI: DestReg = X86::RSI; break;
19113       case X86::DI: DestReg = X86::RDI; break;
19114       case X86::BP: DestReg = X86::RBP; break;
19115       case X86::SP: DestReg = X86::RSP; break;
19116       }
19117       if (DestReg) {
19118         Res.first = DestReg;
19119         Res.second = &X86::GR64RegClass;
19120       }
19121     }
19122   } else if (Res.second == &X86::FR32RegClass ||
19123              Res.second == &X86::FR64RegClass ||
19124              Res.second == &X86::VR128RegClass ||
19125              Res.second == &X86::VR256RegClass ||
19126              Res.second == &X86::FR32XRegClass ||
19127              Res.second == &X86::FR64XRegClass ||
19128              Res.second == &X86::VR128XRegClass ||
19129              Res.second == &X86::VR256XRegClass ||
19130              Res.second == &X86::VR512RegClass) {
19131     // Handle references to XMM physical registers that got mapped into the
19132     // wrong class.  This can happen with constraints like {xmm0} where the
19133     // target independent register mapper will just pick the first match it can
19134     // find, ignoring the required type.
19135
19136     if (VT == MVT::f32 || VT == MVT::i32)
19137       Res.second = &X86::FR32RegClass;
19138     else if (VT == MVT::f64 || VT == MVT::i64)
19139       Res.second = &X86::FR64RegClass;
19140     else if (X86::VR128RegClass.hasType(VT))
19141       Res.second = &X86::VR128RegClass;
19142     else if (X86::VR256RegClass.hasType(VT))
19143       Res.second = &X86::VR256RegClass;
19144     else if (X86::VR512RegClass.hasType(VT))
19145       Res.second = &X86::VR512RegClass;
19146   }
19147
19148   return Res;
19149 }