Convert getMemIntrinsicNode to take ArrayRef of SDValue instead of pointer and size.
[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 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.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/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalAlias.h"
39 #include "llvm/IR/GlobalVariable.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.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/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <bitset>
51 #include <cctype>
52 using namespace llvm;
53
54 #define DEBUG_TYPE "x86-isel"
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
60                        SDValue V2);
61
62 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
63                                 SelectionDAG &DAG, SDLoc dl,
64                                 unsigned vectorWidth) {
65   assert((vectorWidth == 128 || vectorWidth == 256) &&
66          "Unsupported vector width");
67   EVT VT = Vec.getValueType();
68   EVT ElVT = VT.getVectorElementType();
69   unsigned Factor = VT.getSizeInBits()/vectorWidth;
70   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
71                                   VT.getVectorNumElements()/Factor);
72
73   // Extract from UNDEF is UNDEF.
74   if (Vec.getOpcode() == ISD::UNDEF)
75     return DAG.getUNDEF(ResultVT);
76
77   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
78   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
79
80   // This is the index of the first element of the vectorWidth-bit chunk
81   // we want.
82   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
83                                * ElemsPerChunk);
84
85   // If the input is a buildvector just emit a smaller one.
86   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
87     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
88                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
89
90   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
91   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
92                                VecIdx);
93
94   return Result;
95
96 }
97 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
98 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
99 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
100 /// instructions or a simple subregister reference. Idx is an index in the
101 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
102 /// lowering EXTRACT_VECTOR_ELT operations easier.
103 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
104                                    SelectionDAG &DAG, SDLoc dl) {
105   assert((Vec.getValueType().is256BitVector() ||
106           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
107   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
108 }
109
110 /// Generate a DAG to grab 256-bits from a 512-bit vector.
111 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
112                                    SelectionDAG &DAG, SDLoc dl) {
113   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
114   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
115 }
116
117 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
118                                unsigned IdxVal, SelectionDAG &DAG,
119                                SDLoc dl, unsigned vectorWidth) {
120   assert((vectorWidth == 128 || vectorWidth == 256) &&
121          "Unsupported vector width");
122   // Inserting UNDEF is Result
123   if (Vec.getOpcode() == ISD::UNDEF)
124     return Result;
125   EVT VT = Vec.getValueType();
126   EVT ElVT = VT.getVectorElementType();
127   EVT ResultVT = Result.getValueType();
128
129   // Insert the relevant vectorWidth bits.
130   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
131
132   // This is the index of the first element of the vectorWidth-bit chunk
133   // we want.
134   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
135                                * ElemsPerChunk);
136
137   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
138   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
139                      VecIdx);
140 }
141 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
142 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
143 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
144 /// simple superregister reference.  Idx is an index in the 128 bits
145 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
146 /// lowering INSERT_VECTOR_ELT operations easier.
147 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
148                                   unsigned IdxVal, SelectionDAG &DAG,
149                                   SDLoc dl) {
150   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
151   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
152 }
153
154 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
155                                   unsigned IdxVal, SelectionDAG &DAG,
156                                   SDLoc dl) {
157   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
158   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
159 }
160
161 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
162 /// instructions. This is used because creating CONCAT_VECTOR nodes of
163 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
164 /// large BUILD_VECTORS.
165 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
166                                    unsigned NumElems, SelectionDAG &DAG,
167                                    SDLoc dl) {
168   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
169   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
170 }
171
172 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
173                                    unsigned NumElems, SelectionDAG &DAG,
174                                    SDLoc dl) {
175   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
176   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
177 }
178
179 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
180   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
181   bool is64Bit = Subtarget->is64Bit();
182
183   if (Subtarget->isTargetMacho()) {
184     if (is64Bit)
185       return new X86_64MachoTargetObjectFile();
186     return new TargetLoweringObjectFileMachO();
187   }
188
189   if (Subtarget->isTargetLinux())
190     return new X86LinuxTargetObjectFile();
191   if (Subtarget->isTargetELF())
192     return new TargetLoweringObjectFileELF();
193   if (Subtarget->isTargetKnownWindowsMSVC())
194     return new X86WindowsTargetObjectFile();
195   if (Subtarget->isTargetCOFF())
196     return new TargetLoweringObjectFileCOFF();
197   llvm_unreachable("unknown subtarget type");
198 }
199
200 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
201   : TargetLowering(TM, createTLOF(TM)) {
202   Subtarget = &TM.getSubtarget<X86Subtarget>();
203   X86ScalarSSEf64 = Subtarget->hasSSE2();
204   X86ScalarSSEf32 = Subtarget->hasSSE1();
205   TD = getDataLayout();
206
207   resetOperationActions();
208 }
209
210 void X86TargetLowering::resetOperationActions() {
211   const TargetMachine &TM = getTargetMachine();
212   static bool FirstTimeThrough = true;
213
214   // If none of the target options have changed, then we don't need to reset the
215   // operation actions.
216   if (!FirstTimeThrough && TO == TM.Options) return;
217
218   if (!FirstTimeThrough) {
219     // Reinitialize the actions.
220     initActions();
221     FirstTimeThrough = false;
222   }
223
224   TO = TM.Options;
225
226   // Set up the TargetLowering object.
227   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
228
229   // X86 is weird, it always uses i8 for shift amounts and setcc results.
230   setBooleanContents(ZeroOrOneBooleanContent);
231   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
232   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
233
234   // For 64-bit since we have so many registers use the ILP scheduler, for
235   // 32-bit code use the register pressure specific scheduling.
236   // For Atom, always use ILP scheduling.
237   if (Subtarget->isAtom())
238     setSchedulingPreference(Sched::ILP);
239   else if (Subtarget->is64Bit())
240     setSchedulingPreference(Sched::ILP);
241   else
242     setSchedulingPreference(Sched::RegPressure);
243   const X86RegisterInfo *RegInfo =
244     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
245   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
246
247   // Bypass expensive divides on Atom when compiling with O2
248   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
249     addBypassSlowDiv(32, 8);
250     if (Subtarget->is64Bit())
251       addBypassSlowDiv(64, 16);
252   }
253
254   if (Subtarget->isTargetKnownWindowsMSVC()) {
255     // Setup Windows compiler runtime calls.
256     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
257     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
258     setLibcallName(RTLIB::SREM_I64, "_allrem");
259     setLibcallName(RTLIB::UREM_I64, "_aullrem");
260     setLibcallName(RTLIB::MUL_I64, "_allmul");
261     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
266
267     // The _ftol2 runtime function has an unusual calling conv, which
268     // is modeled by a special pseudo-instruction.
269     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
270     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
271     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
272     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
273   }
274
275   if (Subtarget->isTargetDarwin()) {
276     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
277     setUseUnderscoreSetJmp(false);
278     setUseUnderscoreLongJmp(false);
279   } else if (Subtarget->isTargetWindowsGNU()) {
280     // MS runtime is weird: it exports _setjmp, but longjmp!
281     setUseUnderscoreSetJmp(true);
282     setUseUnderscoreLongJmp(false);
283   } else {
284     setUseUnderscoreSetJmp(true);
285     setUseUnderscoreLongJmp(true);
286   }
287
288   // Set up the register classes.
289   addRegisterClass(MVT::i8, &X86::GR8RegClass);
290   addRegisterClass(MVT::i16, &X86::GR16RegClass);
291   addRegisterClass(MVT::i32, &X86::GR32RegClass);
292   if (Subtarget->is64Bit())
293     addRegisterClass(MVT::i64, &X86::GR64RegClass);
294
295   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
296
297   // We don't accept any truncstore of integer registers.
298   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
300   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
301   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
302   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
303   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
304
305   // SETOEQ and SETUNE require checking two conditions.
306   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
307   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
308   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
312
313   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
314   // operation.
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
318
319   if (Subtarget->is64Bit()) {
320     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
321     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
322   } else if (!TM.Options.UseSoftFloat) {
323     // We have an algorithm for SSE2->double, and we turn this into a
324     // 64-bit FILD followed by conditional FADD for other targets.
325     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
326     // We have an algorithm for SSE2, and we turn this into a 64-bit
327     // FILD for other targets.
328     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
329   }
330
331   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
332   // this operation.
333   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
334   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
335
336   if (!TM.Options.UseSoftFloat) {
337     // SSE has no i16 to fp conversion, only i32
338     if (X86ScalarSSEf32) {
339       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
340       // f32 and f64 cases are Legal, f80 case is not
341       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
342     } else {
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
344       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
345     }
346   } else {
347     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
348     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
349   }
350
351   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
352   // are Legal, f80 is custom lowered.
353   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
354   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
355
356   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
357   // this operation.
358   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
359   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
360
361   if (X86ScalarSSEf32) {
362     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
363     // f32 and f64 cases are Legal, f80 case is not
364     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
365   } else {
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
367     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
368   }
369
370   // Handle FP_TO_UINT by promoting the destination to a larger signed
371   // conversion.
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
375
376   if (Subtarget->is64Bit()) {
377     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
378     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
379   } else if (!TM.Options.UseSoftFloat) {
380     // Since AVX is a superset of SSE3, only check for SSE here.
381     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
382       // Expand FP_TO_UINT into a select.
383       // FIXME: We would like to use a Custom expander here eventually to do
384       // the optimal thing for SSE vs. the default expansion in the legalizer.
385       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
386     else
387       // With SSE3 we can use fisttpll to convert to a signed i64; without
388       // SSE, we're stuck with a fistpll.
389       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
390   }
391
392   if (isTargetFTOL()) {
393     // Use the _ftol2 runtime function, which has a pseudo-instruction
394     // to handle its weird calling convention.
395     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
396   }
397
398   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
399   if (!X86ScalarSSEf64) {
400     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
401     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
402     if (Subtarget->is64Bit()) {
403       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
404       // Without SSE, i64->f64 goes through memory.
405       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
406     }
407   }
408
409   // Scalar integer divide and remainder are lowered to use operations that
410   // produce two results, to match the available instructions. This exposes
411   // the two-result form to trivial CSE, which is able to combine x/y and x%y
412   // into a single instruction.
413   //
414   // Scalar integer multiply-high is also lowered to use two-result
415   // operations, to match the available instructions. However, plain multiply
416   // (low) operations are left as Legal, as there are single-result
417   // instructions for this in x86. Using the two-result multiply instructions
418   // when both high and low results are needed must be arranged by dagcombine.
419   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
420     MVT VT = IntVTs[i];
421     setOperationAction(ISD::MULHS, VT, Expand);
422     setOperationAction(ISD::MULHU, VT, Expand);
423     setOperationAction(ISD::SDIV, VT, Expand);
424     setOperationAction(ISD::UDIV, VT, Expand);
425     setOperationAction(ISD::SREM, VT, Expand);
426     setOperationAction(ISD::UREM, VT, Expand);
427
428     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
429     setOperationAction(ISD::ADDC, VT, Custom);
430     setOperationAction(ISD::ADDE, VT, Custom);
431     setOperationAction(ISD::SUBC, VT, Custom);
432     setOperationAction(ISD::SUBE, VT, Custom);
433   }
434
435   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
436   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
437   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
444   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
445   if (Subtarget->is64Bit())
446     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
447   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
448   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
449   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
450   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
451   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
452   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
453   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
454   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
455
456   // Promote the i8 variants and force them on up to i32 which has a shorter
457   // encoding.
458   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
459   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
460   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
461   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
462   if (Subtarget->hasBMI()) {
463     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
464     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
465     if (Subtarget->is64Bit())
466       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
467   } else {
468     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
469     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
470     if (Subtarget->is64Bit())
471       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
472   }
473
474   if (Subtarget->hasLZCNT()) {
475     // When promoting the i8 variants, force them to i32 for a shorter
476     // encoding.
477     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
478     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
479     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
480     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
482     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
483     if (Subtarget->is64Bit())
484       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
485   } else {
486     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
487     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
488     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
491     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
492     if (Subtarget->is64Bit()) {
493       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
494       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
495     }
496   }
497
498   if (Subtarget->hasPOPCNT()) {
499     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
500   } else {
501     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
502     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
503     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
504     if (Subtarget->is64Bit())
505       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
506   }
507
508   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
509
510   if (!Subtarget->hasMOVBE())
511     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
512
513   // These should be promoted to a larger select which is supported.
514   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
515   // X86 wants to expand cmov itself.
516   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
517   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
518   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
519   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
521   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
522   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
523   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
525   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
527   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
528   if (Subtarget->is64Bit()) {
529     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
530     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
531   }
532   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
533   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
534   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
535   // support continuation, user-level threading, and etc.. As a result, no
536   // other SjLj exception interfaces are implemented and please don't build
537   // your own exception handling based on them.
538   // LLVM/Clang supports zero-cost DWARF exception handling.
539   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
540   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
541
542   // Darwin ABI issue.
543   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
544   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
545   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
546   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
547   if (Subtarget->is64Bit())
548     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
549   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
550   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
551   if (Subtarget->is64Bit()) {
552     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
553     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
554     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
555     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
556     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
557   }
558   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
559   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
560   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
561   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
562   if (Subtarget->is64Bit()) {
563     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
564     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
565     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
566   }
567
568   if (Subtarget->hasSSE1())
569     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
570
571   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
572
573   // Expand certain atomics
574   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
575     MVT VT = IntVTs[i];
576     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
577     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
578     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
579   }
580
581   if (!Subtarget->is64Bit()) {
582     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
594   }
595
596   if (Subtarget->hasCmpxchg16b()) {
597     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
598   }
599
600   // FIXME - use subtarget debug flags
601   if (!Subtarget->isTargetDarwin() &&
602       !Subtarget->isTargetELF() &&
603       !Subtarget->isTargetCygMing()) {
604     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
605   }
606
607   if (Subtarget->is64Bit()) {
608     setExceptionPointerRegister(X86::RAX);
609     setExceptionSelectorRegister(X86::RDX);
610   } else {
611     setExceptionPointerRegister(X86::EAX);
612     setExceptionSelectorRegister(X86::EDX);
613   }
614   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
615   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
616
617   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
618   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
619
620   setOperationAction(ISD::TRAP, MVT::Other, Legal);
621   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
622
623   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
624   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
625   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
626   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
627     // TargetInfo::X86_64ABIBuiltinVaList
628     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
629     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
630   } else {
631     // TargetInfo::CharPtrBuiltinVaList
632     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
633     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
634   }
635
636   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
637   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
638
639   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
640                      MVT::i64 : MVT::i32, Custom);
641
642   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
643     // f32 and f64 use SSE.
644     // Set up the FP register classes.
645     addRegisterClass(MVT::f32, &X86::FR32RegClass);
646     addRegisterClass(MVT::f64, &X86::FR64RegClass);
647
648     // Use ANDPD to simulate FABS.
649     setOperationAction(ISD::FABS , MVT::f64, Custom);
650     setOperationAction(ISD::FABS , MVT::f32, Custom);
651
652     // Use XORP to simulate FNEG.
653     setOperationAction(ISD::FNEG , MVT::f64, Custom);
654     setOperationAction(ISD::FNEG , MVT::f32, Custom);
655
656     // Use ANDPD and ORPD to simulate FCOPYSIGN.
657     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
658     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
659
660     // Lower this to FGETSIGNx86 plus an AND.
661     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
662     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
663
664     // We don't support sin/cos/fmod
665     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
666     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
667     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
668     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
669     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
670     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
671
672     // Expand FP immediates into loads from the stack, except for the special
673     // cases we handle.
674     addLegalFPImmediate(APFloat(+0.0)); // xorpd
675     addLegalFPImmediate(APFloat(+0.0f)); // xorps
676   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
677     // Use SSE for f32, x87 for f64.
678     // Set up the FP register classes.
679     addRegisterClass(MVT::f32, &X86::FR32RegClass);
680     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
681
682     // Use ANDPS to simulate FABS.
683     setOperationAction(ISD::FABS , MVT::f32, Custom);
684
685     // Use XORP to simulate FNEG.
686     setOperationAction(ISD::FNEG , MVT::f32, Custom);
687
688     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
689
690     // Use ANDPS and ORPS to simulate FCOPYSIGN.
691     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
692     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
693
694     // We don't support sin/cos/fmod
695     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
696     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
697     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
698
699     // Special cases we handle for FP constants.
700     addLegalFPImmediate(APFloat(+0.0f)); // xorps
701     addLegalFPImmediate(APFloat(+0.0)); // FLD0
702     addLegalFPImmediate(APFloat(+1.0)); // FLD1
703     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
704     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
705
706     if (!TM.Options.UnsafeFPMath) {
707       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
708       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
709       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
710     }
711   } else if (!TM.Options.UseSoftFloat) {
712     // f32 and f64 in x87.
713     // Set up the FP register classes.
714     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
715     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
716
717     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
718     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
719     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
720     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
721
722     if (!TM.Options.UnsafeFPMath) {
723       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
724       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
725       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
726       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
727       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
728       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
729     }
730     addLegalFPImmediate(APFloat(+0.0)); // FLD0
731     addLegalFPImmediate(APFloat(+1.0)); // FLD1
732     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
733     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
734     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
735     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
736     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
737     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
738   }
739
740   // We don't support FMA.
741   setOperationAction(ISD::FMA, MVT::f64, Expand);
742   setOperationAction(ISD::FMA, MVT::f32, Expand);
743
744   // Long double always uses X87.
745   if (!TM.Options.UseSoftFloat) {
746     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
747     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
748     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
749     {
750       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
751       addLegalFPImmediate(TmpFlt);  // FLD0
752       TmpFlt.changeSign();
753       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
754
755       bool ignored;
756       APFloat TmpFlt2(+1.0);
757       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
758                       &ignored);
759       addLegalFPImmediate(TmpFlt2);  // FLD1
760       TmpFlt2.changeSign();
761       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
762     }
763
764     if (!TM.Options.UnsafeFPMath) {
765       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
766       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
767       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
768     }
769
770     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
771     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
772     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
773     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
774     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
775     setOperationAction(ISD::FMA, MVT::f80, Expand);
776   }
777
778   // Always use a library call for pow.
779   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
780   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
781   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
782
783   setOperationAction(ISD::FLOG, MVT::f80, Expand);
784   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
785   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
786   setOperationAction(ISD::FEXP, MVT::f80, Expand);
787   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
788
789   // First set operation action for all vector types to either promote
790   // (for widening) or expand (for scalarization). Then we will selectively
791   // turn on ones that can be effectively codegen'd.
792   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
793            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
794     MVT VT = (MVT::SimpleValueType)i;
795     setOperationAction(ISD::ADD , VT, Expand);
796     setOperationAction(ISD::SUB , VT, Expand);
797     setOperationAction(ISD::FADD, VT, Expand);
798     setOperationAction(ISD::FNEG, VT, Expand);
799     setOperationAction(ISD::FSUB, VT, Expand);
800     setOperationAction(ISD::MUL , VT, Expand);
801     setOperationAction(ISD::FMUL, VT, Expand);
802     setOperationAction(ISD::SDIV, VT, Expand);
803     setOperationAction(ISD::UDIV, VT, Expand);
804     setOperationAction(ISD::FDIV, VT, Expand);
805     setOperationAction(ISD::SREM, VT, Expand);
806     setOperationAction(ISD::UREM, VT, Expand);
807     setOperationAction(ISD::LOAD, VT, Expand);
808     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
809     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
810     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
811     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
812     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
813     setOperationAction(ISD::FABS, VT, Expand);
814     setOperationAction(ISD::FSIN, VT, Expand);
815     setOperationAction(ISD::FSINCOS, VT, Expand);
816     setOperationAction(ISD::FCOS, VT, Expand);
817     setOperationAction(ISD::FSINCOS, VT, Expand);
818     setOperationAction(ISD::FREM, VT, Expand);
819     setOperationAction(ISD::FMA,  VT, Expand);
820     setOperationAction(ISD::FPOWI, VT, Expand);
821     setOperationAction(ISD::FSQRT, VT, Expand);
822     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
823     setOperationAction(ISD::FFLOOR, VT, Expand);
824     setOperationAction(ISD::FCEIL, VT, Expand);
825     setOperationAction(ISD::FTRUNC, VT, Expand);
826     setOperationAction(ISD::FRINT, VT, Expand);
827     setOperationAction(ISD::FNEARBYINT, VT, Expand);
828     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
829     setOperationAction(ISD::MULHS, VT, Expand);
830     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
831     setOperationAction(ISD::MULHU, 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::UMUL_LOHI,          MVT::v4i32, Custom);
944     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
945     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
946     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
947     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
948     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
949     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
950     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
951     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
954     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
955     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
956     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
957     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
958
959     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
960     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
961     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
962     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
963
964     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
965     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
968     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
969
970     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
971     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
972       MVT VT = (MVT::SimpleValueType)i;
973       // Do not attempt to custom lower non-power-of-2 vectors
974       if (!isPowerOf2_32(VT.getVectorNumElements()))
975         continue;
976       // Do not attempt to custom lower non-128-bit vectors
977       if (!VT.is128BitVector())
978         continue;
979       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
980       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
981       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
982     }
983
984     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
985     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
986     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
987     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
989     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
990
991     if (Subtarget->is64Bit()) {
992       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
993       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
994     }
995
996     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
997     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
998       MVT VT = (MVT::SimpleValueType)i;
999
1000       // Do not attempt to promote non-128-bit vectors
1001       if (!VT.is128BitVector())
1002         continue;
1003
1004       setOperationAction(ISD::AND,    VT, Promote);
1005       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1006       setOperationAction(ISD::OR,     VT, Promote);
1007       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1008       setOperationAction(ISD::XOR,    VT, Promote);
1009       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1010       setOperationAction(ISD::LOAD,   VT, Promote);
1011       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1012       setOperationAction(ISD::SELECT, VT, Promote);
1013       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1014     }
1015
1016     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1017
1018     // Custom lower v2i64 and v2f64 selects.
1019     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1020     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1021     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1022     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1023
1024     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1025     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1026
1027     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1028     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1029     // As there is no 64-bit GPR available, we need build a special custom
1030     // sequence to convert from v2i32 to v2f32.
1031     if (!Subtarget->is64Bit())
1032       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1033
1034     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1035     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1036
1037     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1038   }
1039
1040   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1041     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1042     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1043     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1044     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1045     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1046     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1047     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1048     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1049     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1050     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1051
1052     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1053     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1054     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1055     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1056     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1057     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1058     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1059     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1060     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1061     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1062
1063     // FIXME: Do we need to handle scalar-to-vector here?
1064     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1065     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
1066
1067     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1068     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1069     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1070     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1071     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1072
1073     // i8 and i16 vectors are custom , because the source register and source
1074     // source memory operand types are not the same width.  f32 vectors are
1075     // custom since the immediate controlling the insert encodes additional
1076     // information.
1077     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1078     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1079     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1080     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1081
1082     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1083     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1084     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1085     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1086
1087     // FIXME: these should be Legal but thats only for the case where
1088     // the index is constant.  For now custom expand to deal with that.
1089     if (Subtarget->is64Bit()) {
1090       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1091       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1092     }
1093   }
1094
1095   if (Subtarget->hasSSE2()) {
1096     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1097     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1098
1099     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1100     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1101
1102     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1103     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1104
1105     // In the customized shift lowering, the legal cases in AVX2 will be
1106     // recognized.
1107     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1108     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1109
1110     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1111     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1112
1113     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1114   }
1115
1116   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1117     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1118     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1119     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1120     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1121     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1122     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1123
1124     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1125     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1126     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1127
1128     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1129     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1130     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1132     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1133     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1134     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1135     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1136     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1137     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1138     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1139     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1140
1141     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1142     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1143     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1144     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1145     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1146     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1147     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1148     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1149     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1150     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1151     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1152     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1153
1154     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1155     // even though v8i16 is a legal type.
1156     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1157     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1158     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1159
1160     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1161     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1162     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1163
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::SETCC,             MVT::v32i8, Custom);
1179     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1180     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1181     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1182
1183     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1184     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1185     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1186
1187     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1188     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1189     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1190     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1191
1192     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1193     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1194     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1195     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1196     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1197     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1198     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1199     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1200     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1201     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1202     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1203     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1204
1205     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1206       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1207       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1208       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1209       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1210       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1211       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1212     }
1213
1214     if (Subtarget->hasInt256()) {
1215       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1216       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1217       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1218       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1219
1220       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1221       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1222       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1223       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1224
1225       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1226       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1227       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1228       // Don't lower v32i8 because there is no 128-bit byte mul
1229
1230       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1231       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1232       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1233       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1234
1235       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1236     } else {
1237       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1238       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1239       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1240       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1241
1242       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1243       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1244       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1245       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1246
1247       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1248       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1249       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1250       // Don't lower v32i8 because there is no 128-bit byte mul
1251     }
1252
1253     // In the customized shift lowering, the legal cases in AVX2 will be
1254     // recognized.
1255     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1256     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1257
1258     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1259     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1260
1261     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1262
1263     // Custom lower several nodes for 256-bit types.
1264     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1265              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1266       MVT VT = (MVT::SimpleValueType)i;
1267
1268       // Extract subvector is special because the value type
1269       // (result) is 128-bit but the source is 256-bit wide.
1270       if (VT.is128BitVector())
1271         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1272
1273       // Do not attempt to custom lower other non-256-bit vectors
1274       if (!VT.is256BitVector())
1275         continue;
1276
1277       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1278       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1279       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1280       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1281       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1282       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1283       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1284     }
1285
1286     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1287     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1288       MVT VT = (MVT::SimpleValueType)i;
1289
1290       // Do not attempt to promote non-256-bit vectors
1291       if (!VT.is256BitVector())
1292         continue;
1293
1294       setOperationAction(ISD::AND,    VT, Promote);
1295       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1296       setOperationAction(ISD::OR,     VT, Promote);
1297       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1298       setOperationAction(ISD::XOR,    VT, Promote);
1299       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1300       setOperationAction(ISD::LOAD,   VT, Promote);
1301       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1302       setOperationAction(ISD::SELECT, VT, Promote);
1303       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1304     }
1305   }
1306
1307   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1308     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1309     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1310     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1311     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1312
1313     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1314     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1315     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1316
1317     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1318     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1319     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1320     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1321     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1322     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1323     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1324     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1325     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1326     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1327     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1328
1329     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1330     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1331     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1332     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1333     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1334     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1335
1336     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1337     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1338     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1339     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1340     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1341     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1342     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1343     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1344
1345     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1346     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1347     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1348     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1349     if (Subtarget->is64Bit()) {
1350       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1351       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1352       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1353       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1354     }
1355     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1356     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1357     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1358     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1359     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1360     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1361     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1362     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1363     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1364     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1365
1366     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1367     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1368     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1369     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1370     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1371     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1372     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1373     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1374     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1375     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1376     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1377     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1378     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1379
1380     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1381     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1382     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1383     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1384     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1385     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1386
1387     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1388     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1389
1390     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1391
1392     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1393     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1394     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1395     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1396     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1397     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1398     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1399     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1400     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1401
1402     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1403     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1404
1405     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1406     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1407
1408     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1409
1410     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1411     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1412
1413     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1414     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1415
1416     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1417     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1418
1419     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1420     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1421     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1422     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1423     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1424     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1425
1426     // Custom lower several nodes.
1427     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1428              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1429       MVT VT = (MVT::SimpleValueType)i;
1430
1431       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1432       // Extract subvector is special because the value type
1433       // (result) is 256/128-bit but the source is 512-bit wide.
1434       if (VT.is128BitVector() || VT.is256BitVector())
1435         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1436
1437       if (VT.getVectorElementType() == MVT::i1)
1438         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1439
1440       // Do not attempt to custom lower other non-512-bit vectors
1441       if (!VT.is512BitVector())
1442         continue;
1443
1444       if ( EltSize >= 32) {
1445         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1446         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1447         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1448         setOperationAction(ISD::VSELECT,             VT, Legal);
1449         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1450         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1451         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1452       }
1453     }
1454     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1455       MVT VT = (MVT::SimpleValueType)i;
1456
1457       // Do not attempt to promote non-256-bit vectors
1458       if (!VT.is512BitVector())
1459         continue;
1460
1461       setOperationAction(ISD::SELECT, VT, Promote);
1462       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1463     }
1464   }// has  AVX-512
1465
1466   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1467   // of this type with custom code.
1468   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1469            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1470     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1471                        Custom);
1472   }
1473
1474   // We want to custom lower some of our intrinsics.
1475   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1476   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1477   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1478   if (!Subtarget->is64Bit())
1479     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1480
1481   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1482   // handle type legalization for these operations here.
1483   //
1484   // FIXME: We really should do custom legalization for addition and
1485   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1486   // than generic legalization for 64-bit multiplication-with-overflow, though.
1487   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1488     // Add/Sub/Mul with overflow operations are custom lowered.
1489     MVT VT = IntVTs[i];
1490     setOperationAction(ISD::SADDO, VT, Custom);
1491     setOperationAction(ISD::UADDO, VT, Custom);
1492     setOperationAction(ISD::SSUBO, VT, Custom);
1493     setOperationAction(ISD::USUBO, VT, Custom);
1494     setOperationAction(ISD::SMULO, VT, Custom);
1495     setOperationAction(ISD::UMULO, VT, Custom);
1496   }
1497
1498   // There are no 8-bit 3-address imul/mul instructions
1499   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1500   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1501
1502   if (!Subtarget->is64Bit()) {
1503     // These libcalls are not available in 32-bit.
1504     setLibcallName(RTLIB::SHL_I128, nullptr);
1505     setLibcallName(RTLIB::SRL_I128, nullptr);
1506     setLibcallName(RTLIB::SRA_I128, nullptr);
1507   }
1508
1509   // Combine sin / cos into one node or libcall if possible.
1510   if (Subtarget->hasSinCos()) {
1511     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1512     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1513     if (Subtarget->isTargetDarwin()) {
1514       // For MacOSX, we don't want to the normal expansion of a libcall to
1515       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1516       // traffic.
1517       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1518       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1519     }
1520   }
1521
1522   // We have target-specific dag combine patterns for the following nodes:
1523   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1524   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1525   setTargetDAGCombine(ISD::VSELECT);
1526   setTargetDAGCombine(ISD::SELECT);
1527   setTargetDAGCombine(ISD::SHL);
1528   setTargetDAGCombine(ISD::SRA);
1529   setTargetDAGCombine(ISD::SRL);
1530   setTargetDAGCombine(ISD::OR);
1531   setTargetDAGCombine(ISD::AND);
1532   setTargetDAGCombine(ISD::ADD);
1533   setTargetDAGCombine(ISD::FADD);
1534   setTargetDAGCombine(ISD::FSUB);
1535   setTargetDAGCombine(ISD::FMA);
1536   setTargetDAGCombine(ISD::SUB);
1537   setTargetDAGCombine(ISD::LOAD);
1538   setTargetDAGCombine(ISD::STORE);
1539   setTargetDAGCombine(ISD::ZERO_EXTEND);
1540   setTargetDAGCombine(ISD::ANY_EXTEND);
1541   setTargetDAGCombine(ISD::SIGN_EXTEND);
1542   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1543   setTargetDAGCombine(ISD::TRUNCATE);
1544   setTargetDAGCombine(ISD::SINT_TO_FP);
1545   setTargetDAGCombine(ISD::SETCC);
1546   if (Subtarget->is64Bit())
1547     setTargetDAGCombine(ISD::MUL);
1548   setTargetDAGCombine(ISD::XOR);
1549
1550   computeRegisterProperties();
1551
1552   // On Darwin, -Os means optimize for size without hurting performance,
1553   // do not reduce the limit.
1554   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1555   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1556   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1557   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1558   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1559   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1560   setPrefLoopAlignment(4); // 2^4 bytes.
1561
1562   // Predictable cmov don't hurt on atom because it's in-order.
1563   PredictableSelectIsExpensive = !Subtarget->isAtom();
1564
1565   setPrefFunctionAlignment(4); // 2^4 bytes.
1566 }
1567
1568 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1569   if (!VT.isVector())
1570     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1571
1572   if (Subtarget->hasAVX512())
1573     switch(VT.getVectorNumElements()) {
1574     case  8: return MVT::v8i1;
1575     case 16: return MVT::v16i1;
1576   }
1577
1578   return VT.changeVectorElementTypeToInteger();
1579 }
1580
1581 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1582 /// the desired ByVal argument alignment.
1583 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1584   if (MaxAlign == 16)
1585     return;
1586   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1587     if (VTy->getBitWidth() == 128)
1588       MaxAlign = 16;
1589   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1590     unsigned EltAlign = 0;
1591     getMaxByValAlign(ATy->getElementType(), EltAlign);
1592     if (EltAlign > MaxAlign)
1593       MaxAlign = EltAlign;
1594   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1595     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1596       unsigned EltAlign = 0;
1597       getMaxByValAlign(STy->getElementType(i), EltAlign);
1598       if (EltAlign > MaxAlign)
1599         MaxAlign = EltAlign;
1600       if (MaxAlign == 16)
1601         break;
1602     }
1603   }
1604 }
1605
1606 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1607 /// function arguments in the caller parameter area. For X86, aggregates
1608 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1609 /// are at 4-byte boundaries.
1610 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1611   if (Subtarget->is64Bit()) {
1612     // Max of 8 and alignment of type.
1613     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1614     if (TyAlign > 8)
1615       return TyAlign;
1616     return 8;
1617   }
1618
1619   unsigned Align = 4;
1620   if (Subtarget->hasSSE1())
1621     getMaxByValAlign(Ty, Align);
1622   return Align;
1623 }
1624
1625 /// getOptimalMemOpType - Returns the target specific optimal type for load
1626 /// and store operations as a result of memset, memcpy, and memmove
1627 /// lowering. If DstAlign is zero that means it's safe to destination
1628 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1629 /// means there isn't a need to check it against alignment requirement,
1630 /// probably because the source does not need to be loaded. If 'IsMemset' is
1631 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1632 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1633 /// source is constant so it does not need to be loaded.
1634 /// It returns EVT::Other if the type should be determined using generic
1635 /// target-independent logic.
1636 EVT
1637 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1638                                        unsigned DstAlign, unsigned SrcAlign,
1639                                        bool IsMemset, bool ZeroMemset,
1640                                        bool MemcpyStrSrc,
1641                                        MachineFunction &MF) const {
1642   const Function *F = MF.getFunction();
1643   if ((!IsMemset || ZeroMemset) &&
1644       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1645                                        Attribute::NoImplicitFloat)) {
1646     if (Size >= 16 &&
1647         (Subtarget->isUnalignedMemAccessFast() ||
1648          ((DstAlign == 0 || DstAlign >= 16) &&
1649           (SrcAlign == 0 || SrcAlign >= 16)))) {
1650       if (Size >= 32) {
1651         if (Subtarget->hasInt256())
1652           return MVT::v8i32;
1653         if (Subtarget->hasFp256())
1654           return MVT::v8f32;
1655       }
1656       if (Subtarget->hasSSE2())
1657         return MVT::v4i32;
1658       if (Subtarget->hasSSE1())
1659         return MVT::v4f32;
1660     } else if (!MemcpyStrSrc && Size >= 8 &&
1661                !Subtarget->is64Bit() &&
1662                Subtarget->hasSSE2()) {
1663       // Do not use f64 to lower memcpy if source is string constant. It's
1664       // better to use i32 to avoid the loads.
1665       return MVT::f64;
1666     }
1667   }
1668   if (Subtarget->is64Bit() && Size >= 8)
1669     return MVT::i64;
1670   return MVT::i32;
1671 }
1672
1673 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1674   if (VT == MVT::f32)
1675     return X86ScalarSSEf32;
1676   else if (VT == MVT::f64)
1677     return X86ScalarSSEf64;
1678   return true;
1679 }
1680
1681 bool
1682 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1683                                                  unsigned,
1684                                                  bool *Fast) const {
1685   if (Fast)
1686     *Fast = Subtarget->isUnalignedMemAccessFast();
1687   return true;
1688 }
1689
1690 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1691 /// current function.  The returned value is a member of the
1692 /// MachineJumpTableInfo::JTEntryKind enum.
1693 unsigned X86TargetLowering::getJumpTableEncoding() const {
1694   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1695   // symbol.
1696   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1697       Subtarget->isPICStyleGOT())
1698     return MachineJumpTableInfo::EK_Custom32;
1699
1700   // Otherwise, use the normal jump table encoding heuristics.
1701   return TargetLowering::getJumpTableEncoding();
1702 }
1703
1704 const MCExpr *
1705 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1706                                              const MachineBasicBlock *MBB,
1707                                              unsigned uid,MCContext &Ctx) const{
1708   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1709          Subtarget->isPICStyleGOT());
1710   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1711   // entries.
1712   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1713                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1714 }
1715
1716 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1717 /// jumptable.
1718 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1719                                                     SelectionDAG &DAG) const {
1720   if (!Subtarget->is64Bit())
1721     // This doesn't have SDLoc associated with it, but is not really the
1722     // same as a Register.
1723     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1724   return Table;
1725 }
1726
1727 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1728 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1729 /// MCExpr.
1730 const MCExpr *X86TargetLowering::
1731 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1732                              MCContext &Ctx) const {
1733   // X86-64 uses RIP relative addressing based on the jump table label.
1734   if (Subtarget->isPICStyleRIPRel())
1735     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1736
1737   // Otherwise, the reference is relative to the PIC base.
1738   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1739 }
1740
1741 // FIXME: Why this routine is here? Move to RegInfo!
1742 std::pair<const TargetRegisterClass*, uint8_t>
1743 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1744   const TargetRegisterClass *RRC = nullptr;
1745   uint8_t Cost = 1;
1746   switch (VT.SimpleTy) {
1747   default:
1748     return TargetLowering::findRepresentativeClass(VT);
1749   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1750     RRC = Subtarget->is64Bit() ?
1751       (const TargetRegisterClass*)&X86::GR64RegClass :
1752       (const TargetRegisterClass*)&X86::GR32RegClass;
1753     break;
1754   case MVT::x86mmx:
1755     RRC = &X86::VR64RegClass;
1756     break;
1757   case MVT::f32: case MVT::f64:
1758   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1759   case MVT::v4f32: case MVT::v2f64:
1760   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1761   case MVT::v4f64:
1762     RRC = &X86::VR128RegClass;
1763     break;
1764   }
1765   return std::make_pair(RRC, Cost);
1766 }
1767
1768 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1769                                                unsigned &Offset) const {
1770   if (!Subtarget->isTargetLinux())
1771     return false;
1772
1773   if (Subtarget->is64Bit()) {
1774     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1775     Offset = 0x28;
1776     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1777       AddressSpace = 256;
1778     else
1779       AddressSpace = 257;
1780   } else {
1781     // %gs:0x14 on i386
1782     Offset = 0x14;
1783     AddressSpace = 256;
1784   }
1785   return true;
1786 }
1787
1788 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1789                                             unsigned DestAS) const {
1790   assert(SrcAS != DestAS && "Expected different address spaces!");
1791
1792   return SrcAS < 256 && DestAS < 256;
1793 }
1794
1795 //===----------------------------------------------------------------------===//
1796 //               Return Value Calling Convention Implementation
1797 //===----------------------------------------------------------------------===//
1798
1799 #include "X86GenCallingConv.inc"
1800
1801 bool
1802 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1803                                   MachineFunction &MF, bool isVarArg,
1804                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1805                         LLVMContext &Context) const {
1806   SmallVector<CCValAssign, 16> RVLocs;
1807   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1808                  RVLocs, Context);
1809   return CCInfo.CheckReturn(Outs, RetCC_X86);
1810 }
1811
1812 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1813   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1814   return ScratchRegs;
1815 }
1816
1817 SDValue
1818 X86TargetLowering::LowerReturn(SDValue Chain,
1819                                CallingConv::ID CallConv, bool isVarArg,
1820                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1821                                const SmallVectorImpl<SDValue> &OutVals,
1822                                SDLoc dl, SelectionDAG &DAG) const {
1823   MachineFunction &MF = DAG.getMachineFunction();
1824   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1825
1826   SmallVector<CCValAssign, 16> RVLocs;
1827   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1828                  RVLocs, *DAG.getContext());
1829   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1830
1831   SDValue Flag;
1832   SmallVector<SDValue, 6> RetOps;
1833   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1834   // Operand #1 = Bytes To Pop
1835   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1836                    MVT::i16));
1837
1838   // Copy the result values into the output registers.
1839   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1840     CCValAssign &VA = RVLocs[i];
1841     assert(VA.isRegLoc() && "Can only return in registers!");
1842     SDValue ValToCopy = OutVals[i];
1843     EVT ValVT = ValToCopy.getValueType();
1844
1845     // Promote values to the appropriate types
1846     if (VA.getLocInfo() == CCValAssign::SExt)
1847       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1848     else if (VA.getLocInfo() == CCValAssign::ZExt)
1849       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1850     else if (VA.getLocInfo() == CCValAssign::AExt)
1851       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1852     else if (VA.getLocInfo() == CCValAssign::BCvt)
1853       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1854
1855     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1856            "Unexpected FP-extend for return value.");  
1857
1858     // If this is x86-64, and we disabled SSE, we can't return FP values,
1859     // or SSE or MMX vectors.
1860     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1861          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1862           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1863       report_fatal_error("SSE register return with SSE disabled");
1864     }
1865     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1866     // llvm-gcc has never done it right and no one has noticed, so this
1867     // should be OK for now.
1868     if (ValVT == MVT::f64 &&
1869         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1870       report_fatal_error("SSE2 register return with SSE2 disabled");
1871
1872     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1873     // the RET instruction and handled by the FP Stackifier.
1874     if (VA.getLocReg() == X86::ST0 ||
1875         VA.getLocReg() == X86::ST1) {
1876       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1877       // change the value to the FP stack register class.
1878       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1879         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1880       RetOps.push_back(ValToCopy);
1881       // Don't emit a copytoreg.
1882       continue;
1883     }
1884
1885     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1886     // which is returned in RAX / RDX.
1887     if (Subtarget->is64Bit()) {
1888       if (ValVT == MVT::x86mmx) {
1889         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1890           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1891           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1892                                   ValToCopy);
1893           // If we don't have SSE2 available, convert to v4f32 so the generated
1894           // register is legal.
1895           if (!Subtarget->hasSSE2())
1896             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1897         }
1898       }
1899     }
1900
1901     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1902     Flag = Chain.getValue(1);
1903     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1904   }
1905
1906   // The x86-64 ABIs require that for returning structs by value we copy
1907   // the sret argument into %rax/%eax (depending on ABI) for the return.
1908   // Win32 requires us to put the sret argument to %eax as well.
1909   // We saved the argument into a virtual register in the entry block,
1910   // so now we copy the value out and into %rax/%eax.
1911   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1912       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1913     MachineFunction &MF = DAG.getMachineFunction();
1914     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1915     unsigned Reg = FuncInfo->getSRetReturnReg();
1916     assert(Reg &&
1917            "SRetReturnReg should have been set in LowerFormalArguments().");
1918     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1919
1920     unsigned RetValReg
1921         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1922           X86::RAX : X86::EAX;
1923     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1924     Flag = Chain.getValue(1);
1925
1926     // RAX/EAX now acts like a return value.
1927     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1928   }
1929
1930   RetOps[0] = Chain;  // Update chain.
1931
1932   // Add the flag if we have it.
1933   if (Flag.getNode())
1934     RetOps.push_back(Flag);
1935
1936   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1937 }
1938
1939 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1940   if (N->getNumValues() != 1)
1941     return false;
1942   if (!N->hasNUsesOfValue(1, 0))
1943     return false;
1944
1945   SDValue TCChain = Chain;
1946   SDNode *Copy = *N->use_begin();
1947   if (Copy->getOpcode() == ISD::CopyToReg) {
1948     // If the copy has a glue operand, we conservatively assume it isn't safe to
1949     // perform a tail call.
1950     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1951       return false;
1952     TCChain = Copy->getOperand(0);
1953   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1954     return false;
1955
1956   bool HasRet = false;
1957   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1958        UI != UE; ++UI) {
1959     if (UI->getOpcode() != X86ISD::RET_FLAG)
1960       return false;
1961     HasRet = true;
1962   }
1963
1964   if (!HasRet)
1965     return false;
1966
1967   Chain = TCChain;
1968   return true;
1969 }
1970
1971 MVT
1972 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1973                                             ISD::NodeType ExtendKind) const {
1974   MVT ReturnMVT;
1975   // TODO: Is this also valid on 32-bit?
1976   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1977     ReturnMVT = MVT::i8;
1978   else
1979     ReturnMVT = MVT::i32;
1980
1981   MVT MinVT = getRegisterType(ReturnMVT);
1982   return VT.bitsLT(MinVT) ? MinVT : VT;
1983 }
1984
1985 /// LowerCallResult - Lower the result values of a call into the
1986 /// appropriate copies out of appropriate physical registers.
1987 ///
1988 SDValue
1989 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1990                                    CallingConv::ID CallConv, bool isVarArg,
1991                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1992                                    SDLoc dl, SelectionDAG &DAG,
1993                                    SmallVectorImpl<SDValue> &InVals) const {
1994
1995   // Assign locations to each value returned by this call.
1996   SmallVector<CCValAssign, 16> RVLocs;
1997   bool Is64Bit = Subtarget->is64Bit();
1998   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1999                  getTargetMachine(), RVLocs, *DAG.getContext());
2000   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2001
2002   // Copy all of the result registers out of their specified physreg.
2003   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2004     CCValAssign &VA = RVLocs[i];
2005     EVT CopyVT = VA.getValVT();
2006
2007     // If this is x86-64, and we disabled SSE, we can't return FP values
2008     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2009         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2010       report_fatal_error("SSE register return with SSE disabled");
2011     }
2012
2013     SDValue Val;
2014
2015     // If this is a call to a function that returns an fp value on the floating
2016     // point stack, we must guarantee the value is popped from the stack, so
2017     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2018     // if the return value is not used. We use the FpPOP_RETVAL instruction
2019     // instead.
2020     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2021       // If we prefer to use the value in xmm registers, copy it out as f80 and
2022       // use a truncate to move it from fp stack reg to xmm reg.
2023       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2024       SDValue Ops[] = { Chain, InFlag };
2025       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2026                                          MVT::Other, MVT::Glue, Ops), 1);
2027       Val = Chain.getValue(0);
2028
2029       // Round the f80 to the right size, which also moves it to the appropriate
2030       // xmm register.
2031       if (CopyVT != VA.getValVT())
2032         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2033                           // This truncation won't change the value.
2034                           DAG.getIntPtrConstant(1));
2035     } else {
2036       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2037                                  CopyVT, InFlag).getValue(1);
2038       Val = Chain.getValue(0);
2039     }
2040     InFlag = Chain.getValue(2);
2041     InVals.push_back(Val);
2042   }
2043
2044   return Chain;
2045 }
2046
2047 //===----------------------------------------------------------------------===//
2048 //                C & StdCall & Fast Calling Convention implementation
2049 //===----------------------------------------------------------------------===//
2050 //  StdCall calling convention seems to be standard for many Windows' API
2051 //  routines and around. It differs from C calling convention just a little:
2052 //  callee should clean up the stack, not caller. Symbols should be also
2053 //  decorated in some fancy way :) It doesn't support any vector arguments.
2054 //  For info on fast calling convention see Fast Calling Convention (tail call)
2055 //  implementation LowerX86_32FastCCCallTo.
2056
2057 /// CallIsStructReturn - Determines whether a call uses struct return
2058 /// semantics.
2059 enum StructReturnType {
2060   NotStructReturn,
2061   RegStructReturn,
2062   StackStructReturn
2063 };
2064 static StructReturnType
2065 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2066   if (Outs.empty())
2067     return NotStructReturn;
2068
2069   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2070   if (!Flags.isSRet())
2071     return NotStructReturn;
2072   if (Flags.isInReg())
2073     return RegStructReturn;
2074   return StackStructReturn;
2075 }
2076
2077 /// ArgsAreStructReturn - Determines whether a function uses struct
2078 /// return semantics.
2079 static StructReturnType
2080 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2081   if (Ins.empty())
2082     return NotStructReturn;
2083
2084   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2085   if (!Flags.isSRet())
2086     return NotStructReturn;
2087   if (Flags.isInReg())
2088     return RegStructReturn;
2089   return StackStructReturn;
2090 }
2091
2092 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2093 /// by "Src" to address "Dst" with size and alignment information specified by
2094 /// the specific parameter attribute. The copy will be passed as a byval
2095 /// function parameter.
2096 static SDValue
2097 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2098                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2099                           SDLoc dl) {
2100   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2101
2102   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2103                        /*isVolatile*/false, /*AlwaysInline=*/true,
2104                        MachinePointerInfo(), MachinePointerInfo());
2105 }
2106
2107 /// IsTailCallConvention - Return true if the calling convention is one that
2108 /// supports tail call optimization.
2109 static bool IsTailCallConvention(CallingConv::ID CC) {
2110   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2111           CC == CallingConv::HiPE);
2112 }
2113
2114 /// \brief Return true if the calling convention is a C calling convention.
2115 static bool IsCCallConvention(CallingConv::ID CC) {
2116   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2117           CC == CallingConv::X86_64_SysV);
2118 }
2119
2120 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2121   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2122     return false;
2123
2124   CallSite CS(CI);
2125   CallingConv::ID CalleeCC = CS.getCallingConv();
2126   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2127     return false;
2128
2129   return true;
2130 }
2131
2132 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2133 /// a tailcall target by changing its ABI.
2134 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2135                                    bool GuaranteedTailCallOpt) {
2136   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2137 }
2138
2139 SDValue
2140 X86TargetLowering::LowerMemArgument(SDValue Chain,
2141                                     CallingConv::ID CallConv,
2142                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2143                                     SDLoc dl, SelectionDAG &DAG,
2144                                     const CCValAssign &VA,
2145                                     MachineFrameInfo *MFI,
2146                                     unsigned i) const {
2147   // Create the nodes corresponding to a load from this parameter slot.
2148   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2149   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2150                               getTargetMachine().Options.GuaranteedTailCallOpt);
2151   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2152   EVT ValVT;
2153
2154   // If value is passed by pointer we have address passed instead of the value
2155   // itself.
2156   if (VA.getLocInfo() == CCValAssign::Indirect)
2157     ValVT = VA.getLocVT();
2158   else
2159     ValVT = VA.getValVT();
2160
2161   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2162   // changed with more analysis.
2163   // In case of tail call optimization mark all arguments mutable. Since they
2164   // could be overwritten by lowering of arguments in case of a tail call.
2165   if (Flags.isByVal()) {
2166     unsigned Bytes = Flags.getByValSize();
2167     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2168     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2169     return DAG.getFrameIndex(FI, getPointerTy());
2170   } else {
2171     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2172                                     VA.getLocMemOffset(), isImmutable);
2173     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2174     return DAG.getLoad(ValVT, dl, Chain, FIN,
2175                        MachinePointerInfo::getFixedStack(FI),
2176                        false, false, false, 0);
2177   }
2178 }
2179
2180 SDValue
2181 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2182                                         CallingConv::ID CallConv,
2183                                         bool isVarArg,
2184                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2185                                         SDLoc dl,
2186                                         SelectionDAG &DAG,
2187                                         SmallVectorImpl<SDValue> &InVals)
2188                                           const {
2189   MachineFunction &MF = DAG.getMachineFunction();
2190   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2191
2192   const Function* Fn = MF.getFunction();
2193   if (Fn->hasExternalLinkage() &&
2194       Subtarget->isTargetCygMing() &&
2195       Fn->getName() == "main")
2196     FuncInfo->setForceFramePointer(true);
2197
2198   MachineFrameInfo *MFI = MF.getFrameInfo();
2199   bool Is64Bit = Subtarget->is64Bit();
2200   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2201
2202   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2203          "Var args not supported with calling convention fastcc, ghc or hipe");
2204
2205   // Assign locations to all of the incoming arguments.
2206   SmallVector<CCValAssign, 16> ArgLocs;
2207   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2208                  ArgLocs, *DAG.getContext());
2209
2210   // Allocate shadow area for Win64
2211   if (IsWin64)
2212     CCInfo.AllocateStack(32, 8);
2213
2214   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2215
2216   unsigned LastVal = ~0U;
2217   SDValue ArgValue;
2218   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2219     CCValAssign &VA = ArgLocs[i];
2220     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2221     // places.
2222     assert(VA.getValNo() != LastVal &&
2223            "Don't support value assigned to multiple locs yet");
2224     (void)LastVal;
2225     LastVal = VA.getValNo();
2226
2227     if (VA.isRegLoc()) {
2228       EVT RegVT = VA.getLocVT();
2229       const TargetRegisterClass *RC;
2230       if (RegVT == MVT::i32)
2231         RC = &X86::GR32RegClass;
2232       else if (Is64Bit && RegVT == MVT::i64)
2233         RC = &X86::GR64RegClass;
2234       else if (RegVT == MVT::f32)
2235         RC = &X86::FR32RegClass;
2236       else if (RegVT == MVT::f64)
2237         RC = &X86::FR64RegClass;
2238       else if (RegVT.is512BitVector())
2239         RC = &X86::VR512RegClass;
2240       else if (RegVT.is256BitVector())
2241         RC = &X86::VR256RegClass;
2242       else if (RegVT.is128BitVector())
2243         RC = &X86::VR128RegClass;
2244       else if (RegVT == MVT::x86mmx)
2245         RC = &X86::VR64RegClass;
2246       else if (RegVT == MVT::i1)
2247         RC = &X86::VK1RegClass;
2248       else if (RegVT == MVT::v8i1)
2249         RC = &X86::VK8RegClass;
2250       else if (RegVT == MVT::v16i1)
2251         RC = &X86::VK16RegClass;
2252       else
2253         llvm_unreachable("Unknown argument type!");
2254
2255       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2256       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2257
2258       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2259       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2260       // right size.
2261       if (VA.getLocInfo() == CCValAssign::SExt)
2262         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2263                                DAG.getValueType(VA.getValVT()));
2264       else if (VA.getLocInfo() == CCValAssign::ZExt)
2265         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2266                                DAG.getValueType(VA.getValVT()));
2267       else if (VA.getLocInfo() == CCValAssign::BCvt)
2268         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2269
2270       if (VA.isExtInLoc()) {
2271         // Handle MMX values passed in XMM regs.
2272         if (RegVT.isVector())
2273           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2274         else
2275           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2276       }
2277     } else {
2278       assert(VA.isMemLoc());
2279       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2280     }
2281
2282     // If value is passed via pointer - do a load.
2283     if (VA.getLocInfo() == CCValAssign::Indirect)
2284       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2285                              MachinePointerInfo(), false, false, false, 0);
2286
2287     InVals.push_back(ArgValue);
2288   }
2289
2290   // The x86-64 ABIs require that for returning structs by value we copy
2291   // the sret argument into %rax/%eax (depending on ABI) for the return.
2292   // Win32 requires us to put the sret argument to %eax as well.
2293   // Save the argument into a virtual register so that we can access it
2294   // from the return points.
2295   if (MF.getFunction()->hasStructRetAttr() &&
2296       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2297     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2298     unsigned Reg = FuncInfo->getSRetReturnReg();
2299     if (!Reg) {
2300       MVT PtrTy = getPointerTy();
2301       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2302       FuncInfo->setSRetReturnReg(Reg);
2303     }
2304     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2305     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2306   }
2307
2308   unsigned StackSize = CCInfo.getNextStackOffset();
2309   // Align stack specially for tail calls.
2310   if (FuncIsMadeTailCallSafe(CallConv,
2311                              MF.getTarget().Options.GuaranteedTailCallOpt))
2312     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2313
2314   // If the function takes variable number of arguments, make a frame index for
2315   // the start of the first vararg value... for expansion of llvm.va_start.
2316   if (isVarArg) {
2317     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2318                     CallConv != CallingConv::X86_ThisCall)) {
2319       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2320     }
2321     if (Is64Bit) {
2322       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2323
2324       // FIXME: We should really autogenerate these arrays
2325       static const MCPhysReg GPR64ArgRegsWin64[] = {
2326         X86::RCX, X86::RDX, X86::R8,  X86::R9
2327       };
2328       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2329         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2330       };
2331       static const MCPhysReg XMMArgRegs64Bit[] = {
2332         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2333         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2334       };
2335       const MCPhysReg *GPR64ArgRegs;
2336       unsigned NumXMMRegs = 0;
2337
2338       if (IsWin64) {
2339         // The XMM registers which might contain var arg parameters are shadowed
2340         // in their paired GPR.  So we only need to save the GPR to their home
2341         // slots.
2342         TotalNumIntRegs = 4;
2343         GPR64ArgRegs = GPR64ArgRegsWin64;
2344       } else {
2345         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2346         GPR64ArgRegs = GPR64ArgRegs64Bit;
2347
2348         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2349                                                 TotalNumXMMRegs);
2350       }
2351       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2352                                                        TotalNumIntRegs);
2353
2354       bool NoImplicitFloatOps = Fn->getAttributes().
2355         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2356       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2357              "SSE register cannot be used when SSE is disabled!");
2358       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2359                NoImplicitFloatOps) &&
2360              "SSE register cannot be used when SSE is disabled!");
2361       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2362           !Subtarget->hasSSE1())
2363         // Kernel mode asks for SSE to be disabled, so don't push them
2364         // on the stack.
2365         TotalNumXMMRegs = 0;
2366
2367       if (IsWin64) {
2368         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2369         // Get to the caller-allocated home save location.  Add 8 to account
2370         // for the return address.
2371         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2372         FuncInfo->setRegSaveFrameIndex(
2373           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2374         // Fixup to set vararg frame on shadow area (4 x i64).
2375         if (NumIntRegs < 4)
2376           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2377       } else {
2378         // For X86-64, if there are vararg parameters that are passed via
2379         // registers, then we must store them to their spots on the stack so
2380         // they may be loaded by deferencing the result of va_next.
2381         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2382         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2383         FuncInfo->setRegSaveFrameIndex(
2384           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2385                                false));
2386       }
2387
2388       // Store the integer parameter registers.
2389       SmallVector<SDValue, 8> MemOps;
2390       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2391                                         getPointerTy());
2392       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2393       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2394         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2395                                   DAG.getIntPtrConstant(Offset));
2396         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2397                                      &X86::GR64RegClass);
2398         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2399         SDValue Store =
2400           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2401                        MachinePointerInfo::getFixedStack(
2402                          FuncInfo->getRegSaveFrameIndex(), Offset),
2403                        false, false, 0);
2404         MemOps.push_back(Store);
2405         Offset += 8;
2406       }
2407
2408       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2409         // Now store the XMM (fp + vector) parameter registers.
2410         SmallVector<SDValue, 11> SaveXMMOps;
2411         SaveXMMOps.push_back(Chain);
2412
2413         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2414         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2415         SaveXMMOps.push_back(ALVal);
2416
2417         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2418                                FuncInfo->getRegSaveFrameIndex()));
2419         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2420                                FuncInfo->getVarArgsFPOffset()));
2421
2422         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2423           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2424                                        &X86::VR128RegClass);
2425           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2426           SaveXMMOps.push_back(Val);
2427         }
2428         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2429                                      MVT::Other, SaveXMMOps));
2430       }
2431
2432       if (!MemOps.empty())
2433         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2434     }
2435   }
2436
2437   // Some CCs need callee pop.
2438   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2439                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2440     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2441   } else {
2442     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2443     // If this is an sret function, the return should pop the hidden pointer.
2444     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2445         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2446         argsAreStructReturn(Ins) == StackStructReturn)
2447       FuncInfo->setBytesToPopOnReturn(4);
2448   }
2449
2450   if (!Is64Bit) {
2451     // RegSaveFrameIndex is X86-64 only.
2452     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2453     if (CallConv == CallingConv::X86_FastCall ||
2454         CallConv == CallingConv::X86_ThisCall)
2455       // fastcc functions can't have varargs.
2456       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2457   }
2458
2459   FuncInfo->setArgumentStackSize(StackSize);
2460
2461   return Chain;
2462 }
2463
2464 SDValue
2465 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2466                                     SDValue StackPtr, SDValue Arg,
2467                                     SDLoc dl, SelectionDAG &DAG,
2468                                     const CCValAssign &VA,
2469                                     ISD::ArgFlagsTy Flags) const {
2470   unsigned LocMemOffset = VA.getLocMemOffset();
2471   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2472   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2473   if (Flags.isByVal())
2474     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2475
2476   return DAG.getStore(Chain, dl, Arg, PtrOff,
2477                       MachinePointerInfo::getStack(LocMemOffset),
2478                       false, false, 0);
2479 }
2480
2481 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2482 /// optimization is performed and it is required.
2483 SDValue
2484 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2485                                            SDValue &OutRetAddr, SDValue Chain,
2486                                            bool IsTailCall, bool Is64Bit,
2487                                            int FPDiff, SDLoc dl) const {
2488   // Adjust the Return address stack slot.
2489   EVT VT = getPointerTy();
2490   OutRetAddr = getReturnAddressFrameIndex(DAG);
2491
2492   // Load the "old" Return address.
2493   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2494                            false, false, false, 0);
2495   return SDValue(OutRetAddr.getNode(), 1);
2496 }
2497
2498 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2499 /// optimization is performed and it is required (FPDiff!=0).
2500 static SDValue
2501 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2502                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2503                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2504   // Store the return address to the appropriate stack slot.
2505   if (!FPDiff) return Chain;
2506   // Calculate the new stack slot for the return address.
2507   int NewReturnAddrFI =
2508     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2509                                          false);
2510   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2511   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2512                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2513                        false, false, 0);
2514   return Chain;
2515 }
2516
2517 SDValue
2518 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2519                              SmallVectorImpl<SDValue> &InVals) const {
2520   SelectionDAG &DAG                     = CLI.DAG;
2521   SDLoc &dl                             = CLI.DL;
2522   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2523   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2524   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2525   SDValue Chain                         = CLI.Chain;
2526   SDValue Callee                        = CLI.Callee;
2527   CallingConv::ID CallConv              = CLI.CallConv;
2528   bool &isTailCall                      = CLI.IsTailCall;
2529   bool isVarArg                         = CLI.IsVarArg;
2530
2531   MachineFunction &MF = DAG.getMachineFunction();
2532   bool Is64Bit        = Subtarget->is64Bit();
2533   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2534   StructReturnType SR = callIsStructReturn(Outs);
2535   bool IsSibcall      = false;
2536
2537   if (MF.getTarget().Options.DisableTailCalls)
2538     isTailCall = false;
2539
2540   if (isTailCall) {
2541     // Check if it's really possible to do a tail call.
2542     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2543                     isVarArg, SR != NotStructReturn,
2544                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2545                     Outs, OutVals, Ins, DAG);
2546
2547     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
2548       report_fatal_error("failed to perform tail call elimination on a call "
2549                          "site marked musttail");
2550
2551     // Sibcalls are automatically detected tailcalls which do not require
2552     // ABI changes.
2553     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2554       IsSibcall = true;
2555
2556     if (isTailCall)
2557       ++NumTailCalls;
2558   }
2559
2560   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2561          "Var args not supported with calling convention fastcc, ghc or hipe");
2562
2563   // Analyze operands of the call, assigning locations to each operand.
2564   SmallVector<CCValAssign, 16> ArgLocs;
2565   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2566                  ArgLocs, *DAG.getContext());
2567
2568   // Allocate shadow area for Win64
2569   if (IsWin64)
2570     CCInfo.AllocateStack(32, 8);
2571
2572   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2573
2574   // Get a count of how many bytes are to be pushed on the stack.
2575   unsigned NumBytes = CCInfo.getNextStackOffset();
2576   if (IsSibcall)
2577     // This is a sibcall. The memory operands are available in caller's
2578     // own caller's stack.
2579     NumBytes = 0;
2580   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2581            IsTailCallConvention(CallConv))
2582     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2583
2584   int FPDiff = 0;
2585   if (isTailCall && !IsSibcall) {
2586     // Lower arguments at fp - stackoffset + fpdiff.
2587     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2588     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2589
2590     FPDiff = NumBytesCallerPushed - NumBytes;
2591
2592     // Set the delta of movement of the returnaddr stackslot.
2593     // But only set if delta is greater than previous delta.
2594     if (FPDiff < X86Info->getTCReturnAddrDelta())
2595       X86Info->setTCReturnAddrDelta(FPDiff);
2596   }
2597
2598   unsigned NumBytesToPush = NumBytes;
2599   unsigned NumBytesToPop = NumBytes;
2600
2601   // If we have an inalloca argument, all stack space has already been allocated
2602   // for us and be right at the top of the stack.  We don't support multiple
2603   // arguments passed in memory when using inalloca.
2604   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2605     NumBytesToPush = 0;
2606     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2607            "an inalloca argument must be the only memory argument");
2608   }
2609
2610   if (!IsSibcall)
2611     Chain = DAG.getCALLSEQ_START(
2612         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2613
2614   SDValue RetAddrFrIdx;
2615   // Load return address for tail calls.
2616   if (isTailCall && FPDiff)
2617     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2618                                     Is64Bit, FPDiff, dl);
2619
2620   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2621   SmallVector<SDValue, 8> MemOpChains;
2622   SDValue StackPtr;
2623
2624   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2625   // of tail call optimization arguments are handle later.
2626   const X86RegisterInfo *RegInfo =
2627     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2628   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2629     // Skip inalloca arguments, they have already been written.
2630     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2631     if (Flags.isInAlloca())
2632       continue;
2633
2634     CCValAssign &VA = ArgLocs[i];
2635     EVT RegVT = VA.getLocVT();
2636     SDValue Arg = OutVals[i];
2637     bool isByVal = Flags.isByVal();
2638
2639     // Promote the value if needed.
2640     switch (VA.getLocInfo()) {
2641     default: llvm_unreachable("Unknown loc info!");
2642     case CCValAssign::Full: break;
2643     case CCValAssign::SExt:
2644       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2645       break;
2646     case CCValAssign::ZExt:
2647       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2648       break;
2649     case CCValAssign::AExt:
2650       if (RegVT.is128BitVector()) {
2651         // Special case: passing MMX values in XMM registers.
2652         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2653         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2654         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2655       } else
2656         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2657       break;
2658     case CCValAssign::BCvt:
2659       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2660       break;
2661     case CCValAssign::Indirect: {
2662       // Store the argument.
2663       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2664       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2665       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2666                            MachinePointerInfo::getFixedStack(FI),
2667                            false, false, 0);
2668       Arg = SpillSlot;
2669       break;
2670     }
2671     }
2672
2673     if (VA.isRegLoc()) {
2674       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2675       if (isVarArg && IsWin64) {
2676         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2677         // shadow reg if callee is a varargs function.
2678         unsigned ShadowReg = 0;
2679         switch (VA.getLocReg()) {
2680         case X86::XMM0: ShadowReg = X86::RCX; break;
2681         case X86::XMM1: ShadowReg = X86::RDX; break;
2682         case X86::XMM2: ShadowReg = X86::R8; break;
2683         case X86::XMM3: ShadowReg = X86::R9; break;
2684         }
2685         if (ShadowReg)
2686           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2687       }
2688     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2689       assert(VA.isMemLoc());
2690       if (!StackPtr.getNode())
2691         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2692                                       getPointerTy());
2693       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2694                                              dl, DAG, VA, Flags));
2695     }
2696   }
2697
2698   if (!MemOpChains.empty())
2699     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2700
2701   if (Subtarget->isPICStyleGOT()) {
2702     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2703     // GOT pointer.
2704     if (!isTailCall) {
2705       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2706                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2707     } else {
2708       // If we are tail calling and generating PIC/GOT style code load the
2709       // address of the callee into ECX. The value in ecx is used as target of
2710       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2711       // for tail calls on PIC/GOT architectures. Normally we would just put the
2712       // address of GOT into ebx and then call target@PLT. But for tail calls
2713       // ebx would be restored (since ebx is callee saved) before jumping to the
2714       // target@PLT.
2715
2716       // Note: The actual moving to ECX is done further down.
2717       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2718       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2719           !G->getGlobal()->hasProtectedVisibility())
2720         Callee = LowerGlobalAddress(Callee, DAG);
2721       else if (isa<ExternalSymbolSDNode>(Callee))
2722         Callee = LowerExternalSymbol(Callee, DAG);
2723     }
2724   }
2725
2726   if (Is64Bit && isVarArg && !IsWin64) {
2727     // From AMD64 ABI document:
2728     // For calls that may call functions that use varargs or stdargs
2729     // (prototype-less calls or calls to functions containing ellipsis (...) in
2730     // the declaration) %al is used as hidden argument to specify the number
2731     // of SSE registers used. The contents of %al do not need to match exactly
2732     // the number of registers, but must be an ubound on the number of SSE
2733     // registers used and is in the range 0 - 8 inclusive.
2734
2735     // Count the number of XMM registers allocated.
2736     static const MCPhysReg XMMArgRegs[] = {
2737       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2738       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2739     };
2740     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2741     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2742            && "SSE registers cannot be used when SSE is disabled");
2743
2744     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2745                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2746   }
2747
2748   // For tail calls lower the arguments to the 'real' stack slot.
2749   if (isTailCall) {
2750     // Force all the incoming stack arguments to be loaded from the stack
2751     // before any new outgoing arguments are stored to the stack, because the
2752     // outgoing stack slots may alias the incoming argument stack slots, and
2753     // the alias isn't otherwise explicit. This is slightly more conservative
2754     // than necessary, because it means that each store effectively depends
2755     // on every argument instead of just those arguments it would clobber.
2756     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2757
2758     SmallVector<SDValue, 8> MemOpChains2;
2759     SDValue FIN;
2760     int FI = 0;
2761     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2762       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2763         CCValAssign &VA = ArgLocs[i];
2764         if (VA.isRegLoc())
2765           continue;
2766         assert(VA.isMemLoc());
2767         SDValue Arg = OutVals[i];
2768         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2769         // Create frame index.
2770         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2771         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2772         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2773         FIN = DAG.getFrameIndex(FI, getPointerTy());
2774
2775         if (Flags.isByVal()) {
2776           // Copy relative to framepointer.
2777           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2778           if (!StackPtr.getNode())
2779             StackPtr = DAG.getCopyFromReg(Chain, dl,
2780                                           RegInfo->getStackRegister(),
2781                                           getPointerTy());
2782           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2783
2784           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2785                                                            ArgChain,
2786                                                            Flags, DAG, dl));
2787         } else {
2788           // Store relative to framepointer.
2789           MemOpChains2.push_back(
2790             DAG.getStore(ArgChain, dl, Arg, FIN,
2791                          MachinePointerInfo::getFixedStack(FI),
2792                          false, false, 0));
2793         }
2794       }
2795     }
2796
2797     if (!MemOpChains2.empty())
2798       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2799
2800     // Store the return address to the appropriate stack slot.
2801     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2802                                      getPointerTy(), RegInfo->getSlotSize(),
2803                                      FPDiff, dl);
2804   }
2805
2806   // Build a sequence of copy-to-reg nodes chained together with token chain
2807   // and flag operands which copy the outgoing args into registers.
2808   SDValue InFlag;
2809   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2810     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2811                              RegsToPass[i].second, InFlag);
2812     InFlag = Chain.getValue(1);
2813   }
2814
2815   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2816     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2817     // In the 64-bit large code model, we have to make all calls
2818     // through a register, since the call instruction's 32-bit
2819     // pc-relative offset may not be large enough to hold the whole
2820     // address.
2821   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2822     // If the callee is a GlobalAddress node (quite common, every direct call
2823     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2824     // it.
2825
2826     // We should use extra load for direct calls to dllimported functions in
2827     // non-JIT mode.
2828     const GlobalValue *GV = G->getGlobal();
2829     if (!GV->hasDLLImportStorageClass()) {
2830       unsigned char OpFlags = 0;
2831       bool ExtraLoad = false;
2832       unsigned WrapperKind = ISD::DELETED_NODE;
2833
2834       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2835       // external symbols most go through the PLT in PIC mode.  If the symbol
2836       // has hidden or protected visibility, or if it is static or local, then
2837       // we don't need to use the PLT - we can directly call it.
2838       if (Subtarget->isTargetELF() &&
2839           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2840           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2841         OpFlags = X86II::MO_PLT;
2842       } else if (Subtarget->isPICStyleStubAny() &&
2843                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2844                  (!Subtarget->getTargetTriple().isMacOSX() ||
2845                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2846         // PC-relative references to external symbols should go through $stub,
2847         // unless we're building with the leopard linker or later, which
2848         // automatically synthesizes these stubs.
2849         OpFlags = X86II::MO_DARWIN_STUB;
2850       } else if (Subtarget->isPICStyleRIPRel() &&
2851                  isa<Function>(GV) &&
2852                  cast<Function>(GV)->getAttributes().
2853                    hasAttribute(AttributeSet::FunctionIndex,
2854                                 Attribute::NonLazyBind)) {
2855         // If the function is marked as non-lazy, generate an indirect call
2856         // which loads from the GOT directly. This avoids runtime overhead
2857         // at the cost of eager binding (and one extra byte of encoding).
2858         OpFlags = X86II::MO_GOTPCREL;
2859         WrapperKind = X86ISD::WrapperRIP;
2860         ExtraLoad = true;
2861       }
2862
2863       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2864                                           G->getOffset(), OpFlags);
2865
2866       // Add a wrapper if needed.
2867       if (WrapperKind != ISD::DELETED_NODE)
2868         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2869       // Add extra indirection if needed.
2870       if (ExtraLoad)
2871         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2872                              MachinePointerInfo::getGOT(),
2873                              false, false, false, 0);
2874     }
2875   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2876     unsigned char OpFlags = 0;
2877
2878     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2879     // external symbols should go through the PLT.
2880     if (Subtarget->isTargetELF() &&
2881         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2882       OpFlags = X86II::MO_PLT;
2883     } else if (Subtarget->isPICStyleStubAny() &&
2884                (!Subtarget->getTargetTriple().isMacOSX() ||
2885                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2886       // PC-relative references to external symbols should go through $stub,
2887       // unless we're building with the leopard linker or later, which
2888       // automatically synthesizes these stubs.
2889       OpFlags = X86II::MO_DARWIN_STUB;
2890     }
2891
2892     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2893                                          OpFlags);
2894   }
2895
2896   // Returns a chain & a flag for retval copy to use.
2897   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2898   SmallVector<SDValue, 8> Ops;
2899
2900   if (!IsSibcall && isTailCall) {
2901     Chain = DAG.getCALLSEQ_END(Chain,
2902                                DAG.getIntPtrConstant(NumBytesToPop, true),
2903                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2904     InFlag = Chain.getValue(1);
2905   }
2906
2907   Ops.push_back(Chain);
2908   Ops.push_back(Callee);
2909
2910   if (isTailCall)
2911     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2912
2913   // Add argument registers to the end of the list so that they are known live
2914   // into the call.
2915   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2916     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2917                                   RegsToPass[i].second.getValueType()));
2918
2919   // Add a register mask operand representing the call-preserved registers.
2920   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2921   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2922   assert(Mask && "Missing call preserved mask for calling convention");
2923   Ops.push_back(DAG.getRegisterMask(Mask));
2924
2925   if (InFlag.getNode())
2926     Ops.push_back(InFlag);
2927
2928   if (isTailCall) {
2929     // We used to do:
2930     //// If this is the first return lowered for this function, add the regs
2931     //// to the liveout set for the function.
2932     // This isn't right, although it's probably harmless on x86; liveouts
2933     // should be computed from returns not tail calls.  Consider a void
2934     // function making a tail call to a function returning int.
2935     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2936   }
2937
2938   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2939   InFlag = Chain.getValue(1);
2940
2941   // Create the CALLSEQ_END node.
2942   unsigned NumBytesForCalleeToPop;
2943   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2944                        getTargetMachine().Options.GuaranteedTailCallOpt))
2945     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2946   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2947            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2948            SR == StackStructReturn)
2949     // If this is a call to a struct-return function, the callee
2950     // pops the hidden struct pointer, so we have to push it back.
2951     // This is common for Darwin/X86, Linux & Mingw32 targets.
2952     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2953     NumBytesForCalleeToPop = 4;
2954   else
2955     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2956
2957   // Returns a flag for retval copy to use.
2958   if (!IsSibcall) {
2959     Chain = DAG.getCALLSEQ_END(Chain,
2960                                DAG.getIntPtrConstant(NumBytesToPop, true),
2961                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2962                                                      true),
2963                                InFlag, dl);
2964     InFlag = Chain.getValue(1);
2965   }
2966
2967   // Handle result values, copying them out of physregs into vregs that we
2968   // return.
2969   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2970                          Ins, dl, DAG, InVals);
2971 }
2972
2973 //===----------------------------------------------------------------------===//
2974 //                Fast Calling Convention (tail call) implementation
2975 //===----------------------------------------------------------------------===//
2976
2977 //  Like std call, callee cleans arguments, convention except that ECX is
2978 //  reserved for storing the tail called function address. Only 2 registers are
2979 //  free for argument passing (inreg). Tail call optimization is performed
2980 //  provided:
2981 //                * tailcallopt is enabled
2982 //                * caller/callee are fastcc
2983 //  On X86_64 architecture with GOT-style position independent code only local
2984 //  (within module) calls are supported at the moment.
2985 //  To keep the stack aligned according to platform abi the function
2986 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2987 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2988 //  If a tail called function callee has more arguments than the caller the
2989 //  caller needs to make sure that there is room to move the RETADDR to. This is
2990 //  achieved by reserving an area the size of the argument delta right after the
2991 //  original REtADDR, but before the saved framepointer or the spilled registers
2992 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2993 //  stack layout:
2994 //    arg1
2995 //    arg2
2996 //    RETADDR
2997 //    [ new RETADDR
2998 //      move area ]
2999 //    (possible EBP)
3000 //    ESI
3001 //    EDI
3002 //    local1 ..
3003
3004 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3005 /// for a 16 byte align requirement.
3006 unsigned
3007 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3008                                                SelectionDAG& DAG) const {
3009   MachineFunction &MF = DAG.getMachineFunction();
3010   const TargetMachine &TM = MF.getTarget();
3011   const X86RegisterInfo *RegInfo =
3012     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3013   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3014   unsigned StackAlignment = TFI.getStackAlignment();
3015   uint64_t AlignMask = StackAlignment - 1;
3016   int64_t Offset = StackSize;
3017   unsigned SlotSize = RegInfo->getSlotSize();
3018   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3019     // Number smaller than 12 so just add the difference.
3020     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3021   } else {
3022     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3023     Offset = ((~AlignMask) & Offset) + StackAlignment +
3024       (StackAlignment-SlotSize);
3025   }
3026   return Offset;
3027 }
3028
3029 /// MatchingStackOffset - Return true if the given stack call argument is
3030 /// already available in the same position (relatively) of the caller's
3031 /// incoming argument stack.
3032 static
3033 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3034                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3035                          const X86InstrInfo *TII) {
3036   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3037   int FI = INT_MAX;
3038   if (Arg.getOpcode() == ISD::CopyFromReg) {
3039     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3040     if (!TargetRegisterInfo::isVirtualRegister(VR))
3041       return false;
3042     MachineInstr *Def = MRI->getVRegDef(VR);
3043     if (!Def)
3044       return false;
3045     if (!Flags.isByVal()) {
3046       if (!TII->isLoadFromStackSlot(Def, FI))
3047         return false;
3048     } else {
3049       unsigned Opcode = Def->getOpcode();
3050       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3051           Def->getOperand(1).isFI()) {
3052         FI = Def->getOperand(1).getIndex();
3053         Bytes = Flags.getByValSize();
3054       } else
3055         return false;
3056     }
3057   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3058     if (Flags.isByVal())
3059       // ByVal argument is passed in as a pointer but it's now being
3060       // dereferenced. e.g.
3061       // define @foo(%struct.X* %A) {
3062       //   tail call @bar(%struct.X* byval %A)
3063       // }
3064       return false;
3065     SDValue Ptr = Ld->getBasePtr();
3066     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3067     if (!FINode)
3068       return false;
3069     FI = FINode->getIndex();
3070   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3071     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3072     FI = FINode->getIndex();
3073     Bytes = Flags.getByValSize();
3074   } else
3075     return false;
3076
3077   assert(FI != INT_MAX);
3078   if (!MFI->isFixedObjectIndex(FI))
3079     return false;
3080   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3081 }
3082
3083 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3084 /// for tail call optimization. Targets which want to do tail call
3085 /// optimization should implement this function.
3086 bool
3087 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3088                                                      CallingConv::ID CalleeCC,
3089                                                      bool isVarArg,
3090                                                      bool isCalleeStructRet,
3091                                                      bool isCallerStructRet,
3092                                                      Type *RetTy,
3093                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3094                                     const SmallVectorImpl<SDValue> &OutVals,
3095                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3096                                                      SelectionDAG &DAG) const {
3097   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3098     return false;
3099
3100   // If -tailcallopt is specified, make fastcc functions tail-callable.
3101   const MachineFunction &MF = DAG.getMachineFunction();
3102   const Function *CallerF = MF.getFunction();
3103
3104   // If the function return type is x86_fp80 and the callee return type is not,
3105   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3106   // perform a tailcall optimization here.
3107   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3108     return false;
3109
3110   CallingConv::ID CallerCC = CallerF->getCallingConv();
3111   bool CCMatch = CallerCC == CalleeCC;
3112   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3113   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3114
3115   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3116     if (IsTailCallConvention(CalleeCC) && CCMatch)
3117       return true;
3118     return false;
3119   }
3120
3121   // Look for obvious safe cases to perform tail call optimization that do not
3122   // require ABI changes. This is what gcc calls sibcall.
3123
3124   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3125   // emit a special epilogue.
3126   const X86RegisterInfo *RegInfo =
3127     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3128   if (RegInfo->needsStackRealignment(MF))
3129     return false;
3130
3131   // Also avoid sibcall optimization if either caller or callee uses struct
3132   // return semantics.
3133   if (isCalleeStructRet || isCallerStructRet)
3134     return false;
3135
3136   // An stdcall/thiscall caller is expected to clean up its arguments; the
3137   // callee isn't going to do that.
3138   // FIXME: this is more restrictive than needed. We could produce a tailcall
3139   // when the stack adjustment matches. For example, with a thiscall that takes
3140   // only one argument.
3141   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3142                    CallerCC == CallingConv::X86_ThisCall))
3143     return false;
3144
3145   // Do not sibcall optimize vararg calls unless all arguments are passed via
3146   // registers.
3147   if (isVarArg && !Outs.empty()) {
3148
3149     // Optimizing for varargs on Win64 is unlikely to be safe without
3150     // additional testing.
3151     if (IsCalleeWin64 || IsCallerWin64)
3152       return false;
3153
3154     SmallVector<CCValAssign, 16> ArgLocs;
3155     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3156                    getTargetMachine(), ArgLocs, *DAG.getContext());
3157
3158     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3159     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3160       if (!ArgLocs[i].isRegLoc())
3161         return false;
3162   }
3163
3164   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3165   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3166   // this into a sibcall.
3167   bool Unused = false;
3168   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3169     if (!Ins[i].Used) {
3170       Unused = true;
3171       break;
3172     }
3173   }
3174   if (Unused) {
3175     SmallVector<CCValAssign, 16> RVLocs;
3176     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3177                    getTargetMachine(), RVLocs, *DAG.getContext());
3178     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3179     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3180       CCValAssign &VA = RVLocs[i];
3181       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3182         return false;
3183     }
3184   }
3185
3186   // If the calling conventions do not match, then we'd better make sure the
3187   // results are returned in the same way as what the caller expects.
3188   if (!CCMatch) {
3189     SmallVector<CCValAssign, 16> RVLocs1;
3190     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3191                     getTargetMachine(), RVLocs1, *DAG.getContext());
3192     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3193
3194     SmallVector<CCValAssign, 16> RVLocs2;
3195     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3196                     getTargetMachine(), RVLocs2, *DAG.getContext());
3197     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3198
3199     if (RVLocs1.size() != RVLocs2.size())
3200       return false;
3201     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3202       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3203         return false;
3204       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3205         return false;
3206       if (RVLocs1[i].isRegLoc()) {
3207         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3208           return false;
3209       } else {
3210         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3211           return false;
3212       }
3213     }
3214   }
3215
3216   // If the callee takes no arguments then go on to check the results of the
3217   // call.
3218   if (!Outs.empty()) {
3219     // Check if stack adjustment is needed. For now, do not do this if any
3220     // argument is passed on the stack.
3221     SmallVector<CCValAssign, 16> ArgLocs;
3222     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3223                    getTargetMachine(), ArgLocs, *DAG.getContext());
3224
3225     // Allocate shadow area for Win64
3226     if (IsCalleeWin64)
3227       CCInfo.AllocateStack(32, 8);
3228
3229     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3230     if (CCInfo.getNextStackOffset()) {
3231       MachineFunction &MF = DAG.getMachineFunction();
3232       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3233         return false;
3234
3235       // Check if the arguments are already laid out in the right way as
3236       // the caller's fixed stack objects.
3237       MachineFrameInfo *MFI = MF.getFrameInfo();
3238       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3239       const X86InstrInfo *TII =
3240         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3241       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3242         CCValAssign &VA = ArgLocs[i];
3243         SDValue Arg = OutVals[i];
3244         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3245         if (VA.getLocInfo() == CCValAssign::Indirect)
3246           return false;
3247         if (!VA.isRegLoc()) {
3248           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3249                                    MFI, MRI, TII))
3250             return false;
3251         }
3252       }
3253     }
3254
3255     // If the tailcall address may be in a register, then make sure it's
3256     // possible to register allocate for it. In 32-bit, the call address can
3257     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3258     // callee-saved registers are restored. These happen to be the same
3259     // registers used to pass 'inreg' arguments so watch out for those.
3260     if (!Subtarget->is64Bit() &&
3261         ((!isa<GlobalAddressSDNode>(Callee) &&
3262           !isa<ExternalSymbolSDNode>(Callee)) ||
3263          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3264       unsigned NumInRegs = 0;
3265       // In PIC we need an extra register to formulate the address computation
3266       // for the callee.
3267       unsigned MaxInRegs =
3268           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3269
3270       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3271         CCValAssign &VA = ArgLocs[i];
3272         if (!VA.isRegLoc())
3273           continue;
3274         unsigned Reg = VA.getLocReg();
3275         switch (Reg) {
3276         default: break;
3277         case X86::EAX: case X86::EDX: case X86::ECX:
3278           if (++NumInRegs == MaxInRegs)
3279             return false;
3280           break;
3281         }
3282       }
3283     }
3284   }
3285
3286   return true;
3287 }
3288
3289 FastISel *
3290 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3291                                   const TargetLibraryInfo *libInfo) const {
3292   return X86::createFastISel(funcInfo, libInfo);
3293 }
3294
3295 //===----------------------------------------------------------------------===//
3296 //                           Other Lowering Hooks
3297 //===----------------------------------------------------------------------===//
3298
3299 static bool MayFoldLoad(SDValue Op) {
3300   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3301 }
3302
3303 static bool MayFoldIntoStore(SDValue Op) {
3304   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3305 }
3306
3307 static bool isTargetShuffle(unsigned Opcode) {
3308   switch(Opcode) {
3309   default: return false;
3310   case X86ISD::PSHUFD:
3311   case X86ISD::PSHUFHW:
3312   case X86ISD::PSHUFLW:
3313   case X86ISD::SHUFP:
3314   case X86ISD::PALIGNR:
3315   case X86ISD::MOVLHPS:
3316   case X86ISD::MOVLHPD:
3317   case X86ISD::MOVHLPS:
3318   case X86ISD::MOVLPS:
3319   case X86ISD::MOVLPD:
3320   case X86ISD::MOVSHDUP:
3321   case X86ISD::MOVSLDUP:
3322   case X86ISD::MOVDDUP:
3323   case X86ISD::MOVSS:
3324   case X86ISD::MOVSD:
3325   case X86ISD::UNPCKL:
3326   case X86ISD::UNPCKH:
3327   case X86ISD::VPERMILP:
3328   case X86ISD::VPERM2X128:
3329   case X86ISD::VPERMI:
3330     return true;
3331   }
3332 }
3333
3334 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3335                                     SDValue V1, SelectionDAG &DAG) {
3336   switch(Opc) {
3337   default: llvm_unreachable("Unknown x86 shuffle node");
3338   case X86ISD::MOVSHDUP:
3339   case X86ISD::MOVSLDUP:
3340   case X86ISD::MOVDDUP:
3341     return DAG.getNode(Opc, dl, VT, V1);
3342   }
3343 }
3344
3345 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3346                                     SDValue V1, unsigned TargetMask,
3347                                     SelectionDAG &DAG) {
3348   switch(Opc) {
3349   default: llvm_unreachable("Unknown x86 shuffle node");
3350   case X86ISD::PSHUFD:
3351   case X86ISD::PSHUFHW:
3352   case X86ISD::PSHUFLW:
3353   case X86ISD::VPERMILP:
3354   case X86ISD::VPERMI:
3355     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3356   }
3357 }
3358
3359 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3360                                     SDValue V1, SDValue V2, unsigned TargetMask,
3361                                     SelectionDAG &DAG) {
3362   switch(Opc) {
3363   default: llvm_unreachable("Unknown x86 shuffle node");
3364   case X86ISD::PALIGNR:
3365   case X86ISD::SHUFP:
3366   case X86ISD::VPERM2X128:
3367     return DAG.getNode(Opc, dl, VT, V1, V2,
3368                        DAG.getConstant(TargetMask, MVT::i8));
3369   }
3370 }
3371
3372 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3373                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3374   switch(Opc) {
3375   default: llvm_unreachable("Unknown x86 shuffle node");
3376   case X86ISD::MOVLHPS:
3377   case X86ISD::MOVLHPD:
3378   case X86ISD::MOVHLPS:
3379   case X86ISD::MOVLPS:
3380   case X86ISD::MOVLPD:
3381   case X86ISD::MOVSS:
3382   case X86ISD::MOVSD:
3383   case X86ISD::UNPCKL:
3384   case X86ISD::UNPCKH:
3385     return DAG.getNode(Opc, dl, VT, V1, V2);
3386   }
3387 }
3388
3389 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3390   MachineFunction &MF = DAG.getMachineFunction();
3391   const X86RegisterInfo *RegInfo =
3392     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3393   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3394   int ReturnAddrIndex = FuncInfo->getRAIndex();
3395
3396   if (ReturnAddrIndex == 0) {
3397     // Set up a frame object for the return address.
3398     unsigned SlotSize = RegInfo->getSlotSize();
3399     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3400                                                            -(int64_t)SlotSize,
3401                                                            false);
3402     FuncInfo->setRAIndex(ReturnAddrIndex);
3403   }
3404
3405   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3406 }
3407
3408 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3409                                        bool hasSymbolicDisplacement) {
3410   // Offset should fit into 32 bit immediate field.
3411   if (!isInt<32>(Offset))
3412     return false;
3413
3414   // If we don't have a symbolic displacement - we don't have any extra
3415   // restrictions.
3416   if (!hasSymbolicDisplacement)
3417     return true;
3418
3419   // FIXME: Some tweaks might be needed for medium code model.
3420   if (M != CodeModel::Small && M != CodeModel::Kernel)
3421     return false;
3422
3423   // For small code model we assume that latest object is 16MB before end of 31
3424   // bits boundary. We may also accept pretty large negative constants knowing
3425   // that all objects are in the positive half of address space.
3426   if (M == CodeModel::Small && Offset < 16*1024*1024)
3427     return true;
3428
3429   // For kernel code model we know that all object resist in the negative half
3430   // of 32bits address space. We may not accept negative offsets, since they may
3431   // be just off and we may accept pretty large positive ones.
3432   if (M == CodeModel::Kernel && Offset > 0)
3433     return true;
3434
3435   return false;
3436 }
3437
3438 /// isCalleePop - Determines whether the callee is required to pop its
3439 /// own arguments. Callee pop is necessary to support tail calls.
3440 bool X86::isCalleePop(CallingConv::ID CallingConv,
3441                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3442   if (IsVarArg)
3443     return false;
3444
3445   switch (CallingConv) {
3446   default:
3447     return false;
3448   case CallingConv::X86_StdCall:
3449     return !is64Bit;
3450   case CallingConv::X86_FastCall:
3451     return !is64Bit;
3452   case CallingConv::X86_ThisCall:
3453     return !is64Bit;
3454   case CallingConv::Fast:
3455     return TailCallOpt;
3456   case CallingConv::GHC:
3457     return TailCallOpt;
3458   case CallingConv::HiPE:
3459     return TailCallOpt;
3460   }
3461 }
3462
3463 /// \brief Return true if the condition is an unsigned comparison operation.
3464 static bool isX86CCUnsigned(unsigned X86CC) {
3465   switch (X86CC) {
3466   default: llvm_unreachable("Invalid integer condition!");
3467   case X86::COND_E:     return true;
3468   case X86::COND_G:     return false;
3469   case X86::COND_GE:    return false;
3470   case X86::COND_L:     return false;
3471   case X86::COND_LE:    return false;
3472   case X86::COND_NE:    return true;
3473   case X86::COND_B:     return true;
3474   case X86::COND_A:     return true;
3475   case X86::COND_BE:    return true;
3476   case X86::COND_AE:    return true;
3477   }
3478   llvm_unreachable("covered switch fell through?!");
3479 }
3480
3481 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3482 /// specific condition code, returning the condition code and the LHS/RHS of the
3483 /// comparison to make.
3484 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3485                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3486   if (!isFP) {
3487     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3488       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3489         // X > -1   -> X == 0, jump !sign.
3490         RHS = DAG.getConstant(0, RHS.getValueType());
3491         return X86::COND_NS;
3492       }
3493       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3494         // X < 0   -> X == 0, jump on sign.
3495         return X86::COND_S;
3496       }
3497       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3498         // X < 1   -> X <= 0
3499         RHS = DAG.getConstant(0, RHS.getValueType());
3500         return X86::COND_LE;
3501       }
3502     }
3503
3504     switch (SetCCOpcode) {
3505     default: llvm_unreachable("Invalid integer condition!");
3506     case ISD::SETEQ:  return X86::COND_E;
3507     case ISD::SETGT:  return X86::COND_G;
3508     case ISD::SETGE:  return X86::COND_GE;
3509     case ISD::SETLT:  return X86::COND_L;
3510     case ISD::SETLE:  return X86::COND_LE;
3511     case ISD::SETNE:  return X86::COND_NE;
3512     case ISD::SETULT: return X86::COND_B;
3513     case ISD::SETUGT: return X86::COND_A;
3514     case ISD::SETULE: return X86::COND_BE;
3515     case ISD::SETUGE: return X86::COND_AE;
3516     }
3517   }
3518
3519   // First determine if it is required or is profitable to flip the operands.
3520
3521   // If LHS is a foldable load, but RHS is not, flip the condition.
3522   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3523       !ISD::isNON_EXTLoad(RHS.getNode())) {
3524     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3525     std::swap(LHS, RHS);
3526   }
3527
3528   switch (SetCCOpcode) {
3529   default: break;
3530   case ISD::SETOLT:
3531   case ISD::SETOLE:
3532   case ISD::SETUGT:
3533   case ISD::SETUGE:
3534     std::swap(LHS, RHS);
3535     break;
3536   }
3537
3538   // On a floating point condition, the flags are set as follows:
3539   // ZF  PF  CF   op
3540   //  0 | 0 | 0 | X > Y
3541   //  0 | 0 | 1 | X < Y
3542   //  1 | 0 | 0 | X == Y
3543   //  1 | 1 | 1 | unordered
3544   switch (SetCCOpcode) {
3545   default: llvm_unreachable("Condcode should be pre-legalized away");
3546   case ISD::SETUEQ:
3547   case ISD::SETEQ:   return X86::COND_E;
3548   case ISD::SETOLT:              // flipped
3549   case ISD::SETOGT:
3550   case ISD::SETGT:   return X86::COND_A;
3551   case ISD::SETOLE:              // flipped
3552   case ISD::SETOGE:
3553   case ISD::SETGE:   return X86::COND_AE;
3554   case ISD::SETUGT:              // flipped
3555   case ISD::SETULT:
3556   case ISD::SETLT:   return X86::COND_B;
3557   case ISD::SETUGE:              // flipped
3558   case ISD::SETULE:
3559   case ISD::SETLE:   return X86::COND_BE;
3560   case ISD::SETONE:
3561   case ISD::SETNE:   return X86::COND_NE;
3562   case ISD::SETUO:   return X86::COND_P;
3563   case ISD::SETO:    return X86::COND_NP;
3564   case ISD::SETOEQ:
3565   case ISD::SETUNE:  return X86::COND_INVALID;
3566   }
3567 }
3568
3569 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3570 /// code. Current x86 isa includes the following FP cmov instructions:
3571 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3572 static bool hasFPCMov(unsigned X86CC) {
3573   switch (X86CC) {
3574   default:
3575     return false;
3576   case X86::COND_B:
3577   case X86::COND_BE:
3578   case X86::COND_E:
3579   case X86::COND_P:
3580   case X86::COND_A:
3581   case X86::COND_AE:
3582   case X86::COND_NE:
3583   case X86::COND_NP:
3584     return true;
3585   }
3586 }
3587
3588 /// isFPImmLegal - Returns true if the target can instruction select the
3589 /// specified FP immediate natively. If false, the legalizer will
3590 /// materialize the FP immediate as a load from a constant pool.
3591 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3592   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3593     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3594       return true;
3595   }
3596   return false;
3597 }
3598
3599 /// \brief Returns true if it is beneficial to convert a load of a constant
3600 /// to just the constant itself.
3601 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3602                                                           Type *Ty) const {
3603   assert(Ty->isIntegerTy());
3604
3605   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3606   if (BitSize == 0 || BitSize > 64)
3607     return false;
3608   return true;
3609 }
3610
3611 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3612 /// the specified range (L, H].
3613 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3614   return (Val < 0) || (Val >= Low && Val < Hi);
3615 }
3616
3617 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3618 /// specified value.
3619 static bool isUndefOrEqual(int Val, int CmpVal) {
3620   return (Val < 0 || Val == CmpVal);
3621 }
3622
3623 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3624 /// from position Pos and ending in Pos+Size, falls within the specified
3625 /// sequential range (L, L+Pos]. or is undef.
3626 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3627                                        unsigned Pos, unsigned Size, int Low) {
3628   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3629     if (!isUndefOrEqual(Mask[i], Low))
3630       return false;
3631   return true;
3632 }
3633
3634 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3635 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3636 /// the second operand.
3637 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3638   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3639     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3640   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3641     return (Mask[0] < 2 && Mask[1] < 2);
3642   return false;
3643 }
3644
3645 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3646 /// is suitable for input to PSHUFHW.
3647 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3648   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3649     return false;
3650
3651   // Lower quadword copied in order or undef.
3652   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3653     return false;
3654
3655   // Upper quadword shuffled.
3656   for (unsigned i = 4; i != 8; ++i)
3657     if (!isUndefOrInRange(Mask[i], 4, 8))
3658       return false;
3659
3660   if (VT == MVT::v16i16) {
3661     // Lower quadword copied in order or undef.
3662     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3663       return false;
3664
3665     // Upper quadword shuffled.
3666     for (unsigned i = 12; i != 16; ++i)
3667       if (!isUndefOrInRange(Mask[i], 12, 16))
3668         return false;
3669   }
3670
3671   return true;
3672 }
3673
3674 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3675 /// is suitable for input to PSHUFLW.
3676 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3677   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3678     return false;
3679
3680   // Upper quadword copied in order.
3681   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3682     return false;
3683
3684   // Lower quadword shuffled.
3685   for (unsigned i = 0; i != 4; ++i)
3686     if (!isUndefOrInRange(Mask[i], 0, 4))
3687       return false;
3688
3689   if (VT == MVT::v16i16) {
3690     // Upper quadword copied in order.
3691     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3692       return false;
3693
3694     // Lower quadword shuffled.
3695     for (unsigned i = 8; i != 12; ++i)
3696       if (!isUndefOrInRange(Mask[i], 8, 12))
3697         return false;
3698   }
3699
3700   return true;
3701 }
3702
3703 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3704 /// is suitable for input to PALIGNR.
3705 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3706                           const X86Subtarget *Subtarget) {
3707   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3708       (VT.is256BitVector() && !Subtarget->hasInt256()))
3709     return false;
3710
3711   unsigned NumElts = VT.getVectorNumElements();
3712   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3713   unsigned NumLaneElts = NumElts/NumLanes;
3714
3715   // Do not handle 64-bit element shuffles with palignr.
3716   if (NumLaneElts == 2)
3717     return false;
3718
3719   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3720     unsigned i;
3721     for (i = 0; i != NumLaneElts; ++i) {
3722       if (Mask[i+l] >= 0)
3723         break;
3724     }
3725
3726     // Lane is all undef, go to next lane
3727     if (i == NumLaneElts)
3728       continue;
3729
3730     int Start = Mask[i+l];
3731
3732     // Make sure its in this lane in one of the sources
3733     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3734         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3735       return false;
3736
3737     // If not lane 0, then we must match lane 0
3738     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3739       return false;
3740
3741     // Correct second source to be contiguous with first source
3742     if (Start >= (int)NumElts)
3743       Start -= NumElts - NumLaneElts;
3744
3745     // Make sure we're shifting in the right direction.
3746     if (Start <= (int)(i+l))
3747       return false;
3748
3749     Start -= i;
3750
3751     // Check the rest of the elements to see if they are consecutive.
3752     for (++i; i != NumLaneElts; ++i) {
3753       int Idx = Mask[i+l];
3754
3755       // Make sure its in this lane
3756       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3757           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3758         return false;
3759
3760       // If not lane 0, then we must match lane 0
3761       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3762         return false;
3763
3764       if (Idx >= (int)NumElts)
3765         Idx -= NumElts - NumLaneElts;
3766
3767       if (!isUndefOrEqual(Idx, Start+i))
3768         return false;
3769
3770     }
3771   }
3772
3773   return true;
3774 }
3775
3776 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3777 /// the two vector operands have swapped position.
3778 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3779                                      unsigned NumElems) {
3780   for (unsigned i = 0; i != NumElems; ++i) {
3781     int idx = Mask[i];
3782     if (idx < 0)
3783       continue;
3784     else if (idx < (int)NumElems)
3785       Mask[i] = idx + NumElems;
3786     else
3787       Mask[i] = idx - NumElems;
3788   }
3789 }
3790
3791 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3792 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3793 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3794 /// reverse of what x86 shuffles want.
3795 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3796
3797   unsigned NumElems = VT.getVectorNumElements();
3798   unsigned NumLanes = VT.getSizeInBits()/128;
3799   unsigned NumLaneElems = NumElems/NumLanes;
3800
3801   if (NumLaneElems != 2 && NumLaneElems != 4)
3802     return false;
3803
3804   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3805   bool symetricMaskRequired =
3806     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3807
3808   // VSHUFPSY divides the resulting vector into 4 chunks.
3809   // The sources are also splitted into 4 chunks, and each destination
3810   // chunk must come from a different source chunk.
3811   //
3812   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3813   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3814   //
3815   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3816   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3817   //
3818   // VSHUFPDY divides the resulting vector into 4 chunks.
3819   // The sources are also splitted into 4 chunks, and each destination
3820   // chunk must come from a different source chunk.
3821   //
3822   //  SRC1 =>      X3       X2       X1       X0
3823   //  SRC2 =>      Y3       Y2       Y1       Y0
3824   //
3825   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3826   //
3827   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3828   unsigned HalfLaneElems = NumLaneElems/2;
3829   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3830     for (unsigned i = 0; i != NumLaneElems; ++i) {
3831       int Idx = Mask[i+l];
3832       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3833       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3834         return false;
3835       // For VSHUFPSY, the mask of the second half must be the same as the
3836       // first but with the appropriate offsets. This works in the same way as
3837       // VPERMILPS works with masks.
3838       if (!symetricMaskRequired || Idx < 0)
3839         continue;
3840       if (MaskVal[i] < 0) {
3841         MaskVal[i] = Idx - l;
3842         continue;
3843       }
3844       if ((signed)(Idx - l) != MaskVal[i])
3845         return false;
3846     }
3847   }
3848
3849   return true;
3850 }
3851
3852 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3853 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3854 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3855   if (!VT.is128BitVector())
3856     return false;
3857
3858   unsigned NumElems = VT.getVectorNumElements();
3859
3860   if (NumElems != 4)
3861     return false;
3862
3863   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3864   return isUndefOrEqual(Mask[0], 6) &&
3865          isUndefOrEqual(Mask[1], 7) &&
3866          isUndefOrEqual(Mask[2], 2) &&
3867          isUndefOrEqual(Mask[3], 3);
3868 }
3869
3870 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3871 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3872 /// <2, 3, 2, 3>
3873 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3874   if (!VT.is128BitVector())
3875     return false;
3876
3877   unsigned NumElems = VT.getVectorNumElements();
3878
3879   if (NumElems != 4)
3880     return false;
3881
3882   return isUndefOrEqual(Mask[0], 2) &&
3883          isUndefOrEqual(Mask[1], 3) &&
3884          isUndefOrEqual(Mask[2], 2) &&
3885          isUndefOrEqual(Mask[3], 3);
3886 }
3887
3888 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3889 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3890 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3891   if (!VT.is128BitVector())
3892     return false;
3893
3894   unsigned NumElems = VT.getVectorNumElements();
3895
3896   if (NumElems != 2 && NumElems != 4)
3897     return false;
3898
3899   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3900     if (!isUndefOrEqual(Mask[i], i + NumElems))
3901       return false;
3902
3903   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3904     if (!isUndefOrEqual(Mask[i], i))
3905       return false;
3906
3907   return true;
3908 }
3909
3910 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3912 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3913   if (!VT.is128BitVector())
3914     return false;
3915
3916   unsigned NumElems = VT.getVectorNumElements();
3917
3918   if (NumElems != 2 && NumElems != 4)
3919     return false;
3920
3921   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3922     if (!isUndefOrEqual(Mask[i], i))
3923       return false;
3924
3925   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3926     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3927       return false;
3928
3929   return true;
3930 }
3931
3932 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3933 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3934 /// i. e: If all but one element come from the same vector.
3935 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3936   // TODO: Deal with AVX's VINSERTPS
3937   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3938     return false;
3939
3940   unsigned CorrectPosV1 = 0;
3941   unsigned CorrectPosV2 = 0;
3942   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3943     if (Mask[i] == i)
3944       ++CorrectPosV1;
3945     else if (Mask[i] == i + 4)
3946       ++CorrectPosV2;
3947
3948   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3949     // We have 3 elements from one vector, and one from another.
3950     return true;
3951
3952   return false;
3953 }
3954
3955 //
3956 // Some special combinations that can be optimized.
3957 //
3958 static
3959 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3960                                SelectionDAG &DAG) {
3961   MVT VT = SVOp->getSimpleValueType(0);
3962   SDLoc dl(SVOp);
3963
3964   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3965     return SDValue();
3966
3967   ArrayRef<int> Mask = SVOp->getMask();
3968
3969   // These are the special masks that may be optimized.
3970   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3971   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3972   bool MatchEvenMask = true;
3973   bool MatchOddMask  = true;
3974   for (int i=0; i<8; ++i) {
3975     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3976       MatchEvenMask = false;
3977     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3978       MatchOddMask = false;
3979   }
3980
3981   if (!MatchEvenMask && !MatchOddMask)
3982     return SDValue();
3983
3984   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3985
3986   SDValue Op0 = SVOp->getOperand(0);
3987   SDValue Op1 = SVOp->getOperand(1);
3988
3989   if (MatchEvenMask) {
3990     // Shift the second operand right to 32 bits.
3991     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3992     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3993   } else {
3994     // Shift the first operand left to 32 bits.
3995     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3996     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3997   }
3998   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3999   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4000 }
4001
4002 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4003 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4004 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4005                          bool HasInt256, bool V2IsSplat = false) {
4006
4007   assert(VT.getSizeInBits() >= 128 &&
4008          "Unsupported vector type for unpckl");
4009
4010   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4011   unsigned NumLanes;
4012   unsigned NumOf256BitLanes;
4013   unsigned NumElts = VT.getVectorNumElements();
4014   if (VT.is256BitVector()) {
4015     if (NumElts != 4 && NumElts != 8 &&
4016         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4017     return false;
4018     NumLanes = 2;
4019     NumOf256BitLanes = 1;
4020   } else if (VT.is512BitVector()) {
4021     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4022            "Unsupported vector type for unpckh");
4023     NumLanes = 2;
4024     NumOf256BitLanes = 2;
4025   } else {
4026     NumLanes = 1;
4027     NumOf256BitLanes = 1;
4028   }
4029
4030   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4031   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4032
4033   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4034     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4035       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4036         int BitI  = Mask[l256*NumEltsInStride+l+i];
4037         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4038         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4039           return false;
4040         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4041           return false;
4042         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4043           return false;
4044       }
4045     }
4046   }
4047   return true;
4048 }
4049
4050 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4051 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4052 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4053                          bool HasInt256, bool V2IsSplat = false) {
4054   assert(VT.getSizeInBits() >= 128 &&
4055          "Unsupported vector type for unpckh");
4056
4057   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4058   unsigned NumLanes;
4059   unsigned NumOf256BitLanes;
4060   unsigned NumElts = VT.getVectorNumElements();
4061   if (VT.is256BitVector()) {
4062     if (NumElts != 4 && NumElts != 8 &&
4063         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4064     return false;
4065     NumLanes = 2;
4066     NumOf256BitLanes = 1;
4067   } else if (VT.is512BitVector()) {
4068     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4069            "Unsupported vector type for unpckh");
4070     NumLanes = 2;
4071     NumOf256BitLanes = 2;
4072   } else {
4073     NumLanes = 1;
4074     NumOf256BitLanes = 1;
4075   }
4076
4077   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4078   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4079
4080   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4081     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4082       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4083         int BitI  = Mask[l256*NumEltsInStride+l+i];
4084         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4085         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4086           return false;
4087         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4088           return false;
4089         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4090           return false;
4091       }
4092     }
4093   }
4094   return true;
4095 }
4096
4097 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4098 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4099 /// <0, 0, 1, 1>
4100 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4101   unsigned NumElts = VT.getVectorNumElements();
4102   bool Is256BitVec = VT.is256BitVector();
4103
4104   if (VT.is512BitVector())
4105     return false;
4106   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4107          "Unsupported vector type for unpckh");
4108
4109   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4110       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4111     return false;
4112
4113   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4114   // FIXME: Need a better way to get rid of this, there's no latency difference
4115   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4116   // the former later. We should also remove the "_undef" special mask.
4117   if (NumElts == 4 && Is256BitVec)
4118     return false;
4119
4120   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4121   // independently on 128-bit lanes.
4122   unsigned NumLanes = VT.getSizeInBits()/128;
4123   unsigned NumLaneElts = NumElts/NumLanes;
4124
4125   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4126     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4127       int BitI  = Mask[l+i];
4128       int BitI1 = Mask[l+i+1];
4129
4130       if (!isUndefOrEqual(BitI, j))
4131         return false;
4132       if (!isUndefOrEqual(BitI1, j))
4133         return false;
4134     }
4135   }
4136
4137   return true;
4138 }
4139
4140 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4141 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4142 /// <2, 2, 3, 3>
4143 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4144   unsigned NumElts = VT.getVectorNumElements();
4145
4146   if (VT.is512BitVector())
4147     return false;
4148
4149   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4150          "Unsupported vector type for unpckh");
4151
4152   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4153       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4154     return false;
4155
4156   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4157   // independently on 128-bit lanes.
4158   unsigned NumLanes = VT.getSizeInBits()/128;
4159   unsigned NumLaneElts = NumElts/NumLanes;
4160
4161   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4162     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4163       int BitI  = Mask[l+i];
4164       int BitI1 = Mask[l+i+1];
4165       if (!isUndefOrEqual(BitI, j))
4166         return false;
4167       if (!isUndefOrEqual(BitI1, j))
4168         return false;
4169     }
4170   }
4171   return true;
4172 }
4173
4174 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4175 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4176 /// MOVSD, and MOVD, i.e. setting the lowest element.
4177 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4178   if (VT.getVectorElementType().getSizeInBits() < 32)
4179     return false;
4180   if (!VT.is128BitVector())
4181     return false;
4182
4183   unsigned NumElts = VT.getVectorNumElements();
4184
4185   if (!isUndefOrEqual(Mask[0], NumElts))
4186     return false;
4187
4188   for (unsigned i = 1; i != NumElts; ++i)
4189     if (!isUndefOrEqual(Mask[i], i))
4190       return false;
4191
4192   return true;
4193 }
4194
4195 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4196 /// as permutations between 128-bit chunks or halves. As an example: this
4197 /// shuffle bellow:
4198 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4199 /// The first half comes from the second half of V1 and the second half from the
4200 /// the second half of V2.
4201 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4202   if (!HasFp256 || !VT.is256BitVector())
4203     return false;
4204
4205   // The shuffle result is divided into half A and half B. In total the two
4206   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4207   // B must come from C, D, E or F.
4208   unsigned HalfSize = VT.getVectorNumElements()/2;
4209   bool MatchA = false, MatchB = false;
4210
4211   // Check if A comes from one of C, D, E, F.
4212   for (unsigned Half = 0; Half != 4; ++Half) {
4213     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4214       MatchA = true;
4215       break;
4216     }
4217   }
4218
4219   // Check if B comes from one of C, D, E, F.
4220   for (unsigned Half = 0; Half != 4; ++Half) {
4221     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4222       MatchB = true;
4223       break;
4224     }
4225   }
4226
4227   return MatchA && MatchB;
4228 }
4229
4230 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4231 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4232 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4233   MVT VT = SVOp->getSimpleValueType(0);
4234
4235   unsigned HalfSize = VT.getVectorNumElements()/2;
4236
4237   unsigned FstHalf = 0, SndHalf = 0;
4238   for (unsigned i = 0; i < HalfSize; ++i) {
4239     if (SVOp->getMaskElt(i) > 0) {
4240       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4241       break;
4242     }
4243   }
4244   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4245     if (SVOp->getMaskElt(i) > 0) {
4246       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4247       break;
4248     }
4249   }
4250
4251   return (FstHalf | (SndHalf << 4));
4252 }
4253
4254 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4255 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4256   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4257   if (EltSize < 32)
4258     return false;
4259
4260   unsigned NumElts = VT.getVectorNumElements();
4261   Imm8 = 0;
4262   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4263     for (unsigned i = 0; i != NumElts; ++i) {
4264       if (Mask[i] < 0)
4265         continue;
4266       Imm8 |= Mask[i] << (i*2);
4267     }
4268     return true;
4269   }
4270
4271   unsigned LaneSize = 4;
4272   SmallVector<int, 4> MaskVal(LaneSize, -1);
4273
4274   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4275     for (unsigned i = 0; i != LaneSize; ++i) {
4276       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4277         return false;
4278       if (Mask[i+l] < 0)
4279         continue;
4280       if (MaskVal[i] < 0) {
4281         MaskVal[i] = Mask[i+l] - l;
4282         Imm8 |= MaskVal[i] << (i*2);
4283         continue;
4284       }
4285       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4286         return false;
4287     }
4288   }
4289   return true;
4290 }
4291
4292 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4293 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4294 /// Note that VPERMIL mask matching is different depending whether theunderlying
4295 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4296 /// to the same elements of the low, but to the higher half of the source.
4297 /// In VPERMILPD the two lanes could be shuffled independently of each other
4298 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4299 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4300   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4301   if (VT.getSizeInBits() < 256 || EltSize < 32)
4302     return false;
4303   bool symetricMaskRequired = (EltSize == 32);
4304   unsigned NumElts = VT.getVectorNumElements();
4305
4306   unsigned NumLanes = VT.getSizeInBits()/128;
4307   unsigned LaneSize = NumElts/NumLanes;
4308   // 2 or 4 elements in one lane
4309
4310   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4311   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4312     for (unsigned i = 0; i != LaneSize; ++i) {
4313       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4314         return false;
4315       if (symetricMaskRequired) {
4316         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4317           ExpectedMaskVal[i] = Mask[i+l] - l;
4318           continue;
4319         }
4320         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4321           return false;
4322       }
4323     }
4324   }
4325   return true;
4326 }
4327
4328 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4329 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4330 /// element of vector 2 and the other elements to come from vector 1 in order.
4331 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4332                                bool V2IsSplat = false, bool V2IsUndef = false) {
4333   if (!VT.is128BitVector())
4334     return false;
4335
4336   unsigned NumOps = VT.getVectorNumElements();
4337   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4338     return false;
4339
4340   if (!isUndefOrEqual(Mask[0], 0))
4341     return false;
4342
4343   for (unsigned i = 1; i != NumOps; ++i)
4344     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4345           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4346           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4347       return false;
4348
4349   return true;
4350 }
4351
4352 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4353 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4354 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4355 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4356                            const X86Subtarget *Subtarget) {
4357   if (!Subtarget->hasSSE3())
4358     return false;
4359
4360   unsigned NumElems = VT.getVectorNumElements();
4361
4362   if ((VT.is128BitVector() && NumElems != 4) ||
4363       (VT.is256BitVector() && NumElems != 8) ||
4364       (VT.is512BitVector() && NumElems != 16))
4365     return false;
4366
4367   // "i+1" is the value the indexed mask element must have
4368   for (unsigned i = 0; i != NumElems; i += 2)
4369     if (!isUndefOrEqual(Mask[i], i+1) ||
4370         !isUndefOrEqual(Mask[i+1], i+1))
4371       return false;
4372
4373   return true;
4374 }
4375
4376 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4377 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4378 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4379 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4380                            const X86Subtarget *Subtarget) {
4381   if (!Subtarget->hasSSE3())
4382     return false;
4383
4384   unsigned NumElems = VT.getVectorNumElements();
4385
4386   if ((VT.is128BitVector() && NumElems != 4) ||
4387       (VT.is256BitVector() && NumElems != 8) ||
4388       (VT.is512BitVector() && NumElems != 16))
4389     return false;
4390
4391   // "i" is the value the indexed mask element must have
4392   for (unsigned i = 0; i != NumElems; i += 2)
4393     if (!isUndefOrEqual(Mask[i], i) ||
4394         !isUndefOrEqual(Mask[i+1], i))
4395       return false;
4396
4397   return true;
4398 }
4399
4400 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4401 /// specifies a shuffle of elements that is suitable for input to 256-bit
4402 /// version of MOVDDUP.
4403 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4404   if (!HasFp256 || !VT.is256BitVector())
4405     return false;
4406
4407   unsigned NumElts = VT.getVectorNumElements();
4408   if (NumElts != 4)
4409     return false;
4410
4411   for (unsigned i = 0; i != NumElts/2; ++i)
4412     if (!isUndefOrEqual(Mask[i], 0))
4413       return false;
4414   for (unsigned i = NumElts/2; i != NumElts; ++i)
4415     if (!isUndefOrEqual(Mask[i], NumElts/2))
4416       return false;
4417   return true;
4418 }
4419
4420 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4421 /// specifies a shuffle of elements that is suitable for input to 128-bit
4422 /// version of MOVDDUP.
4423 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4424   if (!VT.is128BitVector())
4425     return false;
4426
4427   unsigned e = VT.getVectorNumElements() / 2;
4428   for (unsigned i = 0; i != e; ++i)
4429     if (!isUndefOrEqual(Mask[i], i))
4430       return false;
4431   for (unsigned i = 0; i != e; ++i)
4432     if (!isUndefOrEqual(Mask[e+i], i))
4433       return false;
4434   return true;
4435 }
4436
4437 /// isVEXTRACTIndex - Return true if the specified
4438 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4439 /// suitable for instruction that extract 128 or 256 bit vectors
4440 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4441   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4442   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4443     return false;
4444
4445   // The index should be aligned on a vecWidth-bit boundary.
4446   uint64_t Index =
4447     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4448
4449   MVT VT = N->getSimpleValueType(0);
4450   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4451   bool Result = (Index * ElSize) % vecWidth == 0;
4452
4453   return Result;
4454 }
4455
4456 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4457 /// operand specifies a subvector insert that is suitable for input to
4458 /// insertion of 128 or 256-bit subvectors
4459 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4460   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4461   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4462     return false;
4463   // The index should be aligned on a vecWidth-bit boundary.
4464   uint64_t Index =
4465     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4466
4467   MVT VT = N->getSimpleValueType(0);
4468   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4469   bool Result = (Index * ElSize) % vecWidth == 0;
4470
4471   return Result;
4472 }
4473
4474 bool X86::isVINSERT128Index(SDNode *N) {
4475   return isVINSERTIndex(N, 128);
4476 }
4477
4478 bool X86::isVINSERT256Index(SDNode *N) {
4479   return isVINSERTIndex(N, 256);
4480 }
4481
4482 bool X86::isVEXTRACT128Index(SDNode *N) {
4483   return isVEXTRACTIndex(N, 128);
4484 }
4485
4486 bool X86::isVEXTRACT256Index(SDNode *N) {
4487   return isVEXTRACTIndex(N, 256);
4488 }
4489
4490 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4491 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4492 /// Handles 128-bit and 256-bit.
4493 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4494   MVT VT = N->getSimpleValueType(0);
4495
4496   assert((VT.getSizeInBits() >= 128) &&
4497          "Unsupported vector type for PSHUF/SHUFP");
4498
4499   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4500   // independently on 128-bit lanes.
4501   unsigned NumElts = VT.getVectorNumElements();
4502   unsigned NumLanes = VT.getSizeInBits()/128;
4503   unsigned NumLaneElts = NumElts/NumLanes;
4504
4505   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4506          "Only supports 2, 4 or 8 elements per lane");
4507
4508   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4509   unsigned Mask = 0;
4510   for (unsigned i = 0; i != NumElts; ++i) {
4511     int Elt = N->getMaskElt(i);
4512     if (Elt < 0) continue;
4513     Elt &= NumLaneElts - 1;
4514     unsigned ShAmt = (i << Shift) % 8;
4515     Mask |= Elt << ShAmt;
4516   }
4517
4518   return Mask;
4519 }
4520
4521 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4522 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4523 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4524   MVT VT = N->getSimpleValueType(0);
4525
4526   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4527          "Unsupported vector type for PSHUFHW");
4528
4529   unsigned NumElts = VT.getVectorNumElements();
4530
4531   unsigned Mask = 0;
4532   for (unsigned l = 0; l != NumElts; l += 8) {
4533     // 8 nodes per lane, but we only care about the last 4.
4534     for (unsigned i = 0; i < 4; ++i) {
4535       int Elt = N->getMaskElt(l+i+4);
4536       if (Elt < 0) continue;
4537       Elt &= 0x3; // only 2-bits.
4538       Mask |= Elt << (i * 2);
4539     }
4540   }
4541
4542   return Mask;
4543 }
4544
4545 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4546 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4547 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4548   MVT VT = N->getSimpleValueType(0);
4549
4550   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4551          "Unsupported vector type for PSHUFHW");
4552
4553   unsigned NumElts = VT.getVectorNumElements();
4554
4555   unsigned Mask = 0;
4556   for (unsigned l = 0; l != NumElts; l += 8) {
4557     // 8 nodes per lane, but we only care about the first 4.
4558     for (unsigned i = 0; i < 4; ++i) {
4559       int Elt = N->getMaskElt(l+i);
4560       if (Elt < 0) continue;
4561       Elt &= 0x3; // only 2-bits
4562       Mask |= Elt << (i * 2);
4563     }
4564   }
4565
4566   return Mask;
4567 }
4568
4569 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4570 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4571 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4572   MVT VT = SVOp->getSimpleValueType(0);
4573   unsigned EltSize = VT.is512BitVector() ? 1 :
4574     VT.getVectorElementType().getSizeInBits() >> 3;
4575
4576   unsigned NumElts = VT.getVectorNumElements();
4577   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4578   unsigned NumLaneElts = NumElts/NumLanes;
4579
4580   int Val = 0;
4581   unsigned i;
4582   for (i = 0; i != NumElts; ++i) {
4583     Val = SVOp->getMaskElt(i);
4584     if (Val >= 0)
4585       break;
4586   }
4587   if (Val >= (int)NumElts)
4588     Val -= NumElts - NumLaneElts;
4589
4590   assert(Val - i > 0 && "PALIGNR imm should be positive");
4591   return (Val - i) * EltSize;
4592 }
4593
4594 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4595   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4596   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4597     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4598
4599   uint64_t Index =
4600     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4601
4602   MVT VecVT = N->getOperand(0).getSimpleValueType();
4603   MVT ElVT = VecVT.getVectorElementType();
4604
4605   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4606   return Index / NumElemsPerChunk;
4607 }
4608
4609 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4610   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4611   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4612     llvm_unreachable("Illegal insert subvector for VINSERT");
4613
4614   uint64_t Index =
4615     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4616
4617   MVT VecVT = N->getSimpleValueType(0);
4618   MVT ElVT = VecVT.getVectorElementType();
4619
4620   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4621   return Index / NumElemsPerChunk;
4622 }
4623
4624 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4625 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4626 /// and VINSERTI128 instructions.
4627 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4628   return getExtractVEXTRACTImmediate(N, 128);
4629 }
4630
4631 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4632 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4633 /// and VINSERTI64x4 instructions.
4634 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4635   return getExtractVEXTRACTImmediate(N, 256);
4636 }
4637
4638 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4639 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4640 /// and VINSERTI128 instructions.
4641 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4642   return getInsertVINSERTImmediate(N, 128);
4643 }
4644
4645 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4646 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4647 /// and VINSERTI64x4 instructions.
4648 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4649   return getInsertVINSERTImmediate(N, 256);
4650 }
4651
4652 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4653 /// constant +0.0.
4654 bool X86::isZeroNode(SDValue Elt) {
4655   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4656     return CN->isNullValue();
4657   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4658     return CFP->getValueAPF().isPosZero();
4659   return false;
4660 }
4661
4662 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4663 /// their permute mask.
4664 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4665                                     SelectionDAG &DAG) {
4666   MVT VT = SVOp->getSimpleValueType(0);
4667   unsigned NumElems = VT.getVectorNumElements();
4668   SmallVector<int, 8> MaskVec;
4669
4670   for (unsigned i = 0; i != NumElems; ++i) {
4671     int Idx = SVOp->getMaskElt(i);
4672     if (Idx >= 0) {
4673       if (Idx < (int)NumElems)
4674         Idx += NumElems;
4675       else
4676         Idx -= NumElems;
4677     }
4678     MaskVec.push_back(Idx);
4679   }
4680   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4681                               SVOp->getOperand(0), &MaskVec[0]);
4682 }
4683
4684 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4685 /// match movhlps. The lower half elements should come from upper half of
4686 /// V1 (and in order), and the upper half elements should come from the upper
4687 /// half of V2 (and in order).
4688 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4689   if (!VT.is128BitVector())
4690     return false;
4691   if (VT.getVectorNumElements() != 4)
4692     return false;
4693   for (unsigned i = 0, e = 2; i != e; ++i)
4694     if (!isUndefOrEqual(Mask[i], i+2))
4695       return false;
4696   for (unsigned i = 2; i != 4; ++i)
4697     if (!isUndefOrEqual(Mask[i], i+4))
4698       return false;
4699   return true;
4700 }
4701
4702 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4703 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4704 /// required.
4705 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4706   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4707     return false;
4708   N = N->getOperand(0).getNode();
4709   if (!ISD::isNON_EXTLoad(N))
4710     return false;
4711   if (LD)
4712     *LD = cast<LoadSDNode>(N);
4713   return true;
4714 }
4715
4716 // Test whether the given value is a vector value which will be legalized
4717 // into a load.
4718 static bool WillBeConstantPoolLoad(SDNode *N) {
4719   if (N->getOpcode() != ISD::BUILD_VECTOR)
4720     return false;
4721
4722   // Check for any non-constant elements.
4723   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4724     switch (N->getOperand(i).getNode()->getOpcode()) {
4725     case ISD::UNDEF:
4726     case ISD::ConstantFP:
4727     case ISD::Constant:
4728       break;
4729     default:
4730       return false;
4731     }
4732
4733   // Vectors of all-zeros and all-ones are materialized with special
4734   // instructions rather than being loaded.
4735   return !ISD::isBuildVectorAllZeros(N) &&
4736          !ISD::isBuildVectorAllOnes(N);
4737 }
4738
4739 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4740 /// match movlp{s|d}. The lower half elements should come from lower half of
4741 /// V1 (and in order), and the upper half elements should come from the upper
4742 /// half of V2 (and in order). And since V1 will become the source of the
4743 /// MOVLP, it must be either a vector load or a scalar load to vector.
4744 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4745                                ArrayRef<int> Mask, MVT VT) {
4746   if (!VT.is128BitVector())
4747     return false;
4748
4749   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4750     return false;
4751   // Is V2 is a vector load, don't do this transformation. We will try to use
4752   // load folding shufps op.
4753   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4754     return false;
4755
4756   unsigned NumElems = VT.getVectorNumElements();
4757
4758   if (NumElems != 2 && NumElems != 4)
4759     return false;
4760   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4761     if (!isUndefOrEqual(Mask[i], i))
4762       return false;
4763   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4764     if (!isUndefOrEqual(Mask[i], i+NumElems))
4765       return false;
4766   return true;
4767 }
4768
4769 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4770 /// all the same.
4771 static bool isSplatVector(SDNode *N) {
4772   if (N->getOpcode() != ISD::BUILD_VECTOR)
4773     return false;
4774
4775   SDValue SplatValue = N->getOperand(0);
4776   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4777     if (N->getOperand(i) != SplatValue)
4778       return false;
4779   return true;
4780 }
4781
4782 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4783 /// to an zero vector.
4784 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4785 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4786   SDValue V1 = N->getOperand(0);
4787   SDValue V2 = N->getOperand(1);
4788   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4789   for (unsigned i = 0; i != NumElems; ++i) {
4790     int Idx = N->getMaskElt(i);
4791     if (Idx >= (int)NumElems) {
4792       unsigned Opc = V2.getOpcode();
4793       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4794         continue;
4795       if (Opc != ISD::BUILD_VECTOR ||
4796           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4797         return false;
4798     } else if (Idx >= 0) {
4799       unsigned Opc = V1.getOpcode();
4800       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4801         continue;
4802       if (Opc != ISD::BUILD_VECTOR ||
4803           !X86::isZeroNode(V1.getOperand(Idx)))
4804         return false;
4805     }
4806   }
4807   return true;
4808 }
4809
4810 /// getZeroVector - Returns a vector of specified type with all zero elements.
4811 ///
4812 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4813                              SelectionDAG &DAG, SDLoc dl) {
4814   assert(VT.isVector() && "Expected a vector type");
4815
4816   // Always build SSE zero vectors as <4 x i32> bitcasted
4817   // to their dest type. This ensures they get CSE'd.
4818   SDValue Vec;
4819   if (VT.is128BitVector()) {  // SSE
4820     if (Subtarget->hasSSE2()) {  // SSE2
4821       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4822       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4823     } else { // SSE1
4824       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4825       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4826     }
4827   } else if (VT.is256BitVector()) { // AVX
4828     if (Subtarget->hasInt256()) { // AVX2
4829       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4830       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4831       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4832     } else {
4833       // 256-bit logic and arithmetic instructions in AVX are all
4834       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4835       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4836       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4837       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4838     }
4839   } else if (VT.is512BitVector()) { // AVX-512
4840       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4841       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4842                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4843       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4844   } else if (VT.getScalarType() == MVT::i1) {
4845     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4846     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4847     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4848     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4849   } else
4850     llvm_unreachable("Unexpected vector type");
4851
4852   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4853 }
4854
4855 /// getOnesVector - Returns a vector of specified type with all bits set.
4856 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4857 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4858 /// Then bitcast to their original type, ensuring they get CSE'd.
4859 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4860                              SDLoc dl) {
4861   assert(VT.isVector() && "Expected a vector type");
4862
4863   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4864   SDValue Vec;
4865   if (VT.is256BitVector()) {
4866     if (HasInt256) { // AVX2
4867       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4868       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4869     } else { // AVX
4870       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4871       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4872     }
4873   } else if (VT.is128BitVector()) {
4874     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4875   } else
4876     llvm_unreachable("Unexpected vector type");
4877
4878   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4879 }
4880
4881 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4882 /// that point to V2 points to its first element.
4883 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4884   for (unsigned i = 0; i != NumElems; ++i) {
4885     if (Mask[i] > (int)NumElems) {
4886       Mask[i] = NumElems;
4887     }
4888   }
4889 }
4890
4891 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4892 /// operation of specified width.
4893 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4894                        SDValue V2) {
4895   unsigned NumElems = VT.getVectorNumElements();
4896   SmallVector<int, 8> Mask;
4897   Mask.push_back(NumElems);
4898   for (unsigned i = 1; i != NumElems; ++i)
4899     Mask.push_back(i);
4900   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4901 }
4902
4903 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4904 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4905                           SDValue V2) {
4906   unsigned NumElems = VT.getVectorNumElements();
4907   SmallVector<int, 8> Mask;
4908   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4909     Mask.push_back(i);
4910     Mask.push_back(i + NumElems);
4911   }
4912   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4913 }
4914
4915 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4916 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4917                           SDValue V2) {
4918   unsigned NumElems = VT.getVectorNumElements();
4919   SmallVector<int, 8> Mask;
4920   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4921     Mask.push_back(i + Half);
4922     Mask.push_back(i + NumElems + Half);
4923   }
4924   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4925 }
4926
4927 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4928 // a generic shuffle instruction because the target has no such instructions.
4929 // Generate shuffles which repeat i16 and i8 several times until they can be
4930 // represented by v4f32 and then be manipulated by target suported shuffles.
4931 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4932   MVT VT = V.getSimpleValueType();
4933   int NumElems = VT.getVectorNumElements();
4934   SDLoc dl(V);
4935
4936   while (NumElems > 4) {
4937     if (EltNo < NumElems/2) {
4938       V = getUnpackl(DAG, dl, VT, V, V);
4939     } else {
4940       V = getUnpackh(DAG, dl, VT, V, V);
4941       EltNo -= NumElems/2;
4942     }
4943     NumElems >>= 1;
4944   }
4945   return V;
4946 }
4947
4948 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4949 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4950   MVT VT = V.getSimpleValueType();
4951   SDLoc dl(V);
4952
4953   if (VT.is128BitVector()) {
4954     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4955     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4956     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4957                              &SplatMask[0]);
4958   } else if (VT.is256BitVector()) {
4959     // To use VPERMILPS to splat scalars, the second half of indicies must
4960     // refer to the higher part, which is a duplication of the lower one,
4961     // because VPERMILPS can only handle in-lane permutations.
4962     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4963                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4964
4965     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4966     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4967                              &SplatMask[0]);
4968   } else
4969     llvm_unreachable("Vector size not supported");
4970
4971   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4972 }
4973
4974 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4975 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4976   MVT SrcVT = SV->getSimpleValueType(0);
4977   SDValue V1 = SV->getOperand(0);
4978   SDLoc dl(SV);
4979
4980   int EltNo = SV->getSplatIndex();
4981   int NumElems = SrcVT.getVectorNumElements();
4982   bool Is256BitVec = SrcVT.is256BitVector();
4983
4984   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4985          "Unknown how to promote splat for type");
4986
4987   // Extract the 128-bit part containing the splat element and update
4988   // the splat element index when it refers to the higher register.
4989   if (Is256BitVec) {
4990     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4991     if (EltNo >= NumElems/2)
4992       EltNo -= NumElems/2;
4993   }
4994
4995   // All i16 and i8 vector types can't be used directly by a generic shuffle
4996   // instruction because the target has no such instruction. Generate shuffles
4997   // which repeat i16 and i8 several times until they fit in i32, and then can
4998   // be manipulated by target suported shuffles.
4999   MVT EltVT = SrcVT.getVectorElementType();
5000   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5001     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5002
5003   // Recreate the 256-bit vector and place the same 128-bit vector
5004   // into the low and high part. This is necessary because we want
5005   // to use VPERM* to shuffle the vectors
5006   if (Is256BitVec) {
5007     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5008   }
5009
5010   return getLegalSplat(DAG, V1, EltNo);
5011 }
5012
5013 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5014 /// vector of zero or undef vector.  This produces a shuffle where the low
5015 /// element of V2 is swizzled into the zero/undef vector, landing at element
5016 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5017 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5018                                            bool IsZero,
5019                                            const X86Subtarget *Subtarget,
5020                                            SelectionDAG &DAG) {
5021   MVT VT = V2.getSimpleValueType();
5022   SDValue V1 = IsZero
5023     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5024   unsigned NumElems = VT.getVectorNumElements();
5025   SmallVector<int, 16> MaskVec;
5026   for (unsigned i = 0; i != NumElems; ++i)
5027     // If this is the insertion idx, put the low elt of V2 here.
5028     MaskVec.push_back(i == Idx ? NumElems : i);
5029   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5030 }
5031
5032 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5033 /// target specific opcode. Returns true if the Mask could be calculated.
5034 /// Sets IsUnary to true if only uses one source.
5035 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5036                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5037   unsigned NumElems = VT.getVectorNumElements();
5038   SDValue ImmN;
5039
5040   IsUnary = false;
5041   switch(N->getOpcode()) {
5042   case X86ISD::SHUFP:
5043     ImmN = N->getOperand(N->getNumOperands()-1);
5044     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5045     break;
5046   case X86ISD::UNPCKH:
5047     DecodeUNPCKHMask(VT, Mask);
5048     break;
5049   case X86ISD::UNPCKL:
5050     DecodeUNPCKLMask(VT, Mask);
5051     break;
5052   case X86ISD::MOVHLPS:
5053     DecodeMOVHLPSMask(NumElems, Mask);
5054     break;
5055   case X86ISD::MOVLHPS:
5056     DecodeMOVLHPSMask(NumElems, Mask);
5057     break;
5058   case X86ISD::PALIGNR:
5059     ImmN = N->getOperand(N->getNumOperands()-1);
5060     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5061     break;
5062   case X86ISD::PSHUFD:
5063   case X86ISD::VPERMILP:
5064     ImmN = N->getOperand(N->getNumOperands()-1);
5065     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5066     IsUnary = true;
5067     break;
5068   case X86ISD::PSHUFHW:
5069     ImmN = N->getOperand(N->getNumOperands()-1);
5070     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5071     IsUnary = true;
5072     break;
5073   case X86ISD::PSHUFLW:
5074     ImmN = N->getOperand(N->getNumOperands()-1);
5075     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5076     IsUnary = true;
5077     break;
5078   case X86ISD::VPERMI:
5079     ImmN = N->getOperand(N->getNumOperands()-1);
5080     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5081     IsUnary = true;
5082     break;
5083   case X86ISD::MOVSS:
5084   case X86ISD::MOVSD: {
5085     // The index 0 always comes from the first element of the second source,
5086     // this is why MOVSS and MOVSD are used in the first place. The other
5087     // elements come from the other positions of the first source vector
5088     Mask.push_back(NumElems);
5089     for (unsigned i = 1; i != NumElems; ++i) {
5090       Mask.push_back(i);
5091     }
5092     break;
5093   }
5094   case X86ISD::VPERM2X128:
5095     ImmN = N->getOperand(N->getNumOperands()-1);
5096     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5097     if (Mask.empty()) return false;
5098     break;
5099   case X86ISD::MOVDDUP:
5100   case X86ISD::MOVLHPD:
5101   case X86ISD::MOVLPD:
5102   case X86ISD::MOVLPS:
5103   case X86ISD::MOVSHDUP:
5104   case X86ISD::MOVSLDUP:
5105     // Not yet implemented
5106     return false;
5107   default: llvm_unreachable("unknown target shuffle node");
5108   }
5109
5110   return true;
5111 }
5112
5113 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5114 /// element of the result of the vector shuffle.
5115 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5116                                    unsigned Depth) {
5117   if (Depth == 6)
5118     return SDValue();  // Limit search depth.
5119
5120   SDValue V = SDValue(N, 0);
5121   EVT VT = V.getValueType();
5122   unsigned Opcode = V.getOpcode();
5123
5124   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5125   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5126     int Elt = SV->getMaskElt(Index);
5127
5128     if (Elt < 0)
5129       return DAG.getUNDEF(VT.getVectorElementType());
5130
5131     unsigned NumElems = VT.getVectorNumElements();
5132     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5133                                          : SV->getOperand(1);
5134     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5135   }
5136
5137   // Recurse into target specific vector shuffles to find scalars.
5138   if (isTargetShuffle(Opcode)) {
5139     MVT ShufVT = V.getSimpleValueType();
5140     unsigned NumElems = ShufVT.getVectorNumElements();
5141     SmallVector<int, 16> ShuffleMask;
5142     bool IsUnary;
5143
5144     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5145       return SDValue();
5146
5147     int Elt = ShuffleMask[Index];
5148     if (Elt < 0)
5149       return DAG.getUNDEF(ShufVT.getVectorElementType());
5150
5151     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5152                                          : N->getOperand(1);
5153     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5154                                Depth+1);
5155   }
5156
5157   // Actual nodes that may contain scalar elements
5158   if (Opcode == ISD::BITCAST) {
5159     V = V.getOperand(0);
5160     EVT SrcVT = V.getValueType();
5161     unsigned NumElems = VT.getVectorNumElements();
5162
5163     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5164       return SDValue();
5165   }
5166
5167   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5168     return (Index == 0) ? V.getOperand(0)
5169                         : DAG.getUNDEF(VT.getVectorElementType());
5170
5171   if (V.getOpcode() == ISD::BUILD_VECTOR)
5172     return V.getOperand(Index);
5173
5174   return SDValue();
5175 }
5176
5177 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5178 /// shuffle operation which come from a consecutively from a zero. The
5179 /// search can start in two different directions, from left or right.
5180 /// We count undefs as zeros until PreferredNum is reached.
5181 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5182                                          unsigned NumElems, bool ZerosFromLeft,
5183                                          SelectionDAG &DAG,
5184                                          unsigned PreferredNum = -1U) {
5185   unsigned NumZeros = 0;
5186   for (unsigned i = 0; i != NumElems; ++i) {
5187     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5188     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5189     if (!Elt.getNode())
5190       break;
5191
5192     if (X86::isZeroNode(Elt))
5193       ++NumZeros;
5194     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5195       NumZeros = std::min(NumZeros + 1, PreferredNum);
5196     else
5197       break;
5198   }
5199
5200   return NumZeros;
5201 }
5202
5203 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5204 /// correspond consecutively to elements from one of the vector operands,
5205 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5206 static
5207 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5208                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5209                               unsigned NumElems, unsigned &OpNum) {
5210   bool SeenV1 = false;
5211   bool SeenV2 = false;
5212
5213   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5214     int Idx = SVOp->getMaskElt(i);
5215     // Ignore undef indicies
5216     if (Idx < 0)
5217       continue;
5218
5219     if (Idx < (int)NumElems)
5220       SeenV1 = true;
5221     else
5222       SeenV2 = true;
5223
5224     // Only accept consecutive elements from the same vector
5225     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5226       return false;
5227   }
5228
5229   OpNum = SeenV1 ? 0 : 1;
5230   return true;
5231 }
5232
5233 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5234 /// logical left shift of a vector.
5235 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5236                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5237   unsigned NumElems =
5238     SVOp->getSimpleValueType(0).getVectorNumElements();
5239   unsigned NumZeros = getNumOfConsecutiveZeros(
5240       SVOp, NumElems, false /* check zeros from right */, DAG,
5241       SVOp->getMaskElt(0));
5242   unsigned OpSrc;
5243
5244   if (!NumZeros)
5245     return false;
5246
5247   // Considering the elements in the mask that are not consecutive zeros,
5248   // check if they consecutively come from only one of the source vectors.
5249   //
5250   //               V1 = {X, A, B, C}     0
5251   //                         \  \  \    /
5252   //   vector_shuffle V1, V2 <1, 2, 3, X>
5253   //
5254   if (!isShuffleMaskConsecutive(SVOp,
5255             0,                   // Mask Start Index
5256             NumElems-NumZeros,   // Mask End Index(exclusive)
5257             NumZeros,            // Where to start looking in the src vector
5258             NumElems,            // Number of elements in vector
5259             OpSrc))              // Which source operand ?
5260     return false;
5261
5262   isLeft = false;
5263   ShAmt = NumZeros;
5264   ShVal = SVOp->getOperand(OpSrc);
5265   return true;
5266 }
5267
5268 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5269 /// logical left shift of a vector.
5270 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5271                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5272   unsigned NumElems =
5273     SVOp->getSimpleValueType(0).getVectorNumElements();
5274   unsigned NumZeros = getNumOfConsecutiveZeros(
5275       SVOp, NumElems, true /* check zeros from left */, DAG,
5276       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5277   unsigned OpSrc;
5278
5279   if (!NumZeros)
5280     return false;
5281
5282   // Considering the elements in the mask that are not consecutive zeros,
5283   // check if they consecutively come from only one of the source vectors.
5284   //
5285   //                           0    { A, B, X, X } = V2
5286   //                          / \    /  /
5287   //   vector_shuffle V1, V2 <X, X, 4, 5>
5288   //
5289   if (!isShuffleMaskConsecutive(SVOp,
5290             NumZeros,     // Mask Start Index
5291             NumElems,     // Mask End Index(exclusive)
5292             0,            // Where to start looking in the src vector
5293             NumElems,     // Number of elements in vector
5294             OpSrc))       // Which source operand ?
5295     return false;
5296
5297   isLeft = true;
5298   ShAmt = NumZeros;
5299   ShVal = SVOp->getOperand(OpSrc);
5300   return true;
5301 }
5302
5303 /// isVectorShift - Returns true if the shuffle can be implemented as a
5304 /// logical left or right shift of a vector.
5305 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5306                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5307   // Although the logic below support any bitwidth size, there are no
5308   // shift instructions which handle more than 128-bit vectors.
5309   if (!SVOp->getSimpleValueType(0).is128BitVector())
5310     return false;
5311
5312   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5313       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5314     return true;
5315
5316   return false;
5317 }
5318
5319 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5320 ///
5321 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5322                                        unsigned NumNonZero, unsigned NumZero,
5323                                        SelectionDAG &DAG,
5324                                        const X86Subtarget* Subtarget,
5325                                        const TargetLowering &TLI) {
5326   if (NumNonZero > 8)
5327     return SDValue();
5328
5329   SDLoc dl(Op);
5330   SDValue V;
5331   bool First = true;
5332   for (unsigned i = 0; i < 16; ++i) {
5333     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5334     if (ThisIsNonZero && First) {
5335       if (NumZero)
5336         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5337       else
5338         V = DAG.getUNDEF(MVT::v8i16);
5339       First = false;
5340     }
5341
5342     if ((i & 1) != 0) {
5343       SDValue ThisElt, LastElt;
5344       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5345       if (LastIsNonZero) {
5346         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5347                               MVT::i16, Op.getOperand(i-1));
5348       }
5349       if (ThisIsNonZero) {
5350         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5351         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5352                               ThisElt, DAG.getConstant(8, MVT::i8));
5353         if (LastIsNonZero)
5354           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5355       } else
5356         ThisElt = LastElt;
5357
5358       if (ThisElt.getNode())
5359         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5360                         DAG.getIntPtrConstant(i/2));
5361     }
5362   }
5363
5364   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5365 }
5366
5367 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5368 ///
5369 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5370                                      unsigned NumNonZero, unsigned NumZero,
5371                                      SelectionDAG &DAG,
5372                                      const X86Subtarget* Subtarget,
5373                                      const TargetLowering &TLI) {
5374   if (NumNonZero > 4)
5375     return SDValue();
5376
5377   SDLoc dl(Op);
5378   SDValue V;
5379   bool First = true;
5380   for (unsigned i = 0; i < 8; ++i) {
5381     bool isNonZero = (NonZeros & (1 << i)) != 0;
5382     if (isNonZero) {
5383       if (First) {
5384         if (NumZero)
5385           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5386         else
5387           V = DAG.getUNDEF(MVT::v8i16);
5388         First = false;
5389       }
5390       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5391                       MVT::v8i16, V, Op.getOperand(i),
5392                       DAG.getIntPtrConstant(i));
5393     }
5394   }
5395
5396   return V;
5397 }
5398
5399 /// getVShift - Return a vector logical shift node.
5400 ///
5401 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5402                          unsigned NumBits, SelectionDAG &DAG,
5403                          const TargetLowering &TLI, SDLoc dl) {
5404   assert(VT.is128BitVector() && "Unknown type for VShift");
5405   EVT ShVT = MVT::v2i64;
5406   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5407   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5408   return DAG.getNode(ISD::BITCAST, dl, VT,
5409                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5410                              DAG.getConstant(NumBits,
5411                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5412 }
5413
5414 static SDValue
5415 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5416
5417   // Check if the scalar load can be widened into a vector load. And if
5418   // the address is "base + cst" see if the cst can be "absorbed" into
5419   // the shuffle mask.
5420   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5421     SDValue Ptr = LD->getBasePtr();
5422     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5423       return SDValue();
5424     EVT PVT = LD->getValueType(0);
5425     if (PVT != MVT::i32 && PVT != MVT::f32)
5426       return SDValue();
5427
5428     int FI = -1;
5429     int64_t Offset = 0;
5430     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5431       FI = FINode->getIndex();
5432       Offset = 0;
5433     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5434                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5435       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5436       Offset = Ptr.getConstantOperandVal(1);
5437       Ptr = Ptr.getOperand(0);
5438     } else {
5439       return SDValue();
5440     }
5441
5442     // FIXME: 256-bit vector instructions don't require a strict alignment,
5443     // improve this code to support it better.
5444     unsigned RequiredAlign = VT.getSizeInBits()/8;
5445     SDValue Chain = LD->getChain();
5446     // Make sure the stack object alignment is at least 16 or 32.
5447     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5448     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5449       if (MFI->isFixedObjectIndex(FI)) {
5450         // Can't change the alignment. FIXME: It's possible to compute
5451         // the exact stack offset and reference FI + adjust offset instead.
5452         // If someone *really* cares about this. That's the way to implement it.
5453         return SDValue();
5454       } else {
5455         MFI->setObjectAlignment(FI, RequiredAlign);
5456       }
5457     }
5458
5459     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5460     // Ptr + (Offset & ~15).
5461     if (Offset < 0)
5462       return SDValue();
5463     if ((Offset % RequiredAlign) & 3)
5464       return SDValue();
5465     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5466     if (StartOffset)
5467       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5468                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5469
5470     int EltNo = (Offset - StartOffset) >> 2;
5471     unsigned NumElems = VT.getVectorNumElements();
5472
5473     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5474     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5475                              LD->getPointerInfo().getWithOffset(StartOffset),
5476                              false, false, false, 0);
5477
5478     SmallVector<int, 8> Mask;
5479     for (unsigned i = 0; i != NumElems; ++i)
5480       Mask.push_back(EltNo);
5481
5482     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5483   }
5484
5485   return SDValue();
5486 }
5487
5488 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5489 /// vector of type 'VT', see if the elements can be replaced by a single large
5490 /// load which has the same value as a build_vector whose operands are 'elts'.
5491 ///
5492 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5493 ///
5494 /// FIXME: we'd also like to handle the case where the last elements are zero
5495 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5496 /// There's even a handy isZeroNode for that purpose.
5497 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5498                                         SDLoc &DL, SelectionDAG &DAG,
5499                                         bool isAfterLegalize) {
5500   EVT EltVT = VT.getVectorElementType();
5501   unsigned NumElems = Elts.size();
5502
5503   LoadSDNode *LDBase = nullptr;
5504   unsigned LastLoadedElt = -1U;
5505
5506   // For each element in the initializer, see if we've found a load or an undef.
5507   // If we don't find an initial load element, or later load elements are
5508   // non-consecutive, bail out.
5509   for (unsigned i = 0; i < NumElems; ++i) {
5510     SDValue Elt = Elts[i];
5511
5512     if (!Elt.getNode() ||
5513         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5514       return SDValue();
5515     if (!LDBase) {
5516       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5517         return SDValue();
5518       LDBase = cast<LoadSDNode>(Elt.getNode());
5519       LastLoadedElt = i;
5520       continue;
5521     }
5522     if (Elt.getOpcode() == ISD::UNDEF)
5523       continue;
5524
5525     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5526     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5527       return SDValue();
5528     LastLoadedElt = i;
5529   }
5530
5531   // If we have found an entire vector of loads and undefs, then return a large
5532   // load of the entire vector width starting at the base pointer.  If we found
5533   // consecutive loads for the low half, generate a vzext_load node.
5534   if (LastLoadedElt == NumElems - 1) {
5535
5536     if (isAfterLegalize &&
5537         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5538       return SDValue();
5539
5540     SDValue NewLd = SDValue();
5541
5542     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5543       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5544                           LDBase->getPointerInfo(),
5545                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5546                           LDBase->isInvariant(), 0);
5547     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5548                         LDBase->getPointerInfo(),
5549                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5550                         LDBase->isInvariant(), LDBase->getAlignment());
5551
5552     if (LDBase->hasAnyUseOfValue(1)) {
5553       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5554                                      SDValue(LDBase, 1),
5555                                      SDValue(NewLd.getNode(), 1));
5556       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5557       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5558                              SDValue(NewLd.getNode(), 1));
5559     }
5560
5561     return NewLd;
5562   }
5563   if (NumElems == 4 && LastLoadedElt == 1 &&
5564       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5565     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5566     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5567     SDValue ResNode =
5568         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5569                                 LDBase->getPointerInfo(),
5570                                 LDBase->getAlignment(),
5571                                 false/*isVolatile*/, true/*ReadMem*/,
5572                                 false/*WriteMem*/);
5573
5574     // Make sure the newly-created LOAD is in the same position as LDBase in
5575     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5576     // update uses of LDBase's output chain to use the TokenFactor.
5577     if (LDBase->hasAnyUseOfValue(1)) {
5578       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5579                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5580       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5581       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5582                              SDValue(ResNode.getNode(), 1));
5583     }
5584
5585     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5586   }
5587   return SDValue();
5588 }
5589
5590 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5591 /// to generate a splat value for the following cases:
5592 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5593 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5594 /// a scalar load, or a constant.
5595 /// The VBROADCAST node is returned when a pattern is found,
5596 /// or SDValue() otherwise.
5597 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5598                                     SelectionDAG &DAG) {
5599   if (!Subtarget->hasFp256())
5600     return SDValue();
5601
5602   MVT VT = Op.getSimpleValueType();
5603   SDLoc dl(Op);
5604
5605   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5606          "Unsupported vector type for broadcast.");
5607
5608   SDValue Ld;
5609   bool ConstSplatVal;
5610
5611   switch (Op.getOpcode()) {
5612     default:
5613       // Unknown pattern found.
5614       return SDValue();
5615
5616     case ISD::BUILD_VECTOR: {
5617       // The BUILD_VECTOR node must be a splat.
5618       if (!isSplatVector(Op.getNode()))
5619         return SDValue();
5620
5621       Ld = Op.getOperand(0);
5622       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5623                      Ld.getOpcode() == ISD::ConstantFP);
5624
5625       // The suspected load node has several users. Make sure that all
5626       // of its users are from the BUILD_VECTOR node.
5627       // Constants may have multiple users.
5628       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5629         return SDValue();
5630       break;
5631     }
5632
5633     case ISD::VECTOR_SHUFFLE: {
5634       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5635
5636       // Shuffles must have a splat mask where the first element is
5637       // broadcasted.
5638       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5639         return SDValue();
5640
5641       SDValue Sc = Op.getOperand(0);
5642       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5643           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5644
5645         if (!Subtarget->hasInt256())
5646           return SDValue();
5647
5648         // Use the register form of the broadcast instruction available on AVX2.
5649         if (VT.getSizeInBits() >= 256)
5650           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5651         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5652       }
5653
5654       Ld = Sc.getOperand(0);
5655       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5656                        Ld.getOpcode() == ISD::ConstantFP);
5657
5658       // The scalar_to_vector node and the suspected
5659       // load node must have exactly one user.
5660       // Constants may have multiple users.
5661
5662       // AVX-512 has register version of the broadcast
5663       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5664         Ld.getValueType().getSizeInBits() >= 32;
5665       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5666           !hasRegVer))
5667         return SDValue();
5668       break;
5669     }
5670   }
5671
5672   bool IsGE256 = (VT.getSizeInBits() >= 256);
5673
5674   // Handle the broadcasting a single constant scalar from the constant pool
5675   // into a vector. On Sandybridge it is still better to load a constant vector
5676   // from the constant pool and not to broadcast it from a scalar.
5677   if (ConstSplatVal && Subtarget->hasInt256()) {
5678     EVT CVT = Ld.getValueType();
5679     assert(!CVT.isVector() && "Must not broadcast a vector type");
5680     unsigned ScalarSize = CVT.getSizeInBits();
5681
5682     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5683       const Constant *C = nullptr;
5684       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5685         C = CI->getConstantIntValue();
5686       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5687         C = CF->getConstantFPValue();
5688
5689       assert(C && "Invalid constant type");
5690
5691       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5692       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5693       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5694       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5695                        MachinePointerInfo::getConstantPool(),
5696                        false, false, false, Alignment);
5697
5698       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5699     }
5700   }
5701
5702   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5703   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5704
5705   // Handle AVX2 in-register broadcasts.
5706   if (!IsLoad && Subtarget->hasInt256() &&
5707       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5708     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5709
5710   // The scalar source must be a normal load.
5711   if (!IsLoad)
5712     return SDValue();
5713
5714   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5715     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5716
5717   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5718   // double since there is no vbroadcastsd xmm
5719   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5720     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5721       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5722   }
5723
5724   // Unsupported broadcast.
5725   return SDValue();
5726 }
5727
5728 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5729 /// underlying vector and index.
5730 ///
5731 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5732 /// index.
5733 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5734                                          SDValue ExtIdx) {
5735   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5736   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5737     return Idx;
5738
5739   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5740   // lowered this:
5741   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5742   // to:
5743   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5744   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5745   //                           undef)
5746   //                       Constant<0>)
5747   // In this case the vector is the extract_subvector expression and the index
5748   // is 2, as specified by the shuffle.
5749   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5750   SDValue ShuffleVec = SVOp->getOperand(0);
5751   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5752   assert(ShuffleVecVT.getVectorElementType() ==
5753          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5754
5755   int ShuffleIdx = SVOp->getMaskElt(Idx);
5756   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5757     ExtractedFromVec = ShuffleVec;
5758     return ShuffleIdx;
5759   }
5760   return Idx;
5761 }
5762
5763 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5764   MVT VT = Op.getSimpleValueType();
5765
5766   // Skip if insert_vec_elt is not supported.
5767   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5768   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5769     return SDValue();
5770
5771   SDLoc DL(Op);
5772   unsigned NumElems = Op.getNumOperands();
5773
5774   SDValue VecIn1;
5775   SDValue VecIn2;
5776   SmallVector<unsigned, 4> InsertIndices;
5777   SmallVector<int, 8> Mask(NumElems, -1);
5778
5779   for (unsigned i = 0; i != NumElems; ++i) {
5780     unsigned Opc = Op.getOperand(i).getOpcode();
5781
5782     if (Opc == ISD::UNDEF)
5783       continue;
5784
5785     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5786       // Quit if more than 1 elements need inserting.
5787       if (InsertIndices.size() > 1)
5788         return SDValue();
5789
5790       InsertIndices.push_back(i);
5791       continue;
5792     }
5793
5794     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5795     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5796     // Quit if non-constant index.
5797     if (!isa<ConstantSDNode>(ExtIdx))
5798       return SDValue();
5799     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5800
5801     // Quit if extracted from vector of different type.
5802     if (ExtractedFromVec.getValueType() != VT)
5803       return SDValue();
5804
5805     if (!VecIn1.getNode())
5806       VecIn1 = ExtractedFromVec;
5807     else if (VecIn1 != ExtractedFromVec) {
5808       if (!VecIn2.getNode())
5809         VecIn2 = ExtractedFromVec;
5810       else if (VecIn2 != ExtractedFromVec)
5811         // Quit if more than 2 vectors to shuffle
5812         return SDValue();
5813     }
5814
5815     if (ExtractedFromVec == VecIn1)
5816       Mask[i] = Idx;
5817     else if (ExtractedFromVec == VecIn2)
5818       Mask[i] = Idx + NumElems;
5819   }
5820
5821   if (!VecIn1.getNode())
5822     return SDValue();
5823
5824   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5825   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5826   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5827     unsigned Idx = InsertIndices[i];
5828     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5829                      DAG.getIntPtrConstant(Idx));
5830   }
5831
5832   return NV;
5833 }
5834
5835 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5836 SDValue
5837 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5838
5839   MVT VT = Op.getSimpleValueType();
5840   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5841          "Unexpected type in LowerBUILD_VECTORvXi1!");
5842
5843   SDLoc dl(Op);
5844   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5845     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5846     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5847     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5848   }
5849
5850   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5851     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5852     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5853     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5854   }
5855
5856   bool AllContants = true;
5857   uint64_t Immediate = 0;
5858   int NonConstIdx = -1;
5859   bool IsSplat = true;
5860   unsigned NumNonConsts = 0;
5861   unsigned NumConsts = 0;
5862   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5863     SDValue In = Op.getOperand(idx);
5864     if (In.getOpcode() == ISD::UNDEF)
5865       continue;
5866     if (!isa<ConstantSDNode>(In)) {
5867       AllContants = false;
5868       NonConstIdx = idx;
5869       NumNonConsts++;
5870     }
5871     else {
5872       NumConsts++;
5873       if (cast<ConstantSDNode>(In)->getZExtValue())
5874       Immediate |= (1ULL << idx);
5875     }
5876     if (In != Op.getOperand(0))
5877       IsSplat = false;
5878   }
5879
5880   if (AllContants) {
5881     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
5882       DAG.getConstant(Immediate, MVT::i16));
5883     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
5884                        DAG.getIntPtrConstant(0));
5885   }
5886
5887   if (NumNonConsts == 1 && NonConstIdx != 0) {
5888     SDValue DstVec;
5889     if (NumConsts) {
5890       SDValue VecAsImm = DAG.getConstant(Immediate,
5891                                          MVT::getIntegerVT(VT.getSizeInBits()));
5892       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
5893     }
5894     else 
5895       DstVec = DAG.getUNDEF(VT);
5896     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5897                        Op.getOperand(NonConstIdx),
5898                        DAG.getIntPtrConstant(NonConstIdx));
5899   }
5900   if (!IsSplat && (NonConstIdx != 0))
5901     llvm_unreachable("Unsupported BUILD_VECTOR operation");
5902   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
5903   SDValue Select;
5904   if (IsSplat)
5905     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5906                           DAG.getConstant(-1, SelectVT),
5907                           DAG.getConstant(0, SelectVT));
5908   else
5909     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
5910                          DAG.getConstant((Immediate | 1), SelectVT),
5911                          DAG.getConstant(Immediate, SelectVT));
5912   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
5913 }
5914
5915 SDValue
5916 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5917   SDLoc dl(Op);
5918
5919   MVT VT = Op.getSimpleValueType();
5920   MVT ExtVT = VT.getVectorElementType();
5921   unsigned NumElems = Op.getNumOperands();
5922
5923   // Generate vectors for predicate vectors.
5924   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5925     return LowerBUILD_VECTORvXi1(Op, DAG);
5926
5927   // Vectors containing all zeros can be matched by pxor and xorps later
5928   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5929     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5930     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5931     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5932       return Op;
5933
5934     return getZeroVector(VT, Subtarget, DAG, dl);
5935   }
5936
5937   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5938   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5939   // vpcmpeqd on 256-bit vectors.
5940   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5941     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5942       return Op;
5943
5944     if (!VT.is512BitVector())
5945       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5946   }
5947
5948   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
5949   if (Broadcast.getNode())
5950     return Broadcast;
5951
5952   unsigned EVTBits = ExtVT.getSizeInBits();
5953
5954   unsigned NumZero  = 0;
5955   unsigned NumNonZero = 0;
5956   unsigned NonZeros = 0;
5957   bool IsAllConstants = true;
5958   SmallSet<SDValue, 8> Values;
5959   for (unsigned i = 0; i < NumElems; ++i) {
5960     SDValue Elt = Op.getOperand(i);
5961     if (Elt.getOpcode() == ISD::UNDEF)
5962       continue;
5963     Values.insert(Elt);
5964     if (Elt.getOpcode() != ISD::Constant &&
5965         Elt.getOpcode() != ISD::ConstantFP)
5966       IsAllConstants = false;
5967     if (X86::isZeroNode(Elt))
5968       NumZero++;
5969     else {
5970       NonZeros |= (1 << i);
5971       NumNonZero++;
5972     }
5973   }
5974
5975   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5976   if (NumNonZero == 0)
5977     return DAG.getUNDEF(VT);
5978
5979   // Special case for single non-zero, non-undef, element.
5980   if (NumNonZero == 1) {
5981     unsigned Idx = countTrailingZeros(NonZeros);
5982     SDValue Item = Op.getOperand(Idx);
5983
5984     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5985     // the value are obviously zero, truncate the value to i32 and do the
5986     // insertion that way.  Only do this if the value is non-constant or if the
5987     // value is a constant being inserted into element 0.  It is cheaper to do
5988     // a constant pool load than it is to do a movd + shuffle.
5989     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5990         (!IsAllConstants || Idx == 0)) {
5991       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5992         // Handle SSE only.
5993         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5994         EVT VecVT = MVT::v4i32;
5995         unsigned VecElts = 4;
5996
5997         // Truncate the value (which may itself be a constant) to i32, and
5998         // convert it to a vector with movd (S2V+shuffle to zero extend).
5999         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6000         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6001         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6002
6003         // Now we have our 32-bit value zero extended in the low element of
6004         // a vector.  If Idx != 0, swizzle it into place.
6005         if (Idx != 0) {
6006           SmallVector<int, 4> Mask;
6007           Mask.push_back(Idx);
6008           for (unsigned i = 1; i != VecElts; ++i)
6009             Mask.push_back(i);
6010           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6011                                       &Mask[0]);
6012         }
6013         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6014       }
6015     }
6016
6017     // If we have a constant or non-constant insertion into the low element of
6018     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6019     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6020     // depending on what the source datatype is.
6021     if (Idx == 0) {
6022       if (NumZero == 0)
6023         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6024
6025       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6026           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6027         if (VT.is256BitVector() || VT.is512BitVector()) {
6028           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6029           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6030                              Item, DAG.getIntPtrConstant(0));
6031         }
6032         assert(VT.is128BitVector() && "Expected an SSE value type!");
6033         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6034         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6035         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6036       }
6037
6038       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6039         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6040         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6041         if (VT.is256BitVector()) {
6042           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6043           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6044         } else {
6045           assert(VT.is128BitVector() && "Expected an SSE value type!");
6046           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6047         }
6048         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6049       }
6050     }
6051
6052     // Is it a vector logical left shift?
6053     if (NumElems == 2 && Idx == 1 &&
6054         X86::isZeroNode(Op.getOperand(0)) &&
6055         !X86::isZeroNode(Op.getOperand(1))) {
6056       unsigned NumBits = VT.getSizeInBits();
6057       return getVShift(true, VT,
6058                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6059                                    VT, Op.getOperand(1)),
6060                        NumBits/2, DAG, *this, dl);
6061     }
6062
6063     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6064       return SDValue();
6065
6066     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6067     // is a non-constant being inserted into an element other than the low one,
6068     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6069     // movd/movss) to move this into the low element, then shuffle it into
6070     // place.
6071     if (EVTBits == 32) {
6072       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6073
6074       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6075       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6076       SmallVector<int, 8> MaskVec;
6077       for (unsigned i = 0; i != NumElems; ++i)
6078         MaskVec.push_back(i == Idx ? 0 : 1);
6079       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6080     }
6081   }
6082
6083   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6084   if (Values.size() == 1) {
6085     if (EVTBits == 32) {
6086       // Instead of a shuffle like this:
6087       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6088       // Check if it's possible to issue this instead.
6089       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6090       unsigned Idx = countTrailingZeros(NonZeros);
6091       SDValue Item = Op.getOperand(Idx);
6092       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6093         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6094     }
6095     return SDValue();
6096   }
6097
6098   // A vector full of immediates; various special cases are already
6099   // handled, so this is best done with a single constant-pool load.
6100   if (IsAllConstants)
6101     return SDValue();
6102
6103   // For AVX-length vectors, build the individual 128-bit pieces and use
6104   // shuffles to put them in place.
6105   if (VT.is256BitVector() || VT.is512BitVector()) {
6106     SmallVector<SDValue, 64> V;
6107     for (unsigned i = 0; i != NumElems; ++i)
6108       V.push_back(Op.getOperand(i));
6109
6110     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6111
6112     // Build both the lower and upper subvector.
6113     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6114                                 ArrayRef<SDValue>(&V[0], NumElems/2));
6115     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6116                                 ArrayRef<SDValue>(&V[NumElems / 2],
6117                                                   NumElems/2));
6118
6119     // Recreate the wider vector with the lower and upper part.
6120     if (VT.is256BitVector())
6121       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6122     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6123   }
6124
6125   // Let legalizer expand 2-wide build_vectors.
6126   if (EVTBits == 64) {
6127     if (NumNonZero == 1) {
6128       // One half is zero or undef.
6129       unsigned Idx = countTrailingZeros(NonZeros);
6130       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6131                                  Op.getOperand(Idx));
6132       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6133     }
6134     return SDValue();
6135   }
6136
6137   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6138   if (EVTBits == 8 && NumElems == 16) {
6139     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6140                                         Subtarget, *this);
6141     if (V.getNode()) return V;
6142   }
6143
6144   if (EVTBits == 16 && NumElems == 8) {
6145     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6146                                       Subtarget, *this);
6147     if (V.getNode()) return V;
6148   }
6149
6150   // If element VT is == 32 bits, turn it into a number of shuffles.
6151   SmallVector<SDValue, 8> V(NumElems);
6152   if (NumElems == 4 && NumZero > 0) {
6153     for (unsigned i = 0; i < 4; ++i) {
6154       bool isZero = !(NonZeros & (1 << i));
6155       if (isZero)
6156         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6157       else
6158         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6159     }
6160
6161     for (unsigned i = 0; i < 2; ++i) {
6162       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6163         default: break;
6164         case 0:
6165           V[i] = V[i*2];  // Must be a zero vector.
6166           break;
6167         case 1:
6168           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6169           break;
6170         case 2:
6171           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6172           break;
6173         case 3:
6174           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6175           break;
6176       }
6177     }
6178
6179     bool Reverse1 = (NonZeros & 0x3) == 2;
6180     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6181     int MaskVec[] = {
6182       Reverse1 ? 1 : 0,
6183       Reverse1 ? 0 : 1,
6184       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6185       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6186     };
6187     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6188   }
6189
6190   if (Values.size() > 1 && VT.is128BitVector()) {
6191     // Check for a build vector of consecutive loads.
6192     for (unsigned i = 0; i < NumElems; ++i)
6193       V[i] = Op.getOperand(i);
6194
6195     // Check for elements which are consecutive loads.
6196     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6197     if (LD.getNode())
6198       return LD;
6199
6200     // Check for a build vector from mostly shuffle plus few inserting.
6201     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6202     if (Sh.getNode())
6203       return Sh;
6204
6205     // For SSE 4.1, use insertps to put the high elements into the low element.
6206     if (getSubtarget()->hasSSE41()) {
6207       SDValue Result;
6208       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6209         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6210       else
6211         Result = DAG.getUNDEF(VT);
6212
6213       for (unsigned i = 1; i < NumElems; ++i) {
6214         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6215         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6216                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6217       }
6218       return Result;
6219     }
6220
6221     // Otherwise, expand into a number of unpckl*, start by extending each of
6222     // our (non-undef) elements to the full vector width with the element in the
6223     // bottom slot of the vector (which generates no code for SSE).
6224     for (unsigned i = 0; i < NumElems; ++i) {
6225       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6226         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6227       else
6228         V[i] = DAG.getUNDEF(VT);
6229     }
6230
6231     // Next, we iteratively mix elements, e.g. for v4f32:
6232     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6233     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6234     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6235     unsigned EltStride = NumElems >> 1;
6236     while (EltStride != 0) {
6237       for (unsigned i = 0; i < EltStride; ++i) {
6238         // If V[i+EltStride] is undef and this is the first round of mixing,
6239         // then it is safe to just drop this shuffle: V[i] is already in the
6240         // right place, the one element (since it's the first round) being
6241         // inserted as undef can be dropped.  This isn't safe for successive
6242         // rounds because they will permute elements within both vectors.
6243         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6244             EltStride == NumElems/2)
6245           continue;
6246
6247         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6248       }
6249       EltStride >>= 1;
6250     }
6251     return V[0];
6252   }
6253   return SDValue();
6254 }
6255
6256 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6257 // to create 256-bit vectors from two other 128-bit ones.
6258 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6259   SDLoc dl(Op);
6260   MVT ResVT = Op.getSimpleValueType();
6261
6262   assert((ResVT.is256BitVector() ||
6263           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6264
6265   SDValue V1 = Op.getOperand(0);
6266   SDValue V2 = Op.getOperand(1);
6267   unsigned NumElems = ResVT.getVectorNumElements();
6268   if(ResVT.is256BitVector())
6269     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6270
6271   if (Op.getNumOperands() == 4) {
6272     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6273                                 ResVT.getVectorNumElements()/2);
6274     SDValue V3 = Op.getOperand(2);
6275     SDValue V4 = Op.getOperand(3);
6276     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6277       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6278   }
6279   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6280 }
6281
6282 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6283   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6284   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6285          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6286           Op.getNumOperands() == 4)));
6287
6288   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6289   // from two other 128-bit ones.
6290
6291   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6292   return LowerAVXCONCAT_VECTORS(Op, DAG);
6293 }
6294
6295 // Try to lower a shuffle node into a simple blend instruction.
6296 static SDValue
6297 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6298                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6299   SDValue V1 = SVOp->getOperand(0);
6300   SDValue V2 = SVOp->getOperand(1);
6301   SDLoc dl(SVOp);
6302   MVT VT = SVOp->getSimpleValueType(0);
6303   MVT EltVT = VT.getVectorElementType();
6304   unsigned NumElems = VT.getVectorNumElements();
6305
6306   // There is no blend with immediate in AVX-512.
6307   if (VT.is512BitVector())
6308     return SDValue();
6309
6310   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
6311     return SDValue();
6312   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
6313     return SDValue();
6314
6315   // Check the mask for BLEND and build the value.
6316   unsigned MaskValue = 0;
6317   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6318   unsigned NumLanes = (NumElems-1)/8 + 1;
6319   unsigned NumElemsInLane = NumElems / NumLanes;
6320
6321   // Blend for v16i16 should be symetric for the both lanes.
6322   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6323
6324     int SndLaneEltIdx = (NumLanes == 2) ?
6325       SVOp->getMaskElt(i + NumElemsInLane) : -1;
6326     int EltIdx = SVOp->getMaskElt(i);
6327
6328     if ((EltIdx < 0 || EltIdx == (int)i) &&
6329         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6330       continue;
6331
6332     if (((unsigned)EltIdx == (i + NumElems)) &&
6333         (SndLaneEltIdx < 0 ||
6334          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6335       MaskValue |= (1<<i);
6336     else
6337       return SDValue();
6338   }
6339
6340   // Convert i32 vectors to floating point if it is not AVX2.
6341   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6342   MVT BlendVT = VT;
6343   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6344     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6345                                NumElems);
6346     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6347     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6348   }
6349
6350   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6351                             DAG.getConstant(MaskValue, MVT::i32));
6352   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6353 }
6354
6355 /// In vector type \p VT, return true if the element at index \p InputIdx
6356 /// falls on a different 128-bit lane than \p OutputIdx.
6357 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6358                                      unsigned OutputIdx) {
6359   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6360   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6361 }
6362
6363 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6364 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6365 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6366 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6367 /// zero.
6368 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6369                          SelectionDAG &DAG) {
6370   MVT VT = V1.getSimpleValueType();
6371   assert(VT.is128BitVector() || VT.is256BitVector());
6372
6373   MVT EltVT = VT.getVectorElementType();
6374   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6375   unsigned NumElts = VT.getVectorNumElements();
6376
6377   SmallVector<SDValue, 32> PshufbMask;
6378   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6379     int InputIdx = MaskVals[OutputIdx];
6380     unsigned InputByteIdx;
6381
6382     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6383       InputByteIdx = 0x80;
6384     else {
6385       // Cross lane is not allowed.
6386       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6387         return SDValue();
6388       InputByteIdx = InputIdx * EltSizeInBytes;
6389       // Index is an byte offset within the 128-bit lane.
6390       InputByteIdx &= 0xf;
6391     }
6392
6393     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6394       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6395       if (InputByteIdx != 0x80)
6396         ++InputByteIdx;
6397     }
6398   }
6399
6400   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6401   if (ShufVT != VT)
6402     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6403   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6404                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6405 }
6406
6407 // v8i16 shuffles - Prefer shuffles in the following order:
6408 // 1. [all]   pshuflw, pshufhw, optional move
6409 // 2. [ssse3] 1 x pshufb
6410 // 3. [ssse3] 2 x pshufb + 1 x por
6411 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6412 static SDValue
6413 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6414                          SelectionDAG &DAG) {
6415   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6416   SDValue V1 = SVOp->getOperand(0);
6417   SDValue V2 = SVOp->getOperand(1);
6418   SDLoc dl(SVOp);
6419   SmallVector<int, 8> MaskVals;
6420
6421   // Determine if more than 1 of the words in each of the low and high quadwords
6422   // of the result come from the same quadword of one of the two inputs.  Undef
6423   // mask values count as coming from any quadword, for better codegen.
6424   //
6425   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6426   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6427   unsigned LoQuad[] = { 0, 0, 0, 0 };
6428   unsigned HiQuad[] = { 0, 0, 0, 0 };
6429   // Indices of quads used.
6430   std::bitset<4> InputQuads;
6431   for (unsigned i = 0; i < 8; ++i) {
6432     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6433     int EltIdx = SVOp->getMaskElt(i);
6434     MaskVals.push_back(EltIdx);
6435     if (EltIdx < 0) {
6436       ++Quad[0];
6437       ++Quad[1];
6438       ++Quad[2];
6439       ++Quad[3];
6440       continue;
6441     }
6442     ++Quad[EltIdx / 4];
6443     InputQuads.set(EltIdx / 4);
6444   }
6445
6446   int BestLoQuad = -1;
6447   unsigned MaxQuad = 1;
6448   for (unsigned i = 0; i < 4; ++i) {
6449     if (LoQuad[i] > MaxQuad) {
6450       BestLoQuad = i;
6451       MaxQuad = LoQuad[i];
6452     }
6453   }
6454
6455   int BestHiQuad = -1;
6456   MaxQuad = 1;
6457   for (unsigned i = 0; i < 4; ++i) {
6458     if (HiQuad[i] > MaxQuad) {
6459       BestHiQuad = i;
6460       MaxQuad = HiQuad[i];
6461     }
6462   }
6463
6464   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6465   // of the two input vectors, shuffle them into one input vector so only a
6466   // single pshufb instruction is necessary. If there are more than 2 input
6467   // quads, disable the next transformation since it does not help SSSE3.
6468   bool V1Used = InputQuads[0] || InputQuads[1];
6469   bool V2Used = InputQuads[2] || InputQuads[3];
6470   if (Subtarget->hasSSSE3()) {
6471     if (InputQuads.count() == 2 && V1Used && V2Used) {
6472       BestLoQuad = InputQuads[0] ? 0 : 1;
6473       BestHiQuad = InputQuads[2] ? 2 : 3;
6474     }
6475     if (InputQuads.count() > 2) {
6476       BestLoQuad = -1;
6477       BestHiQuad = -1;
6478     }
6479   }
6480
6481   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6482   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6483   // words from all 4 input quadwords.
6484   SDValue NewV;
6485   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6486     int MaskV[] = {
6487       BestLoQuad < 0 ? 0 : BestLoQuad,
6488       BestHiQuad < 0 ? 1 : BestHiQuad
6489     };
6490     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6491                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6492                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6493     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6494
6495     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6496     // source words for the shuffle, to aid later transformations.
6497     bool AllWordsInNewV = true;
6498     bool InOrder[2] = { true, true };
6499     for (unsigned i = 0; i != 8; ++i) {
6500       int idx = MaskVals[i];
6501       if (idx != (int)i)
6502         InOrder[i/4] = false;
6503       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6504         continue;
6505       AllWordsInNewV = false;
6506       break;
6507     }
6508
6509     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6510     if (AllWordsInNewV) {
6511       for (int i = 0; i != 8; ++i) {
6512         int idx = MaskVals[i];
6513         if (idx < 0)
6514           continue;
6515         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6516         if ((idx != i) && idx < 4)
6517           pshufhw = false;
6518         if ((idx != i) && idx > 3)
6519           pshuflw = false;
6520       }
6521       V1 = NewV;
6522       V2Used = false;
6523       BestLoQuad = 0;
6524       BestHiQuad = 1;
6525     }
6526
6527     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6528     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6529     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6530       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6531       unsigned TargetMask = 0;
6532       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6533                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6534       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6535       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6536                              getShufflePSHUFLWImmediate(SVOp);
6537       V1 = NewV.getOperand(0);
6538       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6539     }
6540   }
6541
6542   // Promote splats to a larger type which usually leads to more efficient code.
6543   // FIXME: Is this true if pshufb is available?
6544   if (SVOp->isSplat())
6545     return PromoteSplat(SVOp, DAG);
6546
6547   // If we have SSSE3, and all words of the result are from 1 input vector,
6548   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6549   // is present, fall back to case 4.
6550   if (Subtarget->hasSSSE3()) {
6551     SmallVector<SDValue,16> pshufbMask;
6552
6553     // If we have elements from both input vectors, set the high bit of the
6554     // shuffle mask element to zero out elements that come from V2 in the V1
6555     // mask, and elements that come from V1 in the V2 mask, so that the two
6556     // results can be OR'd together.
6557     bool TwoInputs = V1Used && V2Used;
6558     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6559     if (!TwoInputs)
6560       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6561
6562     // Calculate the shuffle mask for the second input, shuffle it, and
6563     // OR it with the first shuffled input.
6564     CommuteVectorShuffleMask(MaskVals, 8);
6565     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6566     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6567     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6568   }
6569
6570   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6571   // and update MaskVals with new element order.
6572   std::bitset<8> InOrder;
6573   if (BestLoQuad >= 0) {
6574     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6575     for (int i = 0; i != 4; ++i) {
6576       int idx = MaskVals[i];
6577       if (idx < 0) {
6578         InOrder.set(i);
6579       } else if ((idx / 4) == BestLoQuad) {
6580         MaskV[i] = idx & 3;
6581         InOrder.set(i);
6582       }
6583     }
6584     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6585                                 &MaskV[0]);
6586
6587     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6588       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6589       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6590                                   NewV.getOperand(0),
6591                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6592     }
6593   }
6594
6595   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6596   // and update MaskVals with the new element order.
6597   if (BestHiQuad >= 0) {
6598     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6599     for (unsigned i = 4; i != 8; ++i) {
6600       int idx = MaskVals[i];
6601       if (idx < 0) {
6602         InOrder.set(i);
6603       } else if ((idx / 4) == BestHiQuad) {
6604         MaskV[i] = (idx & 3) + 4;
6605         InOrder.set(i);
6606       }
6607     }
6608     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6609                                 &MaskV[0]);
6610
6611     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6612       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6613       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6614                                   NewV.getOperand(0),
6615                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6616     }
6617   }
6618
6619   // In case BestHi & BestLo were both -1, which means each quadword has a word
6620   // from each of the four input quadwords, calculate the InOrder bitvector now
6621   // before falling through to the insert/extract cleanup.
6622   if (BestLoQuad == -1 && BestHiQuad == -1) {
6623     NewV = V1;
6624     for (int i = 0; i != 8; ++i)
6625       if (MaskVals[i] < 0 || MaskVals[i] == i)
6626         InOrder.set(i);
6627   }
6628
6629   // The other elements are put in the right place using pextrw and pinsrw.
6630   for (unsigned i = 0; i != 8; ++i) {
6631     if (InOrder[i])
6632       continue;
6633     int EltIdx = MaskVals[i];
6634     if (EltIdx < 0)
6635       continue;
6636     SDValue ExtOp = (EltIdx < 8) ?
6637       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6638                   DAG.getIntPtrConstant(EltIdx)) :
6639       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6640                   DAG.getIntPtrConstant(EltIdx - 8));
6641     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6642                        DAG.getIntPtrConstant(i));
6643   }
6644   return NewV;
6645 }
6646
6647 /// \brief v16i16 shuffles
6648 ///
6649 /// FIXME: We only support generation of a single pshufb currently.  We can
6650 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6651 /// well (e.g 2 x pshufb + 1 x por).
6652 static SDValue
6653 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6654   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6655   SDValue V1 = SVOp->getOperand(0);
6656   SDValue V2 = SVOp->getOperand(1);
6657   SDLoc dl(SVOp);
6658
6659   if (V2.getOpcode() != ISD::UNDEF)
6660     return SDValue();
6661
6662   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6663   return getPSHUFB(MaskVals, V1, dl, DAG);
6664 }
6665
6666 // v16i8 shuffles - Prefer shuffles in the following order:
6667 // 1. [ssse3] 1 x pshufb
6668 // 2. [ssse3] 2 x pshufb + 1 x por
6669 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6670 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6671                                         const X86Subtarget* Subtarget,
6672                                         SelectionDAG &DAG) {
6673   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6674   SDValue V1 = SVOp->getOperand(0);
6675   SDValue V2 = SVOp->getOperand(1);
6676   SDLoc dl(SVOp);
6677   ArrayRef<int> MaskVals = SVOp->getMask();
6678
6679   // Promote splats to a larger type which usually leads to more efficient code.
6680   // FIXME: Is this true if pshufb is available?
6681   if (SVOp->isSplat())
6682     return PromoteSplat(SVOp, DAG);
6683
6684   // If we have SSSE3, case 1 is generated when all result bytes come from
6685   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6686   // present, fall back to case 3.
6687
6688   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6689   if (Subtarget->hasSSSE3()) {
6690     SmallVector<SDValue,16> pshufbMask;
6691
6692     // If all result elements are from one input vector, then only translate
6693     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6694     //
6695     // Otherwise, we have elements from both input vectors, and must zero out
6696     // elements that come from V2 in the first mask, and V1 in the second mask
6697     // so that we can OR them together.
6698     for (unsigned i = 0; i != 16; ++i) {
6699       int EltIdx = MaskVals[i];
6700       if (EltIdx < 0 || EltIdx >= 16)
6701         EltIdx = 0x80;
6702       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6703     }
6704     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6705                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6706                                  MVT::v16i8, pshufbMask));
6707
6708     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6709     // the 2nd operand if it's undefined or zero.
6710     if (V2.getOpcode() == ISD::UNDEF ||
6711         ISD::isBuildVectorAllZeros(V2.getNode()))
6712       return V1;
6713
6714     // Calculate the shuffle mask for the second input, shuffle it, and
6715     // OR it with the first shuffled input.
6716     pshufbMask.clear();
6717     for (unsigned i = 0; i != 16; ++i) {
6718       int EltIdx = MaskVals[i];
6719       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6720       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6721     }
6722     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6723                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6724                                  MVT::v16i8, pshufbMask));
6725     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6726   }
6727
6728   // No SSSE3 - Calculate in place words and then fix all out of place words
6729   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6730   // the 16 different words that comprise the two doublequadword input vectors.
6731   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6732   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6733   SDValue NewV = V1;
6734   for (int i = 0; i != 8; ++i) {
6735     int Elt0 = MaskVals[i*2];
6736     int Elt1 = MaskVals[i*2+1];
6737
6738     // This word of the result is all undef, skip it.
6739     if (Elt0 < 0 && Elt1 < 0)
6740       continue;
6741
6742     // This word of the result is already in the correct place, skip it.
6743     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6744       continue;
6745
6746     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6747     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6748     SDValue InsElt;
6749
6750     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6751     // using a single extract together, load it and store it.
6752     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6753       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6754                            DAG.getIntPtrConstant(Elt1 / 2));
6755       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6756                         DAG.getIntPtrConstant(i));
6757       continue;
6758     }
6759
6760     // If Elt1 is defined, extract it from the appropriate source.  If the
6761     // source byte is not also odd, shift the extracted word left 8 bits
6762     // otherwise clear the bottom 8 bits if we need to do an or.
6763     if (Elt1 >= 0) {
6764       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6765                            DAG.getIntPtrConstant(Elt1 / 2));
6766       if ((Elt1 & 1) == 0)
6767         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6768                              DAG.getConstant(8,
6769                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6770       else if (Elt0 >= 0)
6771         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6772                              DAG.getConstant(0xFF00, MVT::i16));
6773     }
6774     // If Elt0 is defined, extract it from the appropriate source.  If the
6775     // source byte is not also even, shift the extracted word right 8 bits. If
6776     // Elt1 was also defined, OR the extracted values together before
6777     // inserting them in the result.
6778     if (Elt0 >= 0) {
6779       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6780                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6781       if ((Elt0 & 1) != 0)
6782         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6783                               DAG.getConstant(8,
6784                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6785       else if (Elt1 >= 0)
6786         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6787                              DAG.getConstant(0x00FF, MVT::i16));
6788       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6789                          : InsElt0;
6790     }
6791     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6792                        DAG.getIntPtrConstant(i));
6793   }
6794   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6795 }
6796
6797 // v32i8 shuffles - Translate to VPSHUFB if possible.
6798 static
6799 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6800                                  const X86Subtarget *Subtarget,
6801                                  SelectionDAG &DAG) {
6802   MVT VT = SVOp->getSimpleValueType(0);
6803   SDValue V1 = SVOp->getOperand(0);
6804   SDValue V2 = SVOp->getOperand(1);
6805   SDLoc dl(SVOp);
6806   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6807
6808   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6809   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6810   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6811
6812   // VPSHUFB may be generated if
6813   // (1) one of input vector is undefined or zeroinitializer.
6814   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6815   // And (2) the mask indexes don't cross the 128-bit lane.
6816   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6817       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6818     return SDValue();
6819
6820   if (V1IsAllZero && !V2IsAllZero) {
6821     CommuteVectorShuffleMask(MaskVals, 32);
6822     V1 = V2;
6823   }
6824   return getPSHUFB(MaskVals, V1, dl, DAG);
6825 }
6826
6827 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6828 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6829 /// done when every pair / quad of shuffle mask elements point to elements in
6830 /// the right sequence. e.g.
6831 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6832 static
6833 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6834                                  SelectionDAG &DAG) {
6835   MVT VT = SVOp->getSimpleValueType(0);
6836   SDLoc dl(SVOp);
6837   unsigned NumElems = VT.getVectorNumElements();
6838   MVT NewVT;
6839   unsigned Scale;
6840   switch (VT.SimpleTy) {
6841   default: llvm_unreachable("Unexpected!");
6842   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6843   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6844   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6845   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6846   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6847   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6848   }
6849
6850   SmallVector<int, 8> MaskVec;
6851   for (unsigned i = 0; i != NumElems; i += Scale) {
6852     int StartIdx = -1;
6853     for (unsigned j = 0; j != Scale; ++j) {
6854       int EltIdx = SVOp->getMaskElt(i+j);
6855       if (EltIdx < 0)
6856         continue;
6857       if (StartIdx < 0)
6858         StartIdx = (EltIdx / Scale);
6859       if (EltIdx != (int)(StartIdx*Scale + j))
6860         return SDValue();
6861     }
6862     MaskVec.push_back(StartIdx);
6863   }
6864
6865   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6866   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6867   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6868 }
6869
6870 /// getVZextMovL - Return a zero-extending vector move low node.
6871 ///
6872 static SDValue getVZextMovL(MVT VT, MVT OpVT,
6873                             SDValue SrcOp, SelectionDAG &DAG,
6874                             const X86Subtarget *Subtarget, SDLoc dl) {
6875   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6876     LoadSDNode *LD = nullptr;
6877     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6878       LD = dyn_cast<LoadSDNode>(SrcOp);
6879     if (!LD) {
6880       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6881       // instead.
6882       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6883       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6884           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6885           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6886           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6887         // PR2108
6888         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6889         return DAG.getNode(ISD::BITCAST, dl, VT,
6890                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6891                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6892                                                    OpVT,
6893                                                    SrcOp.getOperand(0)
6894                                                           .getOperand(0))));
6895       }
6896     }
6897   }
6898
6899   return DAG.getNode(ISD::BITCAST, dl, VT,
6900                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6901                                  DAG.getNode(ISD::BITCAST, dl,
6902                                              OpVT, SrcOp)));
6903 }
6904
6905 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6906 /// which could not be matched by any known target speficic shuffle
6907 static SDValue
6908 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6909
6910   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6911   if (NewOp.getNode())
6912     return NewOp;
6913
6914   MVT VT = SVOp->getSimpleValueType(0);
6915
6916   unsigned NumElems = VT.getVectorNumElements();
6917   unsigned NumLaneElems = NumElems / 2;
6918
6919   SDLoc dl(SVOp);
6920   MVT EltVT = VT.getVectorElementType();
6921   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6922   SDValue Output[2];
6923
6924   SmallVector<int, 16> Mask;
6925   for (unsigned l = 0; l < 2; ++l) {
6926     // Build a shuffle mask for the output, discovering on the fly which
6927     // input vectors to use as shuffle operands (recorded in InputUsed).
6928     // If building a suitable shuffle vector proves too hard, then bail
6929     // out with UseBuildVector set.
6930     bool UseBuildVector = false;
6931     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6932     unsigned LaneStart = l * NumLaneElems;
6933     for (unsigned i = 0; i != NumLaneElems; ++i) {
6934       // The mask element.  This indexes into the input.
6935       int Idx = SVOp->getMaskElt(i+LaneStart);
6936       if (Idx < 0) {
6937         // the mask element does not index into any input vector.
6938         Mask.push_back(-1);
6939         continue;
6940       }
6941
6942       // The input vector this mask element indexes into.
6943       int Input = Idx / NumLaneElems;
6944
6945       // Turn the index into an offset from the start of the input vector.
6946       Idx -= Input * NumLaneElems;
6947
6948       // Find or create a shuffle vector operand to hold this input.
6949       unsigned OpNo;
6950       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6951         if (InputUsed[OpNo] == Input)
6952           // This input vector is already an operand.
6953           break;
6954         if (InputUsed[OpNo] < 0) {
6955           // Create a new operand for this input vector.
6956           InputUsed[OpNo] = Input;
6957           break;
6958         }
6959       }
6960
6961       if (OpNo >= array_lengthof(InputUsed)) {
6962         // More than two input vectors used!  Give up on trying to create a
6963         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6964         UseBuildVector = true;
6965         break;
6966       }
6967
6968       // Add the mask index for the new shuffle vector.
6969       Mask.push_back(Idx + OpNo * NumLaneElems);
6970     }
6971
6972     if (UseBuildVector) {
6973       SmallVector<SDValue, 16> SVOps;
6974       for (unsigned i = 0; i != NumLaneElems; ++i) {
6975         // The mask element.  This indexes into the input.
6976         int Idx = SVOp->getMaskElt(i+LaneStart);
6977         if (Idx < 0) {
6978           SVOps.push_back(DAG.getUNDEF(EltVT));
6979           continue;
6980         }
6981
6982         // The input vector this mask element indexes into.
6983         int Input = Idx / NumElems;
6984
6985         // Turn the index into an offset from the start of the input vector.
6986         Idx -= Input * NumElems;
6987
6988         // Extract the vector element by hand.
6989         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6990                                     SVOp->getOperand(Input),
6991                                     DAG.getIntPtrConstant(Idx)));
6992       }
6993
6994       // Construct the output using a BUILD_VECTOR.
6995       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
6996     } else if (InputUsed[0] < 0) {
6997       // No input vectors were used! The result is undefined.
6998       Output[l] = DAG.getUNDEF(NVT);
6999     } else {
7000       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7001                                         (InputUsed[0] % 2) * NumLaneElems,
7002                                         DAG, dl);
7003       // If only one input was used, use an undefined vector for the other.
7004       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7005         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7006                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7007       // At least one input vector was used. Create a new shuffle vector.
7008       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7009     }
7010
7011     Mask.clear();
7012   }
7013
7014   // Concatenate the result back
7015   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7016 }
7017
7018 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7019 /// 4 elements, and match them with several different shuffle types.
7020 static SDValue
7021 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7022   SDValue V1 = SVOp->getOperand(0);
7023   SDValue V2 = SVOp->getOperand(1);
7024   SDLoc dl(SVOp);
7025   MVT VT = SVOp->getSimpleValueType(0);
7026
7027   assert(VT.is128BitVector() && "Unsupported vector size");
7028
7029   std::pair<int, int> Locs[4];
7030   int Mask1[] = { -1, -1, -1, -1 };
7031   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7032
7033   unsigned NumHi = 0;
7034   unsigned NumLo = 0;
7035   for (unsigned i = 0; i != 4; ++i) {
7036     int Idx = PermMask[i];
7037     if (Idx < 0) {
7038       Locs[i] = std::make_pair(-1, -1);
7039     } else {
7040       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7041       if (Idx < 4) {
7042         Locs[i] = std::make_pair(0, NumLo);
7043         Mask1[NumLo] = Idx;
7044         NumLo++;
7045       } else {
7046         Locs[i] = std::make_pair(1, NumHi);
7047         if (2+NumHi < 4)
7048           Mask1[2+NumHi] = Idx;
7049         NumHi++;
7050       }
7051     }
7052   }
7053
7054   if (NumLo <= 2 && NumHi <= 2) {
7055     // If no more than two elements come from either vector. This can be
7056     // implemented with two shuffles. First shuffle gather the elements.
7057     // The second shuffle, which takes the first shuffle as both of its
7058     // vector operands, put the elements into the right order.
7059     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7060
7061     int Mask2[] = { -1, -1, -1, -1 };
7062
7063     for (unsigned i = 0; i != 4; ++i)
7064       if (Locs[i].first != -1) {
7065         unsigned Idx = (i < 2) ? 0 : 4;
7066         Idx += Locs[i].first * 2 + Locs[i].second;
7067         Mask2[i] = Idx;
7068       }
7069
7070     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7071   }
7072
7073   if (NumLo == 3 || NumHi == 3) {
7074     // Otherwise, we must have three elements from one vector, call it X, and
7075     // one element from the other, call it Y.  First, use a shufps to build an
7076     // intermediate vector with the one element from Y and the element from X
7077     // that will be in the same half in the final destination (the indexes don't
7078     // matter). Then, use a shufps to build the final vector, taking the half
7079     // containing the element from Y from the intermediate, and the other half
7080     // from X.
7081     if (NumHi == 3) {
7082       // Normalize it so the 3 elements come from V1.
7083       CommuteVectorShuffleMask(PermMask, 4);
7084       std::swap(V1, V2);
7085     }
7086
7087     // Find the element from V2.
7088     unsigned HiIndex;
7089     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7090       int Val = PermMask[HiIndex];
7091       if (Val < 0)
7092         continue;
7093       if (Val >= 4)
7094         break;
7095     }
7096
7097     Mask1[0] = PermMask[HiIndex];
7098     Mask1[1] = -1;
7099     Mask1[2] = PermMask[HiIndex^1];
7100     Mask1[3] = -1;
7101     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7102
7103     if (HiIndex >= 2) {
7104       Mask1[0] = PermMask[0];
7105       Mask1[1] = PermMask[1];
7106       Mask1[2] = HiIndex & 1 ? 6 : 4;
7107       Mask1[3] = HiIndex & 1 ? 4 : 6;
7108       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7109     }
7110
7111     Mask1[0] = HiIndex & 1 ? 2 : 0;
7112     Mask1[1] = HiIndex & 1 ? 0 : 2;
7113     Mask1[2] = PermMask[2];
7114     Mask1[3] = PermMask[3];
7115     if (Mask1[2] >= 0)
7116       Mask1[2] += 4;
7117     if (Mask1[3] >= 0)
7118       Mask1[3] += 4;
7119     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7120   }
7121
7122   // Break it into (shuffle shuffle_hi, shuffle_lo).
7123   int LoMask[] = { -1, -1, -1, -1 };
7124   int HiMask[] = { -1, -1, -1, -1 };
7125
7126   int *MaskPtr = LoMask;
7127   unsigned MaskIdx = 0;
7128   unsigned LoIdx = 0;
7129   unsigned HiIdx = 2;
7130   for (unsigned i = 0; i != 4; ++i) {
7131     if (i == 2) {
7132       MaskPtr = HiMask;
7133       MaskIdx = 1;
7134       LoIdx = 0;
7135       HiIdx = 2;
7136     }
7137     int Idx = PermMask[i];
7138     if (Idx < 0) {
7139       Locs[i] = std::make_pair(-1, -1);
7140     } else if (Idx < 4) {
7141       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7142       MaskPtr[LoIdx] = Idx;
7143       LoIdx++;
7144     } else {
7145       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7146       MaskPtr[HiIdx] = Idx;
7147       HiIdx++;
7148     }
7149   }
7150
7151   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7152   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7153   int MaskOps[] = { -1, -1, -1, -1 };
7154   for (unsigned i = 0; i != 4; ++i)
7155     if (Locs[i].first != -1)
7156       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7157   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7158 }
7159
7160 static bool MayFoldVectorLoad(SDValue V) {
7161   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7162     V = V.getOperand(0);
7163
7164   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7165     V = V.getOperand(0);
7166   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7167       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7168     // BUILD_VECTOR (load), undef
7169     V = V.getOperand(0);
7170
7171   return MayFoldLoad(V);
7172 }
7173
7174 static
7175 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7176   MVT VT = Op.getSimpleValueType();
7177
7178   // Canonizalize to v2f64.
7179   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7180   return DAG.getNode(ISD::BITCAST, dl, VT,
7181                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7182                                           V1, DAG));
7183 }
7184
7185 static
7186 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7187                         bool HasSSE2) {
7188   SDValue V1 = Op.getOperand(0);
7189   SDValue V2 = Op.getOperand(1);
7190   MVT VT = Op.getSimpleValueType();
7191
7192   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7193
7194   if (HasSSE2 && VT == MVT::v2f64)
7195     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7196
7197   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7198   return DAG.getNode(ISD::BITCAST, dl, VT,
7199                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7200                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7201                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7202 }
7203
7204 static
7205 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7206   SDValue V1 = Op.getOperand(0);
7207   SDValue V2 = Op.getOperand(1);
7208   MVT VT = Op.getSimpleValueType();
7209
7210   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7211          "unsupported shuffle type");
7212
7213   if (V2.getOpcode() == ISD::UNDEF)
7214     V2 = V1;
7215
7216   // v4i32 or v4f32
7217   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7218 }
7219
7220 static
7221 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7222   SDValue V1 = Op.getOperand(0);
7223   SDValue V2 = Op.getOperand(1);
7224   MVT VT = Op.getSimpleValueType();
7225   unsigned NumElems = VT.getVectorNumElements();
7226
7227   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7228   // operand of these instructions is only memory, so check if there's a
7229   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7230   // same masks.
7231   bool CanFoldLoad = false;
7232
7233   // Trivial case, when V2 comes from a load.
7234   if (MayFoldVectorLoad(V2))
7235     CanFoldLoad = true;
7236
7237   // When V1 is a load, it can be folded later into a store in isel, example:
7238   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7239   //    turns into:
7240   //  (MOVLPSmr addr:$src1, VR128:$src2)
7241   // So, recognize this potential and also use MOVLPS or MOVLPD
7242   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7243     CanFoldLoad = true;
7244
7245   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7246   if (CanFoldLoad) {
7247     if (HasSSE2 && NumElems == 2)
7248       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7249
7250     if (NumElems == 4)
7251       // If we don't care about the second element, proceed to use movss.
7252       if (SVOp->getMaskElt(1) != -1)
7253         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7254   }
7255
7256   // movl and movlp will both match v2i64, but v2i64 is never matched by
7257   // movl earlier because we make it strict to avoid messing with the movlp load
7258   // folding logic (see the code above getMOVLP call). Match it here then,
7259   // this is horrible, but will stay like this until we move all shuffle
7260   // matching to x86 specific nodes. Note that for the 1st condition all
7261   // types are matched with movsd.
7262   if (HasSSE2) {
7263     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7264     // as to remove this logic from here, as much as possible
7265     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7266       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7267     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7268   }
7269
7270   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7271
7272   // Invert the operand order and use SHUFPS to match it.
7273   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7274                               getShuffleSHUFImmediate(SVOp), DAG);
7275 }
7276
7277 // It is only safe to call this function if isINSERTPSMask is true for
7278 // this shufflevector mask.
7279 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7280                            SelectionDAG &DAG) {
7281   // Generate an insertps instruction when inserting an f32 from memory onto a
7282   // v4f32 or when copying a member from one v4f32 to another.
7283   // We also use it for transferring i32 from one register to another,
7284   // since it simply copies the same bits.
7285   // If we're transfering an i32 from memory to a specific element in a
7286   // register, we output a generic DAG that will match the PINSRD
7287   // instruction.
7288   // TODO: Optimize for AVX cases too (VINSERTPS)
7289   MVT VT = SVOp->getSimpleValueType(0);
7290   MVT EVT = VT.getVectorElementType();
7291   SDValue V1 = SVOp->getOperand(0);
7292   SDValue V2 = SVOp->getOperand(1);
7293   auto Mask = SVOp->getMask();
7294   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7295          "unsupported vector type for insertps/pinsrd");
7296
7297   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7298                              [](const int &i) { return i < 4; });
7299
7300   SDValue From;
7301   SDValue To;
7302   unsigned DestIndex;
7303   if (FromV1 == 1) {
7304     From = V1;
7305     To = V2;
7306     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7307                              [](const int &i) { return i < 4; }) -
7308                 Mask.begin();
7309   } else {
7310     From = V2;
7311     To = V1;
7312     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7313                              [](const int &i) { return i >= 4; }) -
7314                 Mask.begin();
7315   }
7316
7317   if (MayFoldLoad(From)) {
7318     // Trivial case, when From comes from a load and is only used by the
7319     // shuffle. Make it use insertps from the vector that we need from that
7320     // load.
7321     SDValue Addr = From.getOperand(1);
7322     SDValue NewAddr =
7323         DAG.getNode(ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7324                     DAG.getConstant(DestIndex * EVT.getStoreSize(),
7325                                     Addr.getSimpleValueType()));
7326
7327     LoadSDNode *Load = cast<LoadSDNode>(From);
7328     SDValue NewLoad =
7329         DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7330                     DAG.getMachineFunction().getMachineMemOperand(
7331                         Load->getMemOperand(), 0, EVT.getStoreSize()));
7332
7333     if (EVT == MVT::f32) {
7334       // Create this as a scalar to vector to match the instruction pattern.
7335       SDValue LoadScalarToVector =
7336           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7337       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7338       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7339                          InsertpsMask);
7340     } else { // EVT == MVT::i32
7341       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7342       // instruction, to match the PINSRD instruction, which loads an i32 to a
7343       // certain vector element.
7344       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7345                          DAG.getConstant(DestIndex, MVT::i32));
7346     }
7347   }
7348
7349   // Vector-element-to-vector
7350   unsigned SrcIndex = Mask[DestIndex] % 4;
7351   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7352   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7353 }
7354
7355 // Reduce a vector shuffle to zext.
7356 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7357                                     SelectionDAG &DAG) {
7358   // PMOVZX is only available from SSE41.
7359   if (!Subtarget->hasSSE41())
7360     return SDValue();
7361
7362   MVT VT = Op.getSimpleValueType();
7363
7364   // Only AVX2 support 256-bit vector integer extending.
7365   if (!Subtarget->hasInt256() && VT.is256BitVector())
7366     return SDValue();
7367
7368   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7369   SDLoc DL(Op);
7370   SDValue V1 = Op.getOperand(0);
7371   SDValue V2 = Op.getOperand(1);
7372   unsigned NumElems = VT.getVectorNumElements();
7373
7374   // Extending is an unary operation and the element type of the source vector
7375   // won't be equal to or larger than i64.
7376   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7377       VT.getVectorElementType() == MVT::i64)
7378     return SDValue();
7379
7380   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7381   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7382   while ((1U << Shift) < NumElems) {
7383     if (SVOp->getMaskElt(1U << Shift) == 1)
7384       break;
7385     Shift += 1;
7386     // The maximal ratio is 8, i.e. from i8 to i64.
7387     if (Shift > 3)
7388       return SDValue();
7389   }
7390
7391   // Check the shuffle mask.
7392   unsigned Mask = (1U << Shift) - 1;
7393   for (unsigned i = 0; i != NumElems; ++i) {
7394     int EltIdx = SVOp->getMaskElt(i);
7395     if ((i & Mask) != 0 && EltIdx != -1)
7396       return SDValue();
7397     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7398       return SDValue();
7399   }
7400
7401   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7402   MVT NeVT = MVT::getIntegerVT(NBits);
7403   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7404
7405   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7406     return SDValue();
7407
7408   // Simplify the operand as it's prepared to be fed into shuffle.
7409   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7410   if (V1.getOpcode() == ISD::BITCAST &&
7411       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7412       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7413       V1.getOperand(0).getOperand(0)
7414         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7415     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7416     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7417     ConstantSDNode *CIdx =
7418       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7419     // If it's foldable, i.e. normal load with single use, we will let code
7420     // selection to fold it. Otherwise, we will short the conversion sequence.
7421     if (CIdx && CIdx->getZExtValue() == 0 &&
7422         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7423       MVT FullVT = V.getSimpleValueType();
7424       MVT V1VT = V1.getSimpleValueType();
7425       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7426         // The "ext_vec_elt" node is wider than the result node.
7427         // In this case we should extract subvector from V.
7428         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7429         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7430         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7431                                         FullVT.getVectorNumElements()/Ratio);
7432         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7433                         DAG.getIntPtrConstant(0));
7434       }
7435       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7436     }
7437   }
7438
7439   return DAG.getNode(ISD::BITCAST, DL, VT,
7440                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7441 }
7442
7443 static SDValue
7444 NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7445                        SelectionDAG &DAG) {
7446   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7447   MVT VT = Op.getSimpleValueType();
7448   SDLoc dl(Op);
7449   SDValue V1 = Op.getOperand(0);
7450   SDValue V2 = Op.getOperand(1);
7451
7452   if (isZeroShuffle(SVOp))
7453     return getZeroVector(VT, Subtarget, DAG, dl);
7454
7455   // Handle splat operations
7456   if (SVOp->isSplat()) {
7457     // Use vbroadcast whenever the splat comes from a foldable load
7458     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7459     if (Broadcast.getNode())
7460       return Broadcast;
7461   }
7462
7463   // Check integer expanding shuffles.
7464   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7465   if (NewOp.getNode())
7466     return NewOp;
7467
7468   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7469   // do it!
7470   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
7471       VT == MVT::v16i16 || VT == MVT::v32i8) {
7472     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7473     if (NewOp.getNode())
7474       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7475   } else if ((VT == MVT::v4i32 ||
7476              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
7477     // FIXME: Figure out a cleaner way to do this.
7478     // Try to make use of movq to zero out the top part.
7479     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7480       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7481       if (NewOp.getNode()) {
7482         MVT NewVT = NewOp.getSimpleValueType();
7483         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7484                                NewVT, true, false))
7485           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
7486                               DAG, Subtarget, dl);
7487       }
7488     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7489       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7490       if (NewOp.getNode()) {
7491         MVT NewVT = NewOp.getSimpleValueType();
7492         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7493           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
7494                               DAG, Subtarget, dl);
7495       }
7496     }
7497   }
7498   return SDValue();
7499 }
7500
7501 SDValue
7502 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7503   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7504   SDValue V1 = Op.getOperand(0);
7505   SDValue V2 = Op.getOperand(1);
7506   MVT VT = Op.getSimpleValueType();
7507   SDLoc dl(Op);
7508   unsigned NumElems = VT.getVectorNumElements();
7509   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7510   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7511   bool V1IsSplat = false;
7512   bool V2IsSplat = false;
7513   bool HasSSE2 = Subtarget->hasSSE2();
7514   bool HasFp256    = Subtarget->hasFp256();
7515   bool HasInt256   = Subtarget->hasInt256();
7516   MachineFunction &MF = DAG.getMachineFunction();
7517   bool OptForSize = MF.getFunction()->getAttributes().
7518     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7519
7520   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7521
7522   if (V1IsUndef && V2IsUndef)
7523     return DAG.getUNDEF(VT);
7524
7525   // When we create a shuffle node we put the UNDEF node to second operand,
7526   // but in some cases the first operand may be transformed to UNDEF.
7527   // In this case we should just commute the node.
7528   if (V1IsUndef)
7529     return CommuteVectorShuffle(SVOp, DAG);
7530
7531   // Vector shuffle lowering takes 3 steps:
7532   //
7533   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7534   //    narrowing and commutation of operands should be handled.
7535   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7536   //    shuffle nodes.
7537   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7538   //    so the shuffle can be broken into other shuffles and the legalizer can
7539   //    try the lowering again.
7540   //
7541   // The general idea is that no vector_shuffle operation should be left to
7542   // be matched during isel, all of them must be converted to a target specific
7543   // node here.
7544
7545   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7546   // narrowing and commutation of operands should be handled. The actual code
7547   // doesn't include all of those, work in progress...
7548   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7549   if (NewOp.getNode())
7550     return NewOp;
7551
7552   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7553
7554   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7555   // unpckh_undef). Only use pshufd if speed is more important than size.
7556   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7557     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7558   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7559     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7560
7561   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7562       V2IsUndef && MayFoldVectorLoad(V1))
7563     return getMOVDDup(Op, dl, V1, DAG);
7564
7565   if (isMOVHLPS_v_undef_Mask(M, VT))
7566     return getMOVHighToLow(Op, dl, DAG);
7567
7568   // Use to match splats
7569   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7570       (VT == MVT::v2f64 || VT == MVT::v2i64))
7571     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7572
7573   if (isPSHUFDMask(M, VT)) {
7574     // The actual implementation will match the mask in the if above and then
7575     // during isel it can match several different instructions, not only pshufd
7576     // as its name says, sad but true, emulate the behavior for now...
7577     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7578       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7579
7580     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7581
7582     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7583       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7584
7585     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7586       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7587                                   DAG);
7588
7589     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7590                                 TargetMask, DAG);
7591   }
7592
7593   if (isPALIGNRMask(M, VT, Subtarget))
7594     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7595                                 getShufflePALIGNRImmediate(SVOp),
7596                                 DAG);
7597
7598   // Check if this can be converted into a logical shift.
7599   bool isLeft = false;
7600   unsigned ShAmt = 0;
7601   SDValue ShVal;
7602   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7603   if (isShift && ShVal.hasOneUse()) {
7604     // If the shifted value has multiple uses, it may be cheaper to use
7605     // v_set0 + movlhps or movhlps, etc.
7606     MVT EltVT = VT.getVectorElementType();
7607     ShAmt *= EltVT.getSizeInBits();
7608     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7609   }
7610
7611   if (isMOVLMask(M, VT)) {
7612     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7613       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7614     if (!isMOVLPMask(M, VT)) {
7615       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7616         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7617
7618       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7619         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7620     }
7621   }
7622
7623   // FIXME: fold these into legal mask.
7624   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7625     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7626
7627   if (isMOVHLPSMask(M, VT))
7628     return getMOVHighToLow(Op, dl, DAG);
7629
7630   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7631     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7632
7633   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7634     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7635
7636   if (isMOVLPMask(M, VT))
7637     return getMOVLP(Op, dl, DAG, HasSSE2);
7638
7639   if (ShouldXformToMOVHLPS(M, VT) ||
7640       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7641     return CommuteVectorShuffle(SVOp, DAG);
7642
7643   if (isShift) {
7644     // No better options. Use a vshldq / vsrldq.
7645     MVT EltVT = VT.getVectorElementType();
7646     ShAmt *= EltVT.getSizeInBits();
7647     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7648   }
7649
7650   bool Commuted = false;
7651   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7652   // 1,1,1,1 -> v8i16 though.
7653   V1IsSplat = isSplatVector(V1.getNode());
7654   V2IsSplat = isSplatVector(V2.getNode());
7655
7656   // Canonicalize the splat or undef, if present, to be on the RHS.
7657   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7658     CommuteVectorShuffleMask(M, NumElems);
7659     std::swap(V1, V2);
7660     std::swap(V1IsSplat, V2IsSplat);
7661     Commuted = true;
7662   }
7663
7664   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7665     // Shuffling low element of v1 into undef, just return v1.
7666     if (V2IsUndef)
7667       return V1;
7668     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7669     // the instruction selector will not match, so get a canonical MOVL with
7670     // swapped operands to undo the commute.
7671     return getMOVL(DAG, dl, VT, V2, V1);
7672   }
7673
7674   if (isUNPCKLMask(M, VT, HasInt256))
7675     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7676
7677   if (isUNPCKHMask(M, VT, HasInt256))
7678     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7679
7680   if (V2IsSplat) {
7681     // Normalize mask so all entries that point to V2 points to its first
7682     // element then try to match unpck{h|l} again. If match, return a
7683     // new vector_shuffle with the corrected mask.p
7684     SmallVector<int, 8> NewMask(M.begin(), M.end());
7685     NormalizeMask(NewMask, NumElems);
7686     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7687       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7688     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7689       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7690   }
7691
7692   if (Commuted) {
7693     // Commute is back and try unpck* again.
7694     // FIXME: this seems wrong.
7695     CommuteVectorShuffleMask(M, NumElems);
7696     std::swap(V1, V2);
7697     std::swap(V1IsSplat, V2IsSplat);
7698
7699     if (isUNPCKLMask(M, VT, HasInt256))
7700       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7701
7702     if (isUNPCKHMask(M, VT, HasInt256))
7703       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7704   }
7705
7706   // Normalize the node to match x86 shuffle ops if needed
7707   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7708     return CommuteVectorShuffle(SVOp, DAG);
7709
7710   // The checks below are all present in isShuffleMaskLegal, but they are
7711   // inlined here right now to enable us to directly emit target specific
7712   // nodes, and remove one by one until they don't return Op anymore.
7713
7714   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7715       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7716     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7717       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7718   }
7719
7720   if (isPSHUFHWMask(M, VT, HasInt256))
7721     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7722                                 getShufflePSHUFHWImmediate(SVOp),
7723                                 DAG);
7724
7725   if (isPSHUFLWMask(M, VT, HasInt256))
7726     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7727                                 getShufflePSHUFLWImmediate(SVOp),
7728                                 DAG);
7729
7730   if (isSHUFPMask(M, VT))
7731     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7732                                 getShuffleSHUFImmediate(SVOp), DAG);
7733
7734   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7735     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7736   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7737     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7738
7739   //===--------------------------------------------------------------------===//
7740   // Generate target specific nodes for 128 or 256-bit shuffles only
7741   // supported in the AVX instruction set.
7742   //
7743
7744   // Handle VMOVDDUPY permutations
7745   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7746     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7747
7748   // Handle VPERMILPS/D* permutations
7749   if (isVPERMILPMask(M, VT)) {
7750     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7751       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7752                                   getShuffleSHUFImmediate(SVOp), DAG);
7753     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7754                                 getShuffleSHUFImmediate(SVOp), DAG);
7755   }
7756
7757   // Handle VPERM2F128/VPERM2I128 permutations
7758   if (isVPERM2X128Mask(M, VT, HasFp256))
7759     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7760                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7761
7762   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7763   if (BlendOp.getNode())
7764     return BlendOp;
7765
7766   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7767     return getINSERTPS(SVOp, dl, DAG);
7768
7769   unsigned Imm8;
7770   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7771     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7772
7773   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7774       VT.is512BitVector()) {
7775     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7776     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7777     SmallVector<SDValue, 16> permclMask;
7778     for (unsigned i = 0; i != NumElems; ++i) {
7779       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7780     }
7781
7782     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7783     if (V2IsUndef)
7784       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7785       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7786                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7787     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7788                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7789   }
7790
7791   //===--------------------------------------------------------------------===//
7792   // Since no target specific shuffle was selected for this generic one,
7793   // lower it into other known shuffles. FIXME: this isn't true yet, but
7794   // this is the plan.
7795   //
7796
7797   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7798   if (VT == MVT::v8i16) {
7799     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7800     if (NewOp.getNode())
7801       return NewOp;
7802   }
7803
7804   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7805     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7806     if (NewOp.getNode())
7807       return NewOp;
7808   }
7809
7810   if (VT == MVT::v16i8) {
7811     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7812     if (NewOp.getNode())
7813       return NewOp;
7814   }
7815
7816   if (VT == MVT::v32i8) {
7817     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7818     if (NewOp.getNode())
7819       return NewOp;
7820   }
7821
7822   // Handle all 128-bit wide vectors with 4 elements, and match them with
7823   // several different shuffle types.
7824   if (NumElems == 4 && VT.is128BitVector())
7825     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7826
7827   // Handle general 256-bit shuffles
7828   if (VT.is256BitVector())
7829     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7830
7831   return SDValue();
7832 }
7833
7834 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7835   MVT VT = Op.getSimpleValueType();
7836   SDLoc dl(Op);
7837
7838   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
7839     return SDValue();
7840
7841   if (VT.getSizeInBits() == 8) {
7842     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7843                                   Op.getOperand(0), Op.getOperand(1));
7844     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7845                                   DAG.getValueType(VT));
7846     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7847   }
7848
7849   if (VT.getSizeInBits() == 16) {
7850     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7851     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7852     if (Idx == 0)
7853       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7854                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7855                                      DAG.getNode(ISD::BITCAST, dl,
7856                                                  MVT::v4i32,
7857                                                  Op.getOperand(0)),
7858                                      Op.getOperand(1)));
7859     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7860                                   Op.getOperand(0), Op.getOperand(1));
7861     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7862                                   DAG.getValueType(VT));
7863     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7864   }
7865
7866   if (VT == MVT::f32) {
7867     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7868     // the result back to FR32 register. It's only worth matching if the
7869     // result has a single use which is a store or a bitcast to i32.  And in
7870     // the case of a store, it's not worth it if the index is a constant 0,
7871     // because a MOVSSmr can be used instead, which is smaller and faster.
7872     if (!Op.hasOneUse())
7873       return SDValue();
7874     SDNode *User = *Op.getNode()->use_begin();
7875     if ((User->getOpcode() != ISD::STORE ||
7876          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7877           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7878         (User->getOpcode() != ISD::BITCAST ||
7879          User->getValueType(0) != MVT::i32))
7880       return SDValue();
7881     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7882                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7883                                               Op.getOperand(0)),
7884                                               Op.getOperand(1));
7885     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7886   }
7887
7888   if (VT == MVT::i32 || VT == MVT::i64) {
7889     // ExtractPS/pextrq works with constant index.
7890     if (isa<ConstantSDNode>(Op.getOperand(1)))
7891       return Op;
7892   }
7893   return SDValue();
7894 }
7895
7896 /// Extract one bit from mask vector, like v16i1 or v8i1.
7897 /// AVX-512 feature.
7898 SDValue
7899 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
7900   SDValue Vec = Op.getOperand(0);
7901   SDLoc dl(Vec);
7902   MVT VecVT = Vec.getSimpleValueType();
7903   SDValue Idx = Op.getOperand(1);
7904   MVT EltVT = Op.getSimpleValueType();
7905
7906   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
7907
7908   // variable index can't be handled in mask registers,
7909   // extend vector to VR512
7910   if (!isa<ConstantSDNode>(Idx)) {
7911     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
7912     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
7913     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
7914                               ExtVT.getVectorElementType(), Ext, Idx);
7915     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
7916   }
7917
7918   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7919   const TargetRegisterClass* rc = getRegClassFor(VecVT);
7920   unsigned MaxSift = rc->getSize()*8 - 1;
7921   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
7922                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
7923   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
7924                     DAG.getConstant(MaxSift, MVT::i8));
7925   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
7926                        DAG.getIntPtrConstant(0));
7927 }
7928
7929 SDValue
7930 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7931                                            SelectionDAG &DAG) const {
7932   SDLoc dl(Op);
7933   SDValue Vec = Op.getOperand(0);
7934   MVT VecVT = Vec.getSimpleValueType();
7935   SDValue Idx = Op.getOperand(1);
7936
7937   if (Op.getSimpleValueType() == MVT::i1)
7938     return ExtractBitFromMaskVector(Op, DAG);
7939
7940   if (!isa<ConstantSDNode>(Idx)) {
7941     if (VecVT.is512BitVector() ||
7942         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
7943          VecVT.getVectorElementType().getSizeInBits() == 32)) {
7944
7945       MVT MaskEltVT =
7946         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
7947       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
7948                                     MaskEltVT.getSizeInBits());
7949
7950       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
7951       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
7952                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
7953                                 Idx, DAG.getConstant(0, getPointerTy()));
7954       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
7955       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
7956                         Perm, DAG.getConstant(0, getPointerTy()));
7957     }
7958     return SDValue();
7959   }
7960
7961   // If this is a 256-bit vector result, first extract the 128-bit vector and
7962   // then extract the element from the 128-bit vector.
7963   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
7964
7965     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7966     // Get the 128-bit vector.
7967     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7968     MVT EltVT = VecVT.getVectorElementType();
7969
7970     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
7971
7972     //if (IdxVal >= NumElems/2)
7973     //  IdxVal -= NumElems/2;
7974     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
7975     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7976                        DAG.getConstant(IdxVal, MVT::i32));
7977   }
7978
7979   assert(VecVT.is128BitVector() && "Unexpected vector length");
7980
7981   if (Subtarget->hasSSE41()) {
7982     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7983     if (Res.getNode())
7984       return Res;
7985   }
7986
7987   MVT VT = Op.getSimpleValueType();
7988   // TODO: handle v16i8.
7989   if (VT.getSizeInBits() == 16) {
7990     SDValue Vec = Op.getOperand(0);
7991     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7992     if (Idx == 0)
7993       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7994                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7995                                      DAG.getNode(ISD::BITCAST, dl,
7996                                                  MVT::v4i32, Vec),
7997                                      Op.getOperand(1)));
7998     // Transform it so it match pextrw which produces a 32-bit result.
7999     MVT EltVT = MVT::i32;
8000     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8001                                   Op.getOperand(0), Op.getOperand(1));
8002     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8003                                   DAG.getValueType(VT));
8004     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8005   }
8006
8007   if (VT.getSizeInBits() == 32) {
8008     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8009     if (Idx == 0)
8010       return Op;
8011
8012     // SHUFPS the element to the lowest double word, then movss.
8013     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8014     MVT VVT = Op.getOperand(0).getSimpleValueType();
8015     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8016                                        DAG.getUNDEF(VVT), Mask);
8017     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8018                        DAG.getIntPtrConstant(0));
8019   }
8020
8021   if (VT.getSizeInBits() == 64) {
8022     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8023     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8024     //        to match extract_elt for f64.
8025     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8026     if (Idx == 0)
8027       return Op;
8028
8029     // UNPCKHPD the element to the lowest double word, then movsd.
8030     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8031     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8032     int Mask[2] = { 1, -1 };
8033     MVT VVT = Op.getOperand(0).getSimpleValueType();
8034     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8035                                        DAG.getUNDEF(VVT), Mask);
8036     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8037                        DAG.getIntPtrConstant(0));
8038   }
8039
8040   return SDValue();
8041 }
8042
8043 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8044   MVT VT = Op.getSimpleValueType();
8045   MVT EltVT = VT.getVectorElementType();
8046   SDLoc dl(Op);
8047
8048   SDValue N0 = Op.getOperand(0);
8049   SDValue N1 = Op.getOperand(1);
8050   SDValue N2 = Op.getOperand(2);
8051
8052   if (!VT.is128BitVector())
8053     return SDValue();
8054
8055   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8056       isa<ConstantSDNode>(N2)) {
8057     unsigned Opc;
8058     if (VT == MVT::v8i16)
8059       Opc = X86ISD::PINSRW;
8060     else if (VT == MVT::v16i8)
8061       Opc = X86ISD::PINSRB;
8062     else
8063       Opc = X86ISD::PINSRB;
8064
8065     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8066     // argument.
8067     if (N1.getValueType() != MVT::i32)
8068       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8069     if (N2.getValueType() != MVT::i32)
8070       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8071     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8072   }
8073
8074   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8075     // Bits [7:6] of the constant are the source select.  This will always be
8076     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8077     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8078     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8079     // Bits [5:4] of the constant are the destination select.  This is the
8080     //  value of the incoming immediate.
8081     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8082     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8083     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8084     // Create this as a scalar to vector..
8085     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8086     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8087   }
8088
8089   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8090     // PINSR* works with constant index.
8091     return Op;
8092   }
8093   return SDValue();
8094 }
8095
8096 /// Insert one bit to mask vector, like v16i1 or v8i1.
8097 /// AVX-512 feature.
8098 SDValue 
8099 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8100   SDLoc dl(Op);
8101   SDValue Vec = Op.getOperand(0);
8102   SDValue Elt = Op.getOperand(1);
8103   SDValue Idx = Op.getOperand(2);
8104   MVT VecVT = Vec.getSimpleValueType();
8105
8106   if (!isa<ConstantSDNode>(Idx)) {
8107     // Non constant index. Extend source and destination,
8108     // insert element and then truncate the result.
8109     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8110     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8111     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8112       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8113       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8114     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8115   }
8116
8117   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8118   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8119   if (Vec.getOpcode() == ISD::UNDEF)
8120     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8121                        DAG.getConstant(IdxVal, MVT::i8));
8122   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8123   unsigned MaxSift = rc->getSize()*8 - 1;
8124   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8125                     DAG.getConstant(MaxSift, MVT::i8));
8126   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8127                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8128   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8129 }
8130 SDValue
8131 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8132   MVT VT = Op.getSimpleValueType();
8133   MVT EltVT = VT.getVectorElementType();
8134   
8135   if (EltVT == MVT::i1)
8136     return InsertBitToMaskVector(Op, DAG);
8137
8138   SDLoc dl(Op);
8139   SDValue N0 = Op.getOperand(0);
8140   SDValue N1 = Op.getOperand(1);
8141   SDValue N2 = Op.getOperand(2);
8142
8143   // If this is a 256-bit vector result, first extract the 128-bit vector,
8144   // insert the element into the extracted half and then place it back.
8145   if (VT.is256BitVector() || VT.is512BitVector()) {
8146     if (!isa<ConstantSDNode>(N2))
8147       return SDValue();
8148
8149     // Get the desired 128-bit vector half.
8150     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8151     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8152
8153     // Insert the element into the desired half.
8154     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8155     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8156
8157     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8158                     DAG.getConstant(IdxIn128, MVT::i32));
8159
8160     // Insert the changed part back to the 256-bit vector
8161     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8162   }
8163
8164   if (Subtarget->hasSSE41())
8165     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8166
8167   if (EltVT == MVT::i8)
8168     return SDValue();
8169
8170   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8171     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8172     // as its second argument.
8173     if (N1.getValueType() != MVT::i32)
8174       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8175     if (N2.getValueType() != MVT::i32)
8176       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8177     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8178   }
8179   return SDValue();
8180 }
8181
8182 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8183   SDLoc dl(Op);
8184   MVT OpVT = Op.getSimpleValueType();
8185
8186   // If this is a 256-bit vector result, first insert into a 128-bit
8187   // vector and then insert into the 256-bit vector.
8188   if (!OpVT.is128BitVector()) {
8189     // Insert into a 128-bit vector.
8190     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8191     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8192                                  OpVT.getVectorNumElements() / SizeFactor);
8193
8194     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8195
8196     // Insert the 128-bit vector.
8197     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8198   }
8199
8200   if (OpVT == MVT::v1i64 &&
8201       Op.getOperand(0).getValueType() == MVT::i64)
8202     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8203
8204   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8205   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8206   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8207                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8208 }
8209
8210 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8211 // a simple subregister reference or explicit instructions to grab
8212 // upper bits of a vector.
8213 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8214                                       SelectionDAG &DAG) {
8215   SDLoc dl(Op);
8216   SDValue In =  Op.getOperand(0);
8217   SDValue Idx = Op.getOperand(1);
8218   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8219   MVT ResVT   = Op.getSimpleValueType();
8220   MVT InVT    = In.getSimpleValueType();
8221
8222   if (Subtarget->hasFp256()) {
8223     if (ResVT.is128BitVector() &&
8224         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8225         isa<ConstantSDNode>(Idx)) {
8226       return Extract128BitVector(In, IdxVal, DAG, dl);
8227     }
8228     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8229         isa<ConstantSDNode>(Idx)) {
8230       return Extract256BitVector(In, IdxVal, DAG, dl);
8231     }
8232   }
8233   return SDValue();
8234 }
8235
8236 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8237 // simple superregister reference or explicit instructions to insert
8238 // the upper bits of a vector.
8239 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8240                                      SelectionDAG &DAG) {
8241   if (Subtarget->hasFp256()) {
8242     SDLoc dl(Op.getNode());
8243     SDValue Vec = Op.getNode()->getOperand(0);
8244     SDValue SubVec = Op.getNode()->getOperand(1);
8245     SDValue Idx = Op.getNode()->getOperand(2);
8246
8247     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8248          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8249         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8250         isa<ConstantSDNode>(Idx)) {
8251       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8252       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8253     }
8254
8255     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8256         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8257         isa<ConstantSDNode>(Idx)) {
8258       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8259       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8260     }
8261   }
8262   return SDValue();
8263 }
8264
8265 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8266 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8267 // one of the above mentioned nodes. It has to be wrapped because otherwise
8268 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8269 // be used to form addressing mode. These wrapped nodes will be selected
8270 // into MOV32ri.
8271 SDValue
8272 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8273   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8274
8275   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8276   // global base reg.
8277   unsigned char OpFlag = 0;
8278   unsigned WrapperKind = X86ISD::Wrapper;
8279   CodeModel::Model M = getTargetMachine().getCodeModel();
8280
8281   if (Subtarget->isPICStyleRIPRel() &&
8282       (M == CodeModel::Small || M == CodeModel::Kernel))
8283     WrapperKind = X86ISD::WrapperRIP;
8284   else if (Subtarget->isPICStyleGOT())
8285     OpFlag = X86II::MO_GOTOFF;
8286   else if (Subtarget->isPICStyleStubPIC())
8287     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8288
8289   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8290                                              CP->getAlignment(),
8291                                              CP->getOffset(), OpFlag);
8292   SDLoc DL(CP);
8293   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8294   // With PIC, the address is actually $g + Offset.
8295   if (OpFlag) {
8296     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8297                          DAG.getNode(X86ISD::GlobalBaseReg,
8298                                      SDLoc(), getPointerTy()),
8299                          Result);
8300   }
8301
8302   return Result;
8303 }
8304
8305 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8306   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8307
8308   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8309   // global base reg.
8310   unsigned char OpFlag = 0;
8311   unsigned WrapperKind = X86ISD::Wrapper;
8312   CodeModel::Model M = getTargetMachine().getCodeModel();
8313
8314   if (Subtarget->isPICStyleRIPRel() &&
8315       (M == CodeModel::Small || M == CodeModel::Kernel))
8316     WrapperKind = X86ISD::WrapperRIP;
8317   else if (Subtarget->isPICStyleGOT())
8318     OpFlag = X86II::MO_GOTOFF;
8319   else if (Subtarget->isPICStyleStubPIC())
8320     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8321
8322   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8323                                           OpFlag);
8324   SDLoc DL(JT);
8325   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8326
8327   // With PIC, the address is actually $g + Offset.
8328   if (OpFlag)
8329     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8330                          DAG.getNode(X86ISD::GlobalBaseReg,
8331                                      SDLoc(), getPointerTy()),
8332                          Result);
8333
8334   return Result;
8335 }
8336
8337 SDValue
8338 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8339   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8340
8341   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8342   // global base reg.
8343   unsigned char OpFlag = 0;
8344   unsigned WrapperKind = X86ISD::Wrapper;
8345   CodeModel::Model M = getTargetMachine().getCodeModel();
8346
8347   if (Subtarget->isPICStyleRIPRel() &&
8348       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8349     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8350       OpFlag = X86II::MO_GOTPCREL;
8351     WrapperKind = X86ISD::WrapperRIP;
8352   } else if (Subtarget->isPICStyleGOT()) {
8353     OpFlag = X86II::MO_GOT;
8354   } else if (Subtarget->isPICStyleStubPIC()) {
8355     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8356   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8357     OpFlag = X86II::MO_DARWIN_NONLAZY;
8358   }
8359
8360   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8361
8362   SDLoc DL(Op);
8363   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8364
8365   // With PIC, the address is actually $g + Offset.
8366   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8367       !Subtarget->is64Bit()) {
8368     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8369                          DAG.getNode(X86ISD::GlobalBaseReg,
8370                                      SDLoc(), getPointerTy()),
8371                          Result);
8372   }
8373
8374   // For symbols that require a load from a stub to get the address, emit the
8375   // load.
8376   if (isGlobalStubReference(OpFlag))
8377     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8378                          MachinePointerInfo::getGOT(), false, false, false, 0);
8379
8380   return Result;
8381 }
8382
8383 SDValue
8384 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8385   // Create the TargetBlockAddressAddress node.
8386   unsigned char OpFlags =
8387     Subtarget->ClassifyBlockAddressReference();
8388   CodeModel::Model M = getTargetMachine().getCodeModel();
8389   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8390   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8391   SDLoc dl(Op);
8392   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8393                                              OpFlags);
8394
8395   if (Subtarget->isPICStyleRIPRel() &&
8396       (M == CodeModel::Small || M == CodeModel::Kernel))
8397     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8398   else
8399     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8400
8401   // With PIC, the address is actually $g + Offset.
8402   if (isGlobalRelativeToPICBase(OpFlags)) {
8403     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8404                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8405                          Result);
8406   }
8407
8408   return Result;
8409 }
8410
8411 SDValue
8412 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8413                                       int64_t Offset, SelectionDAG &DAG) const {
8414   // Create the TargetGlobalAddress node, folding in the constant
8415   // offset if it is legal.
8416   unsigned char OpFlags =
8417     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8418   CodeModel::Model M = getTargetMachine().getCodeModel();
8419   SDValue Result;
8420   if (OpFlags == X86II::MO_NO_FLAG &&
8421       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8422     // A direct static reference to a global.
8423     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8424     Offset = 0;
8425   } else {
8426     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8427   }
8428
8429   if (Subtarget->isPICStyleRIPRel() &&
8430       (M == CodeModel::Small || M == CodeModel::Kernel))
8431     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8432   else
8433     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8434
8435   // With PIC, the address is actually $g + Offset.
8436   if (isGlobalRelativeToPICBase(OpFlags)) {
8437     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8438                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8439                          Result);
8440   }
8441
8442   // For globals that require a load from a stub to get the address, emit the
8443   // load.
8444   if (isGlobalStubReference(OpFlags))
8445     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8446                          MachinePointerInfo::getGOT(), false, false, false, 0);
8447
8448   // If there was a non-zero offset that we didn't fold, create an explicit
8449   // addition for it.
8450   if (Offset != 0)
8451     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8452                          DAG.getConstant(Offset, getPointerTy()));
8453
8454   return Result;
8455 }
8456
8457 SDValue
8458 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8459   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8460   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8461   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8462 }
8463
8464 static SDValue
8465 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8466            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8467            unsigned char OperandFlags, bool LocalDynamic = false) {
8468   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8469   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8470   SDLoc dl(GA);
8471   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8472                                            GA->getValueType(0),
8473                                            GA->getOffset(),
8474                                            OperandFlags);
8475
8476   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8477                                            : X86ISD::TLSADDR;
8478
8479   if (InFlag) {
8480     SDValue Ops[] = { Chain,  TGA, *InFlag };
8481     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8482   } else {
8483     SDValue Ops[]  = { Chain, TGA };
8484     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8485   }
8486
8487   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8488   MFI->setAdjustsStack(true);
8489
8490   SDValue Flag = Chain.getValue(1);
8491   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8492 }
8493
8494 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8495 static SDValue
8496 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8497                                 const EVT PtrVT) {
8498   SDValue InFlag;
8499   SDLoc dl(GA);  // ? function entry point might be better
8500   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8501                                    DAG.getNode(X86ISD::GlobalBaseReg,
8502                                                SDLoc(), PtrVT), InFlag);
8503   InFlag = Chain.getValue(1);
8504
8505   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8506 }
8507
8508 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8509 static SDValue
8510 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8511                                 const EVT PtrVT) {
8512   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8513                     X86::RAX, X86II::MO_TLSGD);
8514 }
8515
8516 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8517                                            SelectionDAG &DAG,
8518                                            const EVT PtrVT,
8519                                            bool is64Bit) {
8520   SDLoc dl(GA);
8521
8522   // Get the start address of the TLS block for this module.
8523   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8524       .getInfo<X86MachineFunctionInfo>();
8525   MFI->incNumLocalDynamicTLSAccesses();
8526
8527   SDValue Base;
8528   if (is64Bit) {
8529     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8530                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8531   } else {
8532     SDValue InFlag;
8533     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8534         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8535     InFlag = Chain.getValue(1);
8536     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8537                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8538   }
8539
8540   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8541   // of Base.
8542
8543   // Build x@dtpoff.
8544   unsigned char OperandFlags = X86II::MO_DTPOFF;
8545   unsigned WrapperKind = X86ISD::Wrapper;
8546   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8547                                            GA->getValueType(0),
8548                                            GA->getOffset(), OperandFlags);
8549   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8550
8551   // Add x@dtpoff with the base.
8552   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8553 }
8554
8555 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8556 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8557                                    const EVT PtrVT, TLSModel::Model model,
8558                                    bool is64Bit, bool isPIC) {
8559   SDLoc dl(GA);
8560
8561   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8562   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8563                                                          is64Bit ? 257 : 256));
8564
8565   SDValue ThreadPointer =
8566       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8567                   MachinePointerInfo(Ptr), false, false, false, 0);
8568
8569   unsigned char OperandFlags = 0;
8570   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8571   // initialexec.
8572   unsigned WrapperKind = X86ISD::Wrapper;
8573   if (model == TLSModel::LocalExec) {
8574     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8575   } else if (model == TLSModel::InitialExec) {
8576     if (is64Bit) {
8577       OperandFlags = X86II::MO_GOTTPOFF;
8578       WrapperKind = X86ISD::WrapperRIP;
8579     } else {
8580       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8581     }
8582   } else {
8583     llvm_unreachable("Unexpected model");
8584   }
8585
8586   // emit "addl x@ntpoff,%eax" (local exec)
8587   // or "addl x@indntpoff,%eax" (initial exec)
8588   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8589   SDValue TGA =
8590       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8591                                  GA->getOffset(), OperandFlags);
8592   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8593
8594   if (model == TLSModel::InitialExec) {
8595     if (isPIC && !is64Bit) {
8596       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8597                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8598                            Offset);
8599     }
8600
8601     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8602                          MachinePointerInfo::getGOT(), false, false, false, 0);
8603   }
8604
8605   // The address of the thread local variable is the add of the thread
8606   // pointer with the offset of the variable.
8607   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8608 }
8609
8610 SDValue
8611 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8612
8613   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8614   const GlobalValue *GV = GA->getGlobal();
8615
8616   if (Subtarget->isTargetELF()) {
8617     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8618
8619     switch (model) {
8620       case TLSModel::GeneralDynamic:
8621         if (Subtarget->is64Bit())
8622           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8623         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8624       case TLSModel::LocalDynamic:
8625         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8626                                            Subtarget->is64Bit());
8627       case TLSModel::InitialExec:
8628       case TLSModel::LocalExec:
8629         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8630                                    Subtarget->is64Bit(),
8631                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8632     }
8633     llvm_unreachable("Unknown TLS model.");
8634   }
8635
8636   if (Subtarget->isTargetDarwin()) {
8637     // Darwin only has one model of TLS.  Lower to that.
8638     unsigned char OpFlag = 0;
8639     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8640                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8641
8642     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8643     // global base reg.
8644     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8645                   !Subtarget->is64Bit();
8646     if (PIC32)
8647       OpFlag = X86II::MO_TLVP_PIC_BASE;
8648     else
8649       OpFlag = X86II::MO_TLVP;
8650     SDLoc DL(Op);
8651     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8652                                                 GA->getValueType(0),
8653                                                 GA->getOffset(), OpFlag);
8654     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8655
8656     // With PIC32, the address is actually $g + Offset.
8657     if (PIC32)
8658       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8659                            DAG.getNode(X86ISD::GlobalBaseReg,
8660                                        SDLoc(), getPointerTy()),
8661                            Offset);
8662
8663     // Lowering the machine isd will make sure everything is in the right
8664     // location.
8665     SDValue Chain = DAG.getEntryNode();
8666     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8667     SDValue Args[] = { Chain, Offset };
8668     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8669
8670     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8671     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8672     MFI->setAdjustsStack(true);
8673
8674     // And our return value (tls address) is in the standard call return value
8675     // location.
8676     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8677     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8678                               Chain.getValue(1));
8679   }
8680
8681   if (Subtarget->isTargetKnownWindowsMSVC() ||
8682       Subtarget->isTargetWindowsGNU()) {
8683     // Just use the implicit TLS architecture
8684     // Need to generate someting similar to:
8685     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8686     //                                  ; from TEB
8687     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8688     //   mov     rcx, qword [rdx+rcx*8]
8689     //   mov     eax, .tls$:tlsvar
8690     //   [rax+rcx] contains the address
8691     // Windows 64bit: gs:0x58
8692     // Windows 32bit: fs:__tls_array
8693
8694     // If GV is an alias then use the aliasee for determining
8695     // thread-localness.
8696     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
8697       GV = GA->getAliasedGlobal();
8698     SDLoc dl(GA);
8699     SDValue Chain = DAG.getEntryNode();
8700
8701     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8702     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8703     // use its literal value of 0x2C.
8704     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8705                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8706                                                              256)
8707                                         : Type::getInt32PtrTy(*DAG.getContext(),
8708                                                               257));
8709
8710     SDValue TlsArray =
8711         Subtarget->is64Bit()
8712             ? DAG.getIntPtrConstant(0x58)
8713             : (Subtarget->isTargetWindowsGNU()
8714                    ? DAG.getIntPtrConstant(0x2C)
8715                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8716
8717     SDValue ThreadPointer =
8718         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8719                     MachinePointerInfo(Ptr), false, false, false, 0);
8720
8721     // Load the _tls_index variable
8722     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8723     if (Subtarget->is64Bit())
8724       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8725                            IDX, MachinePointerInfo(), MVT::i32,
8726                            false, false, 0);
8727     else
8728       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8729                         false, false, false, 0);
8730
8731     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8732                                     getPointerTy());
8733     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8734
8735     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8736     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
8737                       false, false, false, 0);
8738
8739     // Get the offset of start of .tls section
8740     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8741                                              GA->getValueType(0),
8742                                              GA->getOffset(), X86II::MO_SECREL);
8743     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
8744
8745     // The address of the thread local variable is the add of the thread
8746     // pointer with the offset of the variable.
8747     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
8748   }
8749
8750   llvm_unreachable("TLS not implemented for this target.");
8751 }
8752
8753 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
8754 /// and take a 2 x i32 value to shift plus a shift amount.
8755 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
8756   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
8757   MVT VT = Op.getSimpleValueType();
8758   unsigned VTBits = VT.getSizeInBits();
8759   SDLoc dl(Op);
8760   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
8761   SDValue ShOpLo = Op.getOperand(0);
8762   SDValue ShOpHi = Op.getOperand(1);
8763   SDValue ShAmt  = Op.getOperand(2);
8764   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
8765   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
8766   // during isel.
8767   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8768                                   DAG.getConstant(VTBits - 1, MVT::i8));
8769   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
8770                                      DAG.getConstant(VTBits - 1, MVT::i8))
8771                        : DAG.getConstant(0, VT);
8772
8773   SDValue Tmp2, Tmp3;
8774   if (Op.getOpcode() == ISD::SHL_PARTS) {
8775     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
8776     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8777   } else {
8778     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
8779     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8780   }
8781
8782   // If the shift amount is larger or equal than the width of a part we can't
8783   // rely on the results of shld/shrd. Insert a test and select the appropriate
8784   // values for large shift amounts.
8785   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
8786                                 DAG.getConstant(VTBits, MVT::i8));
8787   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8788                              AndNode, DAG.getConstant(0, MVT::i8));
8789
8790   SDValue Hi, Lo;
8791   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8792   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
8793   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
8794
8795   if (Op.getOpcode() == ISD::SHL_PARTS) {
8796     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8797     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8798   } else {
8799     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
8800     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
8801   }
8802
8803   SDValue Ops[2] = { Lo, Hi };
8804   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
8805 }
8806
8807 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
8808                                            SelectionDAG &DAG) const {
8809   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
8810
8811   if (SrcVT.isVector())
8812     return SDValue();
8813
8814   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
8815          "Unknown SINT_TO_FP to lower!");
8816
8817   // These are really Legal; return the operand so the caller accepts it as
8818   // Legal.
8819   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8820     return Op;
8821   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8822       Subtarget->is64Bit()) {
8823     return Op;
8824   }
8825
8826   SDLoc dl(Op);
8827   unsigned Size = SrcVT.getSizeInBits()/8;
8828   MachineFunction &MF = DAG.getMachineFunction();
8829   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8830   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8831   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8832                                StackSlot,
8833                                MachinePointerInfo::getFixedStack(SSFI),
8834                                false, false, 0);
8835   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8836 }
8837
8838 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8839                                      SDValue StackSlot,
8840                                      SelectionDAG &DAG) const {
8841   // Build the FILD
8842   SDLoc DL(Op);
8843   SDVTList Tys;
8844   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8845   if (useSSE)
8846     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8847   else
8848     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8849
8850   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8851
8852   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8853   MachineMemOperand *MMO;
8854   if (FI) {
8855     int SSFI = FI->getIndex();
8856     MMO =
8857       DAG.getMachineFunction()
8858       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8859                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8860   } else {
8861     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8862     StackSlot = StackSlot.getOperand(1);
8863   }
8864   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8865   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8866                                            X86ISD::FILD, DL,
8867                                            Tys, Ops, SrcVT, MMO);
8868
8869   if (useSSE) {
8870     Chain = Result.getValue(1);
8871     SDValue InFlag = Result.getValue(2);
8872
8873     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8874     // shouldn't be necessary except that RFP cannot be live across
8875     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8876     MachineFunction &MF = DAG.getMachineFunction();
8877     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8878     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8879     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8880     Tys = DAG.getVTList(MVT::Other);
8881     SDValue Ops[] = {
8882       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8883     };
8884     MachineMemOperand *MMO =
8885       DAG.getMachineFunction()
8886       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8887                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8888
8889     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8890                                     Ops, Op.getValueType(), MMO);
8891     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8892                          MachinePointerInfo::getFixedStack(SSFI),
8893                          false, false, false, 0);
8894   }
8895
8896   return Result;
8897 }
8898
8899 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8900 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8901                                                SelectionDAG &DAG) const {
8902   // This algorithm is not obvious. Here it is what we're trying to output:
8903   /*
8904      movq       %rax,  %xmm0
8905      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8906      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8907      #ifdef __SSE3__
8908        haddpd   %xmm0, %xmm0
8909      #else
8910        pshufd   $0x4e, %xmm0, %xmm1
8911        addpd    %xmm1, %xmm0
8912      #endif
8913   */
8914
8915   SDLoc dl(Op);
8916   LLVMContext *Context = DAG.getContext();
8917
8918   // Build some magic constants.
8919   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8920   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8921   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8922
8923   SmallVector<Constant*,2> CV1;
8924   CV1.push_back(
8925     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8926                                       APInt(64, 0x4330000000000000ULL))));
8927   CV1.push_back(
8928     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8929                                       APInt(64, 0x4530000000000000ULL))));
8930   Constant *C1 = ConstantVector::get(CV1);
8931   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8932
8933   // Load the 64-bit value into an XMM register.
8934   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8935                             Op.getOperand(0));
8936   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8937                               MachinePointerInfo::getConstantPool(),
8938                               false, false, false, 16);
8939   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8940                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8941                               CLod0);
8942
8943   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8944                               MachinePointerInfo::getConstantPool(),
8945                               false, false, false, 16);
8946   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8947   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8948   SDValue Result;
8949
8950   if (Subtarget->hasSSE3()) {
8951     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8952     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8953   } else {
8954     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8955     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8956                                            S2F, 0x4E, DAG);
8957     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8958                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8959                          Sub);
8960   }
8961
8962   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8963                      DAG.getIntPtrConstant(0));
8964 }
8965
8966 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8967 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8968                                                SelectionDAG &DAG) const {
8969   SDLoc dl(Op);
8970   // FP constant to bias correct the final result.
8971   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8972                                    MVT::f64);
8973
8974   // Load the 32-bit value into an XMM register.
8975   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8976                              Op.getOperand(0));
8977
8978   // Zero out the upper parts of the register.
8979   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8980
8981   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8982                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8983                      DAG.getIntPtrConstant(0));
8984
8985   // Or the load with the bias.
8986   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8987                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8988                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8989                                                    MVT::v2f64, Load)),
8990                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8991                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8992                                                    MVT::v2f64, Bias)));
8993   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8994                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8995                    DAG.getIntPtrConstant(0));
8996
8997   // Subtract the bias.
8998   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8999
9000   // Handle final rounding.
9001   EVT DestVT = Op.getValueType();
9002
9003   if (DestVT.bitsLT(MVT::f64))
9004     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9005                        DAG.getIntPtrConstant(0));
9006   if (DestVT.bitsGT(MVT::f64))
9007     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9008
9009   // Handle final rounding.
9010   return Sub;
9011 }
9012
9013 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9014                                                SelectionDAG &DAG) const {
9015   SDValue N0 = Op.getOperand(0);
9016   MVT SVT = N0.getSimpleValueType();
9017   SDLoc dl(Op);
9018
9019   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9020           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9021          "Custom UINT_TO_FP is not supported!");
9022
9023   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9024   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9025                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9026 }
9027
9028 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9029                                            SelectionDAG &DAG) const {
9030   SDValue N0 = Op.getOperand(0);
9031   SDLoc dl(Op);
9032
9033   if (Op.getValueType().isVector())
9034     return lowerUINT_TO_FP_vec(Op, DAG);
9035
9036   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9037   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9038   // the optimization here.
9039   if (DAG.SignBitIsZero(N0))
9040     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9041
9042   MVT SrcVT = N0.getSimpleValueType();
9043   MVT DstVT = Op.getSimpleValueType();
9044   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9045     return LowerUINT_TO_FP_i64(Op, DAG);
9046   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9047     return LowerUINT_TO_FP_i32(Op, DAG);
9048   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9049     return SDValue();
9050
9051   // Make a 64-bit buffer, and use it to build an FILD.
9052   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9053   if (SrcVT == MVT::i32) {
9054     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9055     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9056                                      getPointerTy(), StackSlot, WordOff);
9057     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9058                                   StackSlot, MachinePointerInfo(),
9059                                   false, false, 0);
9060     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9061                                   OffsetSlot, MachinePointerInfo(),
9062                                   false, false, 0);
9063     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9064     return Fild;
9065   }
9066
9067   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9068   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9069                                StackSlot, MachinePointerInfo(),
9070                                false, false, 0);
9071   // For i64 source, we need to add the appropriate power of 2 if the input
9072   // was negative.  This is the same as the optimization in
9073   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9074   // we must be careful to do the computation in x87 extended precision, not
9075   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9076   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9077   MachineMemOperand *MMO =
9078     DAG.getMachineFunction()
9079     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9080                           MachineMemOperand::MOLoad, 8, 8);
9081
9082   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9083   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9084   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9085                                          MVT::i64, MMO);
9086
9087   APInt FF(32, 0x5F800000ULL);
9088
9089   // Check whether the sign bit is set.
9090   SDValue SignSet = DAG.getSetCC(dl,
9091                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9092                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9093                                  ISD::SETLT);
9094
9095   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9096   SDValue FudgePtr = DAG.getConstantPool(
9097                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9098                                          getPointerTy());
9099
9100   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9101   SDValue Zero = DAG.getIntPtrConstant(0);
9102   SDValue Four = DAG.getIntPtrConstant(4);
9103   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9104                                Zero, Four);
9105   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9106
9107   // Load the value out, extending it from f32 to f80.
9108   // FIXME: Avoid the extend by constructing the right constant pool?
9109   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9110                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9111                                  MVT::f32, false, false, 4);
9112   // Extend everything to 80 bits to force it to be done on x87.
9113   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9114   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9115 }
9116
9117 std::pair<SDValue,SDValue>
9118 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9119                                     bool IsSigned, bool IsReplace) const {
9120   SDLoc DL(Op);
9121
9122   EVT DstTy = Op.getValueType();
9123
9124   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9125     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9126     DstTy = MVT::i64;
9127   }
9128
9129   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9130          DstTy.getSimpleVT() >= MVT::i16 &&
9131          "Unknown FP_TO_INT to lower!");
9132
9133   // These are really Legal.
9134   if (DstTy == MVT::i32 &&
9135       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9136     return std::make_pair(SDValue(), SDValue());
9137   if (Subtarget->is64Bit() &&
9138       DstTy == MVT::i64 &&
9139       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9140     return std::make_pair(SDValue(), SDValue());
9141
9142   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9143   // stack slot, or into the FTOL runtime function.
9144   MachineFunction &MF = DAG.getMachineFunction();
9145   unsigned MemSize = DstTy.getSizeInBits()/8;
9146   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9147   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9148
9149   unsigned Opc;
9150   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9151     Opc = X86ISD::WIN_FTOL;
9152   else
9153     switch (DstTy.getSimpleVT().SimpleTy) {
9154     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9155     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9156     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9157     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9158     }
9159
9160   SDValue Chain = DAG.getEntryNode();
9161   SDValue Value = Op.getOperand(0);
9162   EVT TheVT = Op.getOperand(0).getValueType();
9163   // FIXME This causes a redundant load/store if the SSE-class value is already
9164   // in memory, such as if it is on the callstack.
9165   if (isScalarFPTypeInSSEReg(TheVT)) {
9166     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9167     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9168                          MachinePointerInfo::getFixedStack(SSFI),
9169                          false, false, 0);
9170     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9171     SDValue Ops[] = {
9172       Chain, StackSlot, DAG.getValueType(TheVT)
9173     };
9174
9175     MachineMemOperand *MMO =
9176       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9177                               MachineMemOperand::MOLoad, MemSize, MemSize);
9178     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9179     Chain = Value.getValue(1);
9180     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9181     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9182   }
9183
9184   MachineMemOperand *MMO =
9185     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9186                             MachineMemOperand::MOStore, MemSize, MemSize);
9187
9188   if (Opc != X86ISD::WIN_FTOL) {
9189     // Build the FP_TO_INT*_IN_MEM
9190     SDValue Ops[] = { Chain, Value, StackSlot };
9191     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9192                                            Ops, DstTy, MMO);
9193     return std::make_pair(FIST, StackSlot);
9194   } else {
9195     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9196       DAG.getVTList(MVT::Other, MVT::Glue),
9197       Chain, Value);
9198     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9199       MVT::i32, ftol.getValue(1));
9200     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9201       MVT::i32, eax.getValue(2));
9202     SDValue Ops[] = { eax, edx };
9203     SDValue pair = IsReplace
9204       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9205       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
9206     return std::make_pair(pair, SDValue());
9207   }
9208 }
9209
9210 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9211                               const X86Subtarget *Subtarget) {
9212   MVT VT = Op->getSimpleValueType(0);
9213   SDValue In = Op->getOperand(0);
9214   MVT InVT = In.getSimpleValueType();
9215   SDLoc dl(Op);
9216
9217   // Optimize vectors in AVX mode:
9218   //
9219   //   v8i16 -> v8i32
9220   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9221   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9222   //   Concat upper and lower parts.
9223   //
9224   //   v4i32 -> v4i64
9225   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9226   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9227   //   Concat upper and lower parts.
9228   //
9229
9230   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9231       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9232       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9233     return SDValue();
9234
9235   if (Subtarget->hasInt256())
9236     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9237
9238   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9239   SDValue Undef = DAG.getUNDEF(InVT);
9240   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9241   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9242   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9243
9244   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9245                              VT.getVectorNumElements()/2);
9246
9247   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9248   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9249
9250   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9251 }
9252
9253 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9254                                         SelectionDAG &DAG) {
9255   MVT VT = Op->getSimpleValueType(0);
9256   SDValue In = Op->getOperand(0);
9257   MVT InVT = In.getSimpleValueType();
9258   SDLoc DL(Op);
9259   unsigned int NumElts = VT.getVectorNumElements();
9260   if (NumElts != 8 && NumElts != 16)
9261     return SDValue();
9262
9263   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9264     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9265
9266   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9267   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9268   // Now we have only mask extension
9269   assert(InVT.getVectorElementType() == MVT::i1);
9270   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9271   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9272   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9273   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9274   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9275                            MachinePointerInfo::getConstantPool(),
9276                            false, false, false, Alignment);
9277
9278   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9279   if (VT.is512BitVector())
9280     return Brcst;
9281   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9282 }
9283
9284 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9285                                SelectionDAG &DAG) {
9286   if (Subtarget->hasFp256()) {
9287     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9288     if (Res.getNode())
9289       return Res;
9290   }
9291
9292   return SDValue();
9293 }
9294
9295 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9296                                 SelectionDAG &DAG) {
9297   SDLoc DL(Op);
9298   MVT VT = Op.getSimpleValueType();
9299   SDValue In = Op.getOperand(0);
9300   MVT SVT = In.getSimpleValueType();
9301
9302   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9303     return LowerZERO_EXTEND_AVX512(Op, DAG);
9304
9305   if (Subtarget->hasFp256()) {
9306     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9307     if (Res.getNode())
9308       return Res;
9309   }
9310
9311   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9312          VT.getVectorNumElements() != SVT.getVectorNumElements());
9313   return SDValue();
9314 }
9315
9316 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9317   SDLoc DL(Op);
9318   MVT VT = Op.getSimpleValueType();
9319   SDValue In = Op.getOperand(0);
9320   MVT InVT = In.getSimpleValueType();
9321
9322   if (VT == MVT::i1) {
9323     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9324            "Invalid scalar TRUNCATE operation");
9325     if (InVT == MVT::i32)
9326       return SDValue();
9327     if (InVT.getSizeInBits() == 64)
9328       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9329     else if (InVT.getSizeInBits() < 32)
9330       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9331     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9332   }
9333   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9334          "Invalid TRUNCATE operation");
9335
9336   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9337     if (VT.getVectorElementType().getSizeInBits() >=8)
9338       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9339
9340     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9341     unsigned NumElts = InVT.getVectorNumElements();
9342     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9343     if (InVT.getSizeInBits() < 512) {
9344       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9345       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9346       InVT = ExtVT;
9347     }
9348     
9349     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9350     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9351     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9352     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9353     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9354                            MachinePointerInfo::getConstantPool(),
9355                            false, false, false, Alignment);
9356     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9357     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9358     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9359   }
9360
9361   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9362     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9363     if (Subtarget->hasInt256()) {
9364       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9365       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9366       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9367                                 ShufMask);
9368       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9369                          DAG.getIntPtrConstant(0));
9370     }
9371
9372     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9373                                DAG.getIntPtrConstant(0));
9374     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9375                                DAG.getIntPtrConstant(2));
9376     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9377     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9378     static const int ShufMask[] = {0, 2, 4, 6};
9379     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9380   }
9381
9382   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9383     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9384     if (Subtarget->hasInt256()) {
9385       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9386
9387       SmallVector<SDValue,32> pshufbMask;
9388       for (unsigned i = 0; i < 2; ++i) {
9389         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9390         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9391         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9392         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9393         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9394         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9395         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9396         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9397         for (unsigned j = 0; j < 8; ++j)
9398           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9399       }
9400       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9401       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9402       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9403
9404       static const int ShufMask[] = {0,  2,  -1,  -1};
9405       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9406                                 &ShufMask[0]);
9407       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9408                        DAG.getIntPtrConstant(0));
9409       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9410     }
9411
9412     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9413                                DAG.getIntPtrConstant(0));
9414
9415     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9416                                DAG.getIntPtrConstant(4));
9417
9418     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9419     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9420
9421     // The PSHUFB mask:
9422     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9423                                    -1, -1, -1, -1, -1, -1, -1, -1};
9424
9425     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9426     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9427     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9428
9429     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9430     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9431
9432     // The MOVLHPS Mask:
9433     static const int ShufMask2[] = {0, 1, 4, 5};
9434     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9435     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9436   }
9437
9438   // Handle truncation of V256 to V128 using shuffles.
9439   if (!VT.is128BitVector() || !InVT.is256BitVector())
9440     return SDValue();
9441
9442   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9443
9444   unsigned NumElems = VT.getVectorNumElements();
9445   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9446
9447   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9448   // Prepare truncation shuffle mask
9449   for (unsigned i = 0; i != NumElems; ++i)
9450     MaskVec[i] = i * 2;
9451   SDValue V = DAG.getVectorShuffle(NVT, DL,
9452                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9453                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9454   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9455                      DAG.getIntPtrConstant(0));
9456 }
9457
9458 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9459                                            SelectionDAG &DAG) const {
9460   assert(!Op.getSimpleValueType().isVector());
9461
9462   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9463     /*IsSigned=*/ true, /*IsReplace=*/ false);
9464   SDValue FIST = Vals.first, StackSlot = Vals.second;
9465   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9466   if (!FIST.getNode()) return Op;
9467
9468   if (StackSlot.getNode())
9469     // Load the result.
9470     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9471                        FIST, StackSlot, MachinePointerInfo(),
9472                        false, false, false, 0);
9473
9474   // The node is the result.
9475   return FIST;
9476 }
9477
9478 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9479                                            SelectionDAG &DAG) const {
9480   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9481     /*IsSigned=*/ false, /*IsReplace=*/ false);
9482   SDValue FIST = Vals.first, StackSlot = Vals.second;
9483   assert(FIST.getNode() && "Unexpected failure");
9484
9485   if (StackSlot.getNode())
9486     // Load the result.
9487     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9488                        FIST, StackSlot, MachinePointerInfo(),
9489                        false, false, false, 0);
9490
9491   // The node is the result.
9492   return FIST;
9493 }
9494
9495 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9496   SDLoc DL(Op);
9497   MVT VT = Op.getSimpleValueType();
9498   SDValue In = Op.getOperand(0);
9499   MVT SVT = In.getSimpleValueType();
9500
9501   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9502
9503   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9504                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9505                                  In, DAG.getUNDEF(SVT)));
9506 }
9507
9508 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9509   LLVMContext *Context = DAG.getContext();
9510   SDLoc dl(Op);
9511   MVT VT = Op.getSimpleValueType();
9512   MVT EltVT = VT;
9513   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9514   if (VT.isVector()) {
9515     EltVT = VT.getVectorElementType();
9516     NumElts = VT.getVectorNumElements();
9517   }
9518   Constant *C;
9519   if (EltVT == MVT::f64)
9520     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9521                                           APInt(64, ~(1ULL << 63))));
9522   else
9523     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9524                                           APInt(32, ~(1U << 31))));
9525   C = ConstantVector::getSplat(NumElts, C);
9526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9527   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9528   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9529   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9530                              MachinePointerInfo::getConstantPool(),
9531                              false, false, false, Alignment);
9532   if (VT.isVector()) {
9533     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9534     return DAG.getNode(ISD::BITCAST, dl, VT,
9535                        DAG.getNode(ISD::AND, dl, ANDVT,
9536                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9537                                                Op.getOperand(0)),
9538                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9539   }
9540   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9541 }
9542
9543 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9544   LLVMContext *Context = DAG.getContext();
9545   SDLoc dl(Op);
9546   MVT VT = Op.getSimpleValueType();
9547   MVT EltVT = VT;
9548   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9549   if (VT.isVector()) {
9550     EltVT = VT.getVectorElementType();
9551     NumElts = VT.getVectorNumElements();
9552   }
9553   Constant *C;
9554   if (EltVT == MVT::f64)
9555     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9556                                           APInt(64, 1ULL << 63)));
9557   else
9558     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9559                                           APInt(32, 1U << 31)));
9560   C = ConstantVector::getSplat(NumElts, C);
9561   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9562   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9563   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9564   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9565                              MachinePointerInfo::getConstantPool(),
9566                              false, false, false, Alignment);
9567   if (VT.isVector()) {
9568     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9569     return DAG.getNode(ISD::BITCAST, dl, VT,
9570                        DAG.getNode(ISD::XOR, dl, XORVT,
9571                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9572                                                Op.getOperand(0)),
9573                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9574   }
9575
9576   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9577 }
9578
9579 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9580   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9581   LLVMContext *Context = DAG.getContext();
9582   SDValue Op0 = Op.getOperand(0);
9583   SDValue Op1 = Op.getOperand(1);
9584   SDLoc dl(Op);
9585   MVT VT = Op.getSimpleValueType();
9586   MVT SrcVT = Op1.getSimpleValueType();
9587
9588   // If second operand is smaller, extend it first.
9589   if (SrcVT.bitsLT(VT)) {
9590     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9591     SrcVT = VT;
9592   }
9593   // And if it is bigger, shrink it first.
9594   if (SrcVT.bitsGT(VT)) {
9595     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9596     SrcVT = VT;
9597   }
9598
9599   // At this point the operands and the result should have the same
9600   // type, and that won't be f80 since that is not custom lowered.
9601
9602   // First get the sign bit of second operand.
9603   SmallVector<Constant*,4> CV;
9604   if (SrcVT == MVT::f64) {
9605     const fltSemantics &Sem = APFloat::IEEEdouble;
9606     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9607     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9608   } else {
9609     const fltSemantics &Sem = APFloat::IEEEsingle;
9610     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9611     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9612     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9613     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9614   }
9615   Constant *C = ConstantVector::get(CV);
9616   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9617   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9618                               MachinePointerInfo::getConstantPool(),
9619                               false, false, false, 16);
9620   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9621
9622   // Shift sign bit right or left if the two operands have different types.
9623   if (SrcVT.bitsGT(VT)) {
9624     // Op0 is MVT::f32, Op1 is MVT::f64.
9625     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9626     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9627                           DAG.getConstant(32, MVT::i32));
9628     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9629     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9630                           DAG.getIntPtrConstant(0));
9631   }
9632
9633   // Clear first operand sign bit.
9634   CV.clear();
9635   if (VT == MVT::f64) {
9636     const fltSemantics &Sem = APFloat::IEEEdouble;
9637     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9638                                                    APInt(64, ~(1ULL << 63)))));
9639     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9640   } else {
9641     const fltSemantics &Sem = APFloat::IEEEsingle;
9642     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9643                                                    APInt(32, ~(1U << 31)))));
9644     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9645     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9646     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9647   }
9648   C = ConstantVector::get(CV);
9649   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9650   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9651                               MachinePointerInfo::getConstantPool(),
9652                               false, false, false, 16);
9653   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9654
9655   // Or the value with the sign bit.
9656   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9657 }
9658
9659 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9660   SDValue N0 = Op.getOperand(0);
9661   SDLoc dl(Op);
9662   MVT VT = Op.getSimpleValueType();
9663
9664   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9665   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9666                                   DAG.getConstant(1, VT));
9667   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9668 }
9669
9670 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9671 //
9672 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9673                                       SelectionDAG &DAG) {
9674   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9675
9676   if (!Subtarget->hasSSE41())
9677     return SDValue();
9678
9679   if (!Op->hasOneUse())
9680     return SDValue();
9681
9682   SDNode *N = Op.getNode();
9683   SDLoc DL(N);
9684
9685   SmallVector<SDValue, 8> Opnds;
9686   DenseMap<SDValue, unsigned> VecInMap;
9687   SmallVector<SDValue, 8> VecIns;
9688   EVT VT = MVT::Other;
9689
9690   // Recognize a special case where a vector is casted into wide integer to
9691   // test all 0s.
9692   Opnds.push_back(N->getOperand(0));
9693   Opnds.push_back(N->getOperand(1));
9694
9695   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9696     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9697     // BFS traverse all OR'd operands.
9698     if (I->getOpcode() == ISD::OR) {
9699       Opnds.push_back(I->getOperand(0));
9700       Opnds.push_back(I->getOperand(1));
9701       // Re-evaluate the number of nodes to be traversed.
9702       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9703       continue;
9704     }
9705
9706     // Quit if a non-EXTRACT_VECTOR_ELT
9707     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9708       return SDValue();
9709
9710     // Quit if without a constant index.
9711     SDValue Idx = I->getOperand(1);
9712     if (!isa<ConstantSDNode>(Idx))
9713       return SDValue();
9714
9715     SDValue ExtractedFromVec = I->getOperand(0);
9716     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9717     if (M == VecInMap.end()) {
9718       VT = ExtractedFromVec.getValueType();
9719       // Quit if not 128/256-bit vector.
9720       if (!VT.is128BitVector() && !VT.is256BitVector())
9721         return SDValue();
9722       // Quit if not the same type.
9723       if (VecInMap.begin() != VecInMap.end() &&
9724           VT != VecInMap.begin()->first.getValueType())
9725         return SDValue();
9726       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9727       VecIns.push_back(ExtractedFromVec);
9728     }
9729     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9730   }
9731
9732   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9733          "Not extracted from 128-/256-bit vector.");
9734
9735   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9736
9737   for (DenseMap<SDValue, unsigned>::const_iterator
9738         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
9739     // Quit if not all elements are used.
9740     if (I->second != FullMask)
9741       return SDValue();
9742   }
9743
9744   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9745
9746   // Cast all vectors into TestVT for PTEST.
9747   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
9748     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
9749
9750   // If more than one full vectors are evaluated, OR them first before PTEST.
9751   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
9752     // Each iteration will OR 2 nodes and append the result until there is only
9753     // 1 node left, i.e. the final OR'd value of all vectors.
9754     SDValue LHS = VecIns[Slot];
9755     SDValue RHS = VecIns[Slot + 1];
9756     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
9757   }
9758
9759   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
9760                      VecIns.back(), VecIns.back());
9761 }
9762
9763 /// \brief return true if \c Op has a use that doesn't just read flags.
9764 static bool hasNonFlagsUse(SDValue Op) {
9765   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
9766        ++UI) {
9767     SDNode *User = *UI;
9768     unsigned UOpNo = UI.getOperandNo();
9769     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9770       // Look pass truncate.
9771       UOpNo = User->use_begin().getOperandNo();
9772       User = *User->use_begin();
9773     }
9774
9775     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
9776         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
9777       return true;
9778   }
9779   return false;
9780 }
9781
9782 /// Emit nodes that will be selected as "test Op0,Op0", or something
9783 /// equivalent.
9784 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
9785                                     SelectionDAG &DAG) const {
9786   if (Op.getValueType() == MVT::i1)
9787     // KORTEST instruction should be selected
9788     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9789                        DAG.getConstant(0, Op.getValueType()));
9790
9791   // CF and OF aren't always set the way we want. Determine which
9792   // of these we need.
9793   bool NeedCF = false;
9794   bool NeedOF = false;
9795   switch (X86CC) {
9796   default: break;
9797   case X86::COND_A: case X86::COND_AE:
9798   case X86::COND_B: case X86::COND_BE:
9799     NeedCF = true;
9800     break;
9801   case X86::COND_G: case X86::COND_GE:
9802   case X86::COND_L: case X86::COND_LE:
9803   case X86::COND_O: case X86::COND_NO:
9804     NeedOF = true;
9805     break;
9806   }
9807   // See if we can use the EFLAGS value from the operand instead of
9808   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
9809   // we prove that the arithmetic won't overflow, we can't use OF or CF.
9810   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
9811     // Emit a CMP with 0, which is the TEST pattern.
9812     //if (Op.getValueType() == MVT::i1)
9813     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
9814     //                     DAG.getConstant(0, MVT::i1));
9815     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9816                        DAG.getConstant(0, Op.getValueType()));
9817   }
9818   unsigned Opcode = 0;
9819   unsigned NumOperands = 0;
9820
9821   // Truncate operations may prevent the merge of the SETCC instruction
9822   // and the arithmetic instruction before it. Attempt to truncate the operands
9823   // of the arithmetic instruction and use a reduced bit-width instruction.
9824   bool NeedTruncation = false;
9825   SDValue ArithOp = Op;
9826   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
9827     SDValue Arith = Op->getOperand(0);
9828     // Both the trunc and the arithmetic op need to have one user each.
9829     if (Arith->hasOneUse())
9830       switch (Arith.getOpcode()) {
9831         default: break;
9832         case ISD::ADD:
9833         case ISD::SUB:
9834         case ISD::AND:
9835         case ISD::OR:
9836         case ISD::XOR: {
9837           NeedTruncation = true;
9838           ArithOp = Arith;
9839         }
9840       }
9841   }
9842
9843   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
9844   // which may be the result of a CAST.  We use the variable 'Op', which is the
9845   // non-casted variable when we check for possible users.
9846   switch (ArithOp.getOpcode()) {
9847   case ISD::ADD:
9848     // Due to an isel shortcoming, be conservative if this add is likely to be
9849     // selected as part of a load-modify-store instruction. When the root node
9850     // in a match is a store, isel doesn't know how to remap non-chain non-flag
9851     // uses of other nodes in the match, such as the ADD in this case. This
9852     // leads to the ADD being left around and reselected, with the result being
9853     // two adds in the output.  Alas, even if none our users are stores, that
9854     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
9855     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
9856     // climbing the DAG back to the root, and it doesn't seem to be worth the
9857     // effort.
9858     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9859          UE = Op.getNode()->use_end(); UI != UE; ++UI)
9860       if (UI->getOpcode() != ISD::CopyToReg &&
9861           UI->getOpcode() != ISD::SETCC &&
9862           UI->getOpcode() != ISD::STORE)
9863         goto default_case;
9864
9865     if (ConstantSDNode *C =
9866         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
9867       // An add of one will be selected as an INC.
9868       if (C->getAPIntValue() == 1) {
9869         Opcode = X86ISD::INC;
9870         NumOperands = 1;
9871         break;
9872       }
9873
9874       // An add of negative one (subtract of one) will be selected as a DEC.
9875       if (C->getAPIntValue().isAllOnesValue()) {
9876         Opcode = X86ISD::DEC;
9877         NumOperands = 1;
9878         break;
9879       }
9880     }
9881
9882     // Otherwise use a regular EFLAGS-setting add.
9883     Opcode = X86ISD::ADD;
9884     NumOperands = 2;
9885     break;
9886   case ISD::SHL:
9887   case ISD::SRL:
9888     // If we have a constant logical shift that's only used in a comparison
9889     // against zero turn it into an equivalent AND. This allows turning it into
9890     // a TEST instruction later.
9891     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
9892         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
9893       EVT VT = Op.getValueType();
9894       unsigned BitWidth = VT.getSizeInBits();
9895       unsigned ShAmt = Op->getConstantOperandVal(1);
9896       if (ShAmt >= BitWidth) // Avoid undefined shifts.
9897         break;
9898       APInt Mask = ArithOp.getOpcode() == ISD::SRL
9899                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
9900                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
9901       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
9902         break;
9903       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
9904                                 DAG.getConstant(Mask, VT));
9905       DAG.ReplaceAllUsesWith(Op, New);
9906       Op = New;
9907     }
9908     break;
9909
9910   case ISD::AND:
9911     // If the primary and result isn't used, don't bother using X86ISD::AND,
9912     // because a TEST instruction will be better.
9913     if (!hasNonFlagsUse(Op))
9914       break;
9915     // FALL THROUGH
9916   case ISD::SUB:
9917   case ISD::OR:
9918   case ISD::XOR:
9919     // Due to the ISEL shortcoming noted above, be conservative if this op is
9920     // likely to be selected as part of a load-modify-store instruction.
9921     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9922            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9923       if (UI->getOpcode() == ISD::STORE)
9924         goto default_case;
9925
9926     // Otherwise use a regular EFLAGS-setting instruction.
9927     switch (ArithOp.getOpcode()) {
9928     default: llvm_unreachable("unexpected operator!");
9929     case ISD::SUB: Opcode = X86ISD::SUB; break;
9930     case ISD::XOR: Opcode = X86ISD::XOR; break;
9931     case ISD::AND: Opcode = X86ISD::AND; break;
9932     case ISD::OR: {
9933       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9934         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
9935         if (EFLAGS.getNode())
9936           return EFLAGS;
9937       }
9938       Opcode = X86ISD::OR;
9939       break;
9940     }
9941     }
9942
9943     NumOperands = 2;
9944     break;
9945   case X86ISD::ADD:
9946   case X86ISD::SUB:
9947   case X86ISD::INC:
9948   case X86ISD::DEC:
9949   case X86ISD::OR:
9950   case X86ISD::XOR:
9951   case X86ISD::AND:
9952     return SDValue(Op.getNode(), 1);
9953   default:
9954   default_case:
9955     break;
9956   }
9957
9958   // If we found that truncation is beneficial, perform the truncation and
9959   // update 'Op'.
9960   if (NeedTruncation) {
9961     EVT VT = Op.getValueType();
9962     SDValue WideVal = Op->getOperand(0);
9963     EVT WideVT = WideVal.getValueType();
9964     unsigned ConvertedOp = 0;
9965     // Use a target machine opcode to prevent further DAGCombine
9966     // optimizations that may separate the arithmetic operations
9967     // from the setcc node.
9968     switch (WideVal.getOpcode()) {
9969       default: break;
9970       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9971       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9972       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9973       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9974       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9975     }
9976
9977     if (ConvertedOp) {
9978       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9979       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9980         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9981         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9982         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9983       }
9984     }
9985   }
9986
9987   if (Opcode == 0)
9988     // Emit a CMP with 0, which is the TEST pattern.
9989     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9990                        DAG.getConstant(0, Op.getValueType()));
9991
9992   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9993   SmallVector<SDValue, 4> Ops;
9994   for (unsigned i = 0; i != NumOperands; ++i)
9995     Ops.push_back(Op.getOperand(i));
9996
9997   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
9998   DAG.ReplaceAllUsesWith(Op, New);
9999   return SDValue(New.getNode(), 1);
10000 }
10001
10002 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10003 /// equivalent.
10004 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10005                                    SDLoc dl, SelectionDAG &DAG) const {
10006   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10007     if (C->getAPIntValue() == 0)
10008       return EmitTest(Op0, X86CC, dl, DAG);
10009
10010      if (Op0.getValueType() == MVT::i1)
10011        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10012   }
10013  
10014   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10015        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10016     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10017     // This avoids subregister aliasing issues. Keep the smaller reference 
10018     // if we're optimizing for size, however, as that'll allow better folding 
10019     // of memory operations.
10020     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10021         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10022              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10023         !Subtarget->isAtom()) {
10024       unsigned ExtendOp =
10025           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10026       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10027       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10028     }
10029     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10030     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10031     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10032                               Op0, Op1);
10033     return SDValue(Sub.getNode(), 1);
10034   }
10035   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10036 }
10037
10038 /// Convert a comparison if required by the subtarget.
10039 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10040                                                  SelectionDAG &DAG) const {
10041   // If the subtarget does not support the FUCOMI instruction, floating-point
10042   // comparisons have to be converted.
10043   if (Subtarget->hasCMov() ||
10044       Cmp.getOpcode() != X86ISD::CMP ||
10045       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10046       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10047     return Cmp;
10048
10049   // The instruction selector will select an FUCOM instruction instead of
10050   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10051   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10052   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10053   SDLoc dl(Cmp);
10054   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10055   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10056   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10057                             DAG.getConstant(8, MVT::i8));
10058   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10059   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10060 }
10061
10062 static bool isAllOnes(SDValue V) {
10063   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10064   return C && C->isAllOnesValue();
10065 }
10066
10067 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10068 /// if it's possible.
10069 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10070                                      SDLoc dl, SelectionDAG &DAG) const {
10071   SDValue Op0 = And.getOperand(0);
10072   SDValue Op1 = And.getOperand(1);
10073   if (Op0.getOpcode() == ISD::TRUNCATE)
10074     Op0 = Op0.getOperand(0);
10075   if (Op1.getOpcode() == ISD::TRUNCATE)
10076     Op1 = Op1.getOperand(0);
10077
10078   SDValue LHS, RHS;
10079   if (Op1.getOpcode() == ISD::SHL)
10080     std::swap(Op0, Op1);
10081   if (Op0.getOpcode() == ISD::SHL) {
10082     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10083       if (And00C->getZExtValue() == 1) {
10084         // If we looked past a truncate, check that it's only truncating away
10085         // known zeros.
10086         unsigned BitWidth = Op0.getValueSizeInBits();
10087         unsigned AndBitWidth = And.getValueSizeInBits();
10088         if (BitWidth > AndBitWidth) {
10089           APInt Zeros, Ones;
10090           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
10091           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10092             return SDValue();
10093         }
10094         LHS = Op1;
10095         RHS = Op0.getOperand(1);
10096       }
10097   } else if (Op1.getOpcode() == ISD::Constant) {
10098     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10099     uint64_t AndRHSVal = AndRHS->getZExtValue();
10100     SDValue AndLHS = Op0;
10101
10102     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10103       LHS = AndLHS.getOperand(0);
10104       RHS = AndLHS.getOperand(1);
10105     }
10106
10107     // Use BT if the immediate can't be encoded in a TEST instruction.
10108     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10109       LHS = AndLHS;
10110       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10111     }
10112   }
10113
10114   if (LHS.getNode()) {
10115     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10116     // instruction.  Since the shift amount is in-range-or-undefined, we know
10117     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10118     // the encoding for the i16 version is larger than the i32 version.
10119     // Also promote i16 to i32 for performance / code size reason.
10120     if (LHS.getValueType() == MVT::i8 ||
10121         LHS.getValueType() == MVT::i16)
10122       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10123
10124     // If the operand types disagree, extend the shift amount to match.  Since
10125     // BT ignores high bits (like shifts) we can use anyextend.
10126     if (LHS.getValueType() != RHS.getValueType())
10127       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10128
10129     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10130     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10131     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10132                        DAG.getConstant(Cond, MVT::i8), BT);
10133   }
10134
10135   return SDValue();
10136 }
10137
10138 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10139 /// mask CMPs.
10140 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10141                               SDValue &Op1) {
10142   unsigned SSECC;
10143   bool Swap = false;
10144
10145   // SSE Condition code mapping:
10146   //  0 - EQ
10147   //  1 - LT
10148   //  2 - LE
10149   //  3 - UNORD
10150   //  4 - NEQ
10151   //  5 - NLT
10152   //  6 - NLE
10153   //  7 - ORD
10154   switch (SetCCOpcode) {
10155   default: llvm_unreachable("Unexpected SETCC condition");
10156   case ISD::SETOEQ:
10157   case ISD::SETEQ:  SSECC = 0; break;
10158   case ISD::SETOGT:
10159   case ISD::SETGT:  Swap = true; // Fallthrough
10160   case ISD::SETLT:
10161   case ISD::SETOLT: SSECC = 1; break;
10162   case ISD::SETOGE:
10163   case ISD::SETGE:  Swap = true; // Fallthrough
10164   case ISD::SETLE:
10165   case ISD::SETOLE: SSECC = 2; break;
10166   case ISD::SETUO:  SSECC = 3; break;
10167   case ISD::SETUNE:
10168   case ISD::SETNE:  SSECC = 4; break;
10169   case ISD::SETULE: Swap = true; // Fallthrough
10170   case ISD::SETUGE: SSECC = 5; break;
10171   case ISD::SETULT: Swap = true; // Fallthrough
10172   case ISD::SETUGT: SSECC = 6; break;
10173   case ISD::SETO:   SSECC = 7; break;
10174   case ISD::SETUEQ:
10175   case ISD::SETONE: SSECC = 8; break;
10176   }
10177   if (Swap)
10178     std::swap(Op0, Op1);
10179
10180   return SSECC;
10181 }
10182
10183 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10184 // ones, and then concatenate the result back.
10185 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10186   MVT VT = Op.getSimpleValueType();
10187
10188   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10189          "Unsupported value type for operation");
10190
10191   unsigned NumElems = VT.getVectorNumElements();
10192   SDLoc dl(Op);
10193   SDValue CC = Op.getOperand(2);
10194
10195   // Extract the LHS vectors
10196   SDValue LHS = Op.getOperand(0);
10197   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10198   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10199
10200   // Extract the RHS vectors
10201   SDValue RHS = Op.getOperand(1);
10202   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10203   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10204
10205   // Issue the operation on the smaller types and concatenate the result back
10206   MVT EltVT = VT.getVectorElementType();
10207   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10208   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10209                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10210                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10211 }
10212
10213 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10214                                      const X86Subtarget *Subtarget) {
10215   SDValue Op0 = Op.getOperand(0);
10216   SDValue Op1 = Op.getOperand(1);
10217   SDValue CC = Op.getOperand(2);
10218   MVT VT = Op.getSimpleValueType();
10219   SDLoc dl(Op);
10220
10221   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10222          Op.getValueType().getScalarType() == MVT::i1 &&
10223          "Cannot set masked compare for this operation");
10224
10225   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10226   unsigned  Opc = 0;
10227   bool Unsigned = false;
10228   bool Swap = false;
10229   unsigned SSECC;
10230   switch (SetCCOpcode) {
10231   default: llvm_unreachable("Unexpected SETCC condition");
10232   case ISD::SETNE:  SSECC = 4; break;
10233   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10234   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10235   case ISD::SETLT:  Swap = true; //fall-through
10236   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10237   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10238   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10239   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10240   case ISD::SETULE: Unsigned = true; //fall-through
10241   case ISD::SETLE:  SSECC = 2; break;
10242   }
10243
10244   if (Swap)
10245     std::swap(Op0, Op1);
10246   if (Opc)
10247     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10248   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10249   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10250                      DAG.getConstant(SSECC, MVT::i8));
10251 }
10252
10253 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10254 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10255 /// return an empty value.
10256 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10257 {
10258   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10259   if (!BV)
10260     return SDValue();
10261
10262   MVT VT = Op1.getSimpleValueType();
10263   MVT EVT = VT.getVectorElementType();
10264   unsigned n = VT.getVectorNumElements();
10265   SmallVector<SDValue, 8> ULTOp1;
10266
10267   for (unsigned i = 0; i < n; ++i) {
10268     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10269     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10270       return SDValue();
10271
10272     // Avoid underflow.
10273     APInt Val = Elt->getAPIntValue();
10274     if (Val == 0)
10275       return SDValue();
10276
10277     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10278   }
10279
10280   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10281 }
10282
10283 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10284                            SelectionDAG &DAG) {
10285   SDValue Op0 = Op.getOperand(0);
10286   SDValue Op1 = Op.getOperand(1);
10287   SDValue CC = Op.getOperand(2);
10288   MVT VT = Op.getSimpleValueType();
10289   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10290   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10291   SDLoc dl(Op);
10292
10293   if (isFP) {
10294 #ifndef NDEBUG
10295     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10296     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10297 #endif
10298
10299     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10300     unsigned Opc = X86ISD::CMPP;
10301     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10302       assert(VT.getVectorNumElements() <= 16);
10303       Opc = X86ISD::CMPM;
10304     }
10305     // In the two special cases we can't handle, emit two comparisons.
10306     if (SSECC == 8) {
10307       unsigned CC0, CC1;
10308       unsigned CombineOpc;
10309       if (SetCCOpcode == ISD::SETUEQ) {
10310         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10311       } else {
10312         assert(SetCCOpcode == ISD::SETONE);
10313         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10314       }
10315
10316       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10317                                  DAG.getConstant(CC0, MVT::i8));
10318       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10319                                  DAG.getConstant(CC1, MVT::i8));
10320       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10321     }
10322     // Handle all other FP comparisons here.
10323     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10324                        DAG.getConstant(SSECC, MVT::i8));
10325   }
10326
10327   // Break 256-bit integer vector compare into smaller ones.
10328   if (VT.is256BitVector() && !Subtarget->hasInt256())
10329     return Lower256IntVSETCC(Op, DAG);
10330
10331   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10332   EVT OpVT = Op1.getValueType();
10333   if (Subtarget->hasAVX512()) {
10334     if (Op1.getValueType().is512BitVector() ||
10335         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10336       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10337
10338     // In AVX-512 architecture setcc returns mask with i1 elements,
10339     // But there is no compare instruction for i8 and i16 elements.
10340     // We are not talking about 512-bit operands in this case, these
10341     // types are illegal.
10342     if (MaskResult &&
10343         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10344          OpVT.getVectorElementType().getSizeInBits() >= 8))
10345       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10346                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10347   }
10348
10349   // We are handling one of the integer comparisons here.  Since SSE only has
10350   // GT and EQ comparisons for integer, swapping operands and multiple
10351   // operations may be required for some comparisons.
10352   unsigned Opc;
10353   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10354   bool Subus = false;
10355
10356   switch (SetCCOpcode) {
10357   default: llvm_unreachable("Unexpected SETCC condition");
10358   case ISD::SETNE:  Invert = true;
10359   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10360   case ISD::SETLT:  Swap = true;
10361   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10362   case ISD::SETGE:  Swap = true;
10363   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10364                     Invert = true; break;
10365   case ISD::SETULT: Swap = true;
10366   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10367                     FlipSigns = true; break;
10368   case ISD::SETUGE: Swap = true;
10369   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10370                     FlipSigns = true; Invert = true; break;
10371   }
10372
10373   // Special case: Use min/max operations for SETULE/SETUGE
10374   MVT VET = VT.getVectorElementType();
10375   bool hasMinMax =
10376        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10377     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10378
10379   if (hasMinMax) {
10380     switch (SetCCOpcode) {
10381     default: break;
10382     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10383     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10384     }
10385
10386     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10387   }
10388
10389   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10390   if (!MinMax && hasSubus) {
10391     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10392     // Op0 u<= Op1:
10393     //   t = psubus Op0, Op1
10394     //   pcmpeq t, <0..0>
10395     switch (SetCCOpcode) {
10396     default: break;
10397     case ISD::SETULT: {
10398       // If the comparison is against a constant we can turn this into a
10399       // setule.  With psubus, setule does not require a swap.  This is
10400       // beneficial because the constant in the register is no longer
10401       // destructed as the destination so it can be hoisted out of a loop.
10402       // Only do this pre-AVX since vpcmp* is no longer destructive.
10403       if (Subtarget->hasAVX())
10404         break;
10405       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10406       if (ULEOp1.getNode()) {
10407         Op1 = ULEOp1;
10408         Subus = true; Invert = false; Swap = false;
10409       }
10410       break;
10411     }
10412     // Psubus is better than flip-sign because it requires no inversion.
10413     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10414     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10415     }
10416
10417     if (Subus) {
10418       Opc = X86ISD::SUBUS;
10419       FlipSigns = false;
10420     }
10421   }
10422
10423   if (Swap)
10424     std::swap(Op0, Op1);
10425
10426   // Check that the operation in question is available (most are plain SSE2,
10427   // but PCMPGTQ and PCMPEQQ have different requirements).
10428   if (VT == MVT::v2i64) {
10429     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10430       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10431
10432       // First cast everything to the right type.
10433       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10434       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10435
10436       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10437       // bits of the inputs before performing those operations. The lower
10438       // compare is always unsigned.
10439       SDValue SB;
10440       if (FlipSigns) {
10441         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10442       } else {
10443         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10444         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10445         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10446                          Sign, Zero, Sign, Zero);
10447       }
10448       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10449       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10450
10451       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10452       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10453       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10454
10455       // Create masks for only the low parts/high parts of the 64 bit integers.
10456       static const int MaskHi[] = { 1, 1, 3, 3 };
10457       static const int MaskLo[] = { 0, 0, 2, 2 };
10458       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10459       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10460       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10461
10462       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10463       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10464
10465       if (Invert)
10466         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10467
10468       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10469     }
10470
10471     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10472       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10473       // pcmpeqd + pshufd + pand.
10474       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10475
10476       // First cast everything to the right type.
10477       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10478       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10479
10480       // Do the compare.
10481       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10482
10483       // Make sure the lower and upper halves are both all-ones.
10484       static const int Mask[] = { 1, 0, 3, 2 };
10485       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10486       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10487
10488       if (Invert)
10489         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10490
10491       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10492     }
10493   }
10494
10495   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10496   // bits of the inputs before performing those operations.
10497   if (FlipSigns) {
10498     EVT EltVT = VT.getVectorElementType();
10499     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10500     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10501     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10502   }
10503
10504   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10505
10506   // If the logical-not of the result is required, perform that now.
10507   if (Invert)
10508     Result = DAG.getNOT(dl, Result, VT);
10509
10510   if (MinMax)
10511     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10512
10513   if (Subus)
10514     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10515                          getZeroVector(VT, Subtarget, DAG, dl));
10516
10517   return Result;
10518 }
10519
10520 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10521
10522   MVT VT = Op.getSimpleValueType();
10523
10524   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10525
10526   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10527          && "SetCC type must be 8-bit or 1-bit integer");
10528   SDValue Op0 = Op.getOperand(0);
10529   SDValue Op1 = Op.getOperand(1);
10530   SDLoc dl(Op);
10531   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10532
10533   // Optimize to BT if possible.
10534   // Lower (X & (1 << N)) == 0 to BT(X, N).
10535   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10536   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10537   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10538       Op1.getOpcode() == ISD::Constant &&
10539       cast<ConstantSDNode>(Op1)->isNullValue() &&
10540       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10541     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10542     if (NewSetCC.getNode())
10543       return NewSetCC;
10544   }
10545
10546   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10547   // these.
10548   if (Op1.getOpcode() == ISD::Constant &&
10549       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10550        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10551       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10552
10553     // If the input is a setcc, then reuse the input setcc or use a new one with
10554     // the inverted condition.
10555     if (Op0.getOpcode() == X86ISD::SETCC) {
10556       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10557       bool Invert = (CC == ISD::SETNE) ^
10558         cast<ConstantSDNode>(Op1)->isNullValue();
10559       if (!Invert)
10560         return Op0;
10561
10562       CCode = X86::GetOppositeBranchCondition(CCode);
10563       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10564                                   DAG.getConstant(CCode, MVT::i8),
10565                                   Op0.getOperand(1));
10566       if (VT == MVT::i1)
10567         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10568       return SetCC;
10569     }
10570   }
10571   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10572       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10573       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10574
10575     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10576     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10577   }
10578
10579   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10580   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10581   if (X86CC == X86::COND_INVALID)
10582     return SDValue();
10583
10584   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10585   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10586   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10587                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10588   if (VT == MVT::i1)
10589     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10590   return SetCC;
10591 }
10592
10593 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10594 static bool isX86LogicalCmp(SDValue Op) {
10595   unsigned Opc = Op.getNode()->getOpcode();
10596   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10597       Opc == X86ISD::SAHF)
10598     return true;
10599   if (Op.getResNo() == 1 &&
10600       (Opc == X86ISD::ADD ||
10601        Opc == X86ISD::SUB ||
10602        Opc == X86ISD::ADC ||
10603        Opc == X86ISD::SBB ||
10604        Opc == X86ISD::SMUL ||
10605        Opc == X86ISD::UMUL ||
10606        Opc == X86ISD::INC ||
10607        Opc == X86ISD::DEC ||
10608        Opc == X86ISD::OR ||
10609        Opc == X86ISD::XOR ||
10610        Opc == X86ISD::AND))
10611     return true;
10612
10613   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10614     return true;
10615
10616   return false;
10617 }
10618
10619 static bool isZero(SDValue V) {
10620   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10621   return C && C->isNullValue();
10622 }
10623
10624 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10625   if (V.getOpcode() != ISD::TRUNCATE)
10626     return false;
10627
10628   SDValue VOp0 = V.getOperand(0);
10629   unsigned InBits = VOp0.getValueSizeInBits();
10630   unsigned Bits = V.getValueSizeInBits();
10631   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10632 }
10633
10634 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10635   bool addTest = true;
10636   SDValue Cond  = Op.getOperand(0);
10637   SDValue Op1 = Op.getOperand(1);
10638   SDValue Op2 = Op.getOperand(2);
10639   SDLoc DL(Op);
10640   EVT VT = Op1.getValueType();
10641   SDValue CC;
10642
10643   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10644   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10645   // sequence later on.
10646   if (Cond.getOpcode() == ISD::SETCC &&
10647       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10648        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10649       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10650     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10651     int SSECC = translateX86FSETCC(
10652         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10653
10654     if (SSECC != 8) {
10655       if (Subtarget->hasAVX512()) {
10656         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10657                                   DAG.getConstant(SSECC, MVT::i8));
10658         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10659       }
10660       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10661                                 DAG.getConstant(SSECC, MVT::i8));
10662       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10663       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10664       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10665     }
10666   }
10667
10668   if (Cond.getOpcode() == ISD::SETCC) {
10669     SDValue NewCond = LowerSETCC(Cond, DAG);
10670     if (NewCond.getNode())
10671       Cond = NewCond;
10672   }
10673
10674   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10675   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10676   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10677   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10678   if (Cond.getOpcode() == X86ISD::SETCC &&
10679       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10680       isZero(Cond.getOperand(1).getOperand(1))) {
10681     SDValue Cmp = Cond.getOperand(1);
10682
10683     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10684
10685     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10686         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10687       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10688
10689       SDValue CmpOp0 = Cmp.getOperand(0);
10690       // Apply further optimizations for special cases
10691       // (select (x != 0), -1, 0) -> neg & sbb
10692       // (select (x == 0), 0, -1) -> neg & sbb
10693       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10694         if (YC->isNullValue() &&
10695             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10696           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10697           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10698                                     DAG.getConstant(0, CmpOp0.getValueType()),
10699                                     CmpOp0);
10700           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10701                                     DAG.getConstant(X86::COND_B, MVT::i8),
10702                                     SDValue(Neg.getNode(), 1));
10703           return Res;
10704         }
10705
10706       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10707                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10708       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10709
10710       SDValue Res =   // Res = 0 or -1.
10711         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10712                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10713
10714       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10715         Res = DAG.getNOT(DL, Res, Res.getValueType());
10716
10717       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10718       if (!N2C || !N2C->isNullValue())
10719         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10720       return Res;
10721     }
10722   }
10723
10724   // Look past (and (setcc_carry (cmp ...)), 1).
10725   if (Cond.getOpcode() == ISD::AND &&
10726       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10727     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10728     if (C && C->getAPIntValue() == 1)
10729       Cond = Cond.getOperand(0);
10730   }
10731
10732   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10733   // setting operand in place of the X86ISD::SETCC.
10734   unsigned CondOpcode = Cond.getOpcode();
10735   if (CondOpcode == X86ISD::SETCC ||
10736       CondOpcode == X86ISD::SETCC_CARRY) {
10737     CC = Cond.getOperand(0);
10738
10739     SDValue Cmp = Cond.getOperand(1);
10740     unsigned Opc = Cmp.getOpcode();
10741     MVT VT = Op.getSimpleValueType();
10742
10743     bool IllegalFPCMov = false;
10744     if (VT.isFloatingPoint() && !VT.isVector() &&
10745         !isScalarFPTypeInSSEReg(VT))  // FPStack?
10746       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
10747
10748     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
10749         Opc == X86ISD::BT) { // FIXME
10750       Cond = Cmp;
10751       addTest = false;
10752     }
10753   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
10754              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
10755              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
10756               Cond.getOperand(0).getValueType() != MVT::i8)) {
10757     SDValue LHS = Cond.getOperand(0);
10758     SDValue RHS = Cond.getOperand(1);
10759     unsigned X86Opcode;
10760     unsigned X86Cond;
10761     SDVTList VTs;
10762     switch (CondOpcode) {
10763     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
10764     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
10765     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
10766     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
10767     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
10768     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
10769     default: llvm_unreachable("unexpected overflowing operator");
10770     }
10771     if (CondOpcode == ISD::UMULO)
10772       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
10773                           MVT::i32);
10774     else
10775       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
10776
10777     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
10778
10779     if (CondOpcode == ISD::UMULO)
10780       Cond = X86Op.getValue(2);
10781     else
10782       Cond = X86Op.getValue(1);
10783
10784     CC = DAG.getConstant(X86Cond, MVT::i8);
10785     addTest = false;
10786   }
10787
10788   if (addTest) {
10789     // Look pass the truncate if the high bits are known zero.
10790     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10791         Cond = Cond.getOperand(0);
10792
10793     // We know the result of AND is compared against zero. Try to match
10794     // it to BT.
10795     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10796       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
10797       if (NewSetCC.getNode()) {
10798         CC = NewSetCC.getOperand(0);
10799         Cond = NewSetCC.getOperand(1);
10800         addTest = false;
10801       }
10802     }
10803   }
10804
10805   if (addTest) {
10806     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10807     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
10808   }
10809
10810   // a <  b ? -1 :  0 -> RES = ~setcc_carry
10811   // a <  b ?  0 : -1 -> RES = setcc_carry
10812   // a >= b ? -1 :  0 -> RES = setcc_carry
10813   // a >= b ?  0 : -1 -> RES = ~setcc_carry
10814   if (Cond.getOpcode() == X86ISD::SUB) {
10815     Cond = ConvertCmpIfNecessary(Cond, DAG);
10816     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
10817
10818     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
10819         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
10820       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10821                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
10822       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
10823         return DAG.getNOT(DL, Res, Res.getValueType());
10824       return Res;
10825     }
10826   }
10827
10828   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
10829   // widen the cmov and push the truncate through. This avoids introducing a new
10830   // branch during isel and doesn't add any extensions.
10831   if (Op.getValueType() == MVT::i8 &&
10832       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
10833     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
10834     if (T1.getValueType() == T2.getValueType() &&
10835         // Blacklist CopyFromReg to avoid partial register stalls.
10836         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
10837       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
10838       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
10839       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
10840     }
10841   }
10842
10843   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
10844   // condition is true.
10845   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
10846   SDValue Ops[] = { Op2, Op1, CC, Cond };
10847   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
10848 }
10849
10850 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
10851   MVT VT = Op->getSimpleValueType(0);
10852   SDValue In = Op->getOperand(0);
10853   MVT InVT = In.getSimpleValueType();
10854   SDLoc dl(Op);
10855
10856   unsigned int NumElts = VT.getVectorNumElements();
10857   if (NumElts != 8 && NumElts != 16)
10858     return SDValue();
10859
10860   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
10861     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10862
10863   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10864   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10865
10866   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
10867   Constant *C = ConstantInt::get(*DAG.getContext(),
10868     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
10869
10870   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
10871   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10872   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
10873                           MachinePointerInfo::getConstantPool(),
10874                           false, false, false, Alignment);
10875   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
10876   if (VT.is512BitVector())
10877     return Brcst;
10878   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
10879 }
10880
10881 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10882                                 SelectionDAG &DAG) {
10883   MVT VT = Op->getSimpleValueType(0);
10884   SDValue In = Op->getOperand(0);
10885   MVT InVT = In.getSimpleValueType();
10886   SDLoc dl(Op);
10887
10888   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
10889     return LowerSIGN_EXTEND_AVX512(Op, DAG);
10890
10891   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
10892       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
10893       (VT != MVT::v16i16 || InVT != MVT::v16i8))
10894     return SDValue();
10895
10896   if (Subtarget->hasInt256())
10897     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
10898
10899   // Optimize vectors in AVX mode
10900   // Sign extend  v8i16 to v8i32 and
10901   //              v4i32 to v4i64
10902   //
10903   // Divide input vector into two parts
10904   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
10905   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
10906   // concat the vectors to original VT
10907
10908   unsigned NumElems = InVT.getVectorNumElements();
10909   SDValue Undef = DAG.getUNDEF(InVT);
10910
10911   SmallVector<int,8> ShufMask1(NumElems, -1);
10912   for (unsigned i = 0; i != NumElems/2; ++i)
10913     ShufMask1[i] = i;
10914
10915   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
10916
10917   SmallVector<int,8> ShufMask2(NumElems, -1);
10918   for (unsigned i = 0; i != NumElems/2; ++i)
10919     ShufMask2[i] = i + NumElems/2;
10920
10921   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
10922
10923   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
10924                                 VT.getVectorNumElements()/2);
10925
10926   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
10927   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
10928
10929   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
10930 }
10931
10932 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
10933 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
10934 // from the AND / OR.
10935 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
10936   Opc = Op.getOpcode();
10937   if (Opc != ISD::OR && Opc != ISD::AND)
10938     return false;
10939   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10940           Op.getOperand(0).hasOneUse() &&
10941           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
10942           Op.getOperand(1).hasOneUse());
10943 }
10944
10945 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
10946 // 1 and that the SETCC node has a single use.
10947 static bool isXor1OfSetCC(SDValue Op) {
10948   if (Op.getOpcode() != ISD::XOR)
10949     return false;
10950   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10951   if (N1C && N1C->getAPIntValue() == 1) {
10952     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
10953       Op.getOperand(0).hasOneUse();
10954   }
10955   return false;
10956 }
10957
10958 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
10959   bool addTest = true;
10960   SDValue Chain = Op.getOperand(0);
10961   SDValue Cond  = Op.getOperand(1);
10962   SDValue Dest  = Op.getOperand(2);
10963   SDLoc dl(Op);
10964   SDValue CC;
10965   bool Inverted = false;
10966
10967   if (Cond.getOpcode() == ISD::SETCC) {
10968     // Check for setcc([su]{add,sub,mul}o == 0).
10969     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
10970         isa<ConstantSDNode>(Cond.getOperand(1)) &&
10971         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
10972         Cond.getOperand(0).getResNo() == 1 &&
10973         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
10974          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
10975          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
10976          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
10977          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
10978          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
10979       Inverted = true;
10980       Cond = Cond.getOperand(0);
10981     } else {
10982       SDValue NewCond = LowerSETCC(Cond, DAG);
10983       if (NewCond.getNode())
10984         Cond = NewCond;
10985     }
10986   }
10987 #if 0
10988   // FIXME: LowerXALUO doesn't handle these!!
10989   else if (Cond.getOpcode() == X86ISD::ADD  ||
10990            Cond.getOpcode() == X86ISD::SUB  ||
10991            Cond.getOpcode() == X86ISD::SMUL ||
10992            Cond.getOpcode() == X86ISD::UMUL)
10993     Cond = LowerXALUO(Cond, DAG);
10994 #endif
10995
10996   // Look pass (and (setcc_carry (cmp ...)), 1).
10997   if (Cond.getOpcode() == ISD::AND &&
10998       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10999     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11000     if (C && C->getAPIntValue() == 1)
11001       Cond = Cond.getOperand(0);
11002   }
11003
11004   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11005   // setting operand in place of the X86ISD::SETCC.
11006   unsigned CondOpcode = Cond.getOpcode();
11007   if (CondOpcode == X86ISD::SETCC ||
11008       CondOpcode == X86ISD::SETCC_CARRY) {
11009     CC = Cond.getOperand(0);
11010
11011     SDValue Cmp = Cond.getOperand(1);
11012     unsigned Opc = Cmp.getOpcode();
11013     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11014     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11015       Cond = Cmp;
11016       addTest = false;
11017     } else {
11018       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11019       default: break;
11020       case X86::COND_O:
11021       case X86::COND_B:
11022         // These can only come from an arithmetic instruction with overflow,
11023         // e.g. SADDO, UADDO.
11024         Cond = Cond.getNode()->getOperand(1);
11025         addTest = false;
11026         break;
11027       }
11028     }
11029   }
11030   CondOpcode = Cond.getOpcode();
11031   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11032       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11033       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11034        Cond.getOperand(0).getValueType() != MVT::i8)) {
11035     SDValue LHS = Cond.getOperand(0);
11036     SDValue RHS = Cond.getOperand(1);
11037     unsigned X86Opcode;
11038     unsigned X86Cond;
11039     SDVTList VTs;
11040     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11041     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11042     // X86ISD::INC).
11043     switch (CondOpcode) {
11044     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11045     case ISD::SADDO:
11046       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11047         if (C->isOne()) {
11048           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11049           break;
11050         }
11051       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11052     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11053     case ISD::SSUBO:
11054       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11055         if (C->isOne()) {
11056           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11057           break;
11058         }
11059       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11060     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11061     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11062     default: llvm_unreachable("unexpected overflowing operator");
11063     }
11064     if (Inverted)
11065       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11066     if (CondOpcode == ISD::UMULO)
11067       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11068                           MVT::i32);
11069     else
11070       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11071
11072     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11073
11074     if (CondOpcode == ISD::UMULO)
11075       Cond = X86Op.getValue(2);
11076     else
11077       Cond = X86Op.getValue(1);
11078
11079     CC = DAG.getConstant(X86Cond, MVT::i8);
11080     addTest = false;
11081   } else {
11082     unsigned CondOpc;
11083     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11084       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11085       if (CondOpc == ISD::OR) {
11086         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11087         // two branches instead of an explicit OR instruction with a
11088         // separate test.
11089         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11090             isX86LogicalCmp(Cmp)) {
11091           CC = Cond.getOperand(0).getOperand(0);
11092           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11093                               Chain, Dest, CC, Cmp);
11094           CC = Cond.getOperand(1).getOperand(0);
11095           Cond = Cmp;
11096           addTest = false;
11097         }
11098       } else { // ISD::AND
11099         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11100         // two branches instead of an explicit AND instruction with a
11101         // separate test. However, we only do this if this block doesn't
11102         // have a fall-through edge, because this requires an explicit
11103         // jmp when the condition is false.
11104         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11105             isX86LogicalCmp(Cmp) &&
11106             Op.getNode()->hasOneUse()) {
11107           X86::CondCode CCode =
11108             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11109           CCode = X86::GetOppositeBranchCondition(CCode);
11110           CC = DAG.getConstant(CCode, MVT::i8);
11111           SDNode *User = *Op.getNode()->use_begin();
11112           // Look for an unconditional branch following this conditional branch.
11113           // We need this because we need to reverse the successors in order
11114           // to implement FCMP_OEQ.
11115           if (User->getOpcode() == ISD::BR) {
11116             SDValue FalseBB = User->getOperand(1);
11117             SDNode *NewBR =
11118               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11119             assert(NewBR == User);
11120             (void)NewBR;
11121             Dest = FalseBB;
11122
11123             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11124                                 Chain, Dest, CC, Cmp);
11125             X86::CondCode CCode =
11126               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11127             CCode = X86::GetOppositeBranchCondition(CCode);
11128             CC = DAG.getConstant(CCode, MVT::i8);
11129             Cond = Cmp;
11130             addTest = false;
11131           }
11132         }
11133       }
11134     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11135       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11136       // It should be transformed during dag combiner except when the condition
11137       // is set by a arithmetics with overflow node.
11138       X86::CondCode CCode =
11139         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11140       CCode = X86::GetOppositeBranchCondition(CCode);
11141       CC = DAG.getConstant(CCode, MVT::i8);
11142       Cond = Cond.getOperand(0).getOperand(1);
11143       addTest = false;
11144     } else if (Cond.getOpcode() == ISD::SETCC &&
11145                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11146       // For FCMP_OEQ, we can emit
11147       // two branches instead of an explicit AND instruction with a
11148       // separate test. However, we only do this if this block doesn't
11149       // have a fall-through edge, because this requires an explicit
11150       // jmp when the condition is false.
11151       if (Op.getNode()->hasOneUse()) {
11152         SDNode *User = *Op.getNode()->use_begin();
11153         // Look for an unconditional branch following this conditional branch.
11154         // We need this because we need to reverse the successors in order
11155         // to implement FCMP_OEQ.
11156         if (User->getOpcode() == ISD::BR) {
11157           SDValue FalseBB = User->getOperand(1);
11158           SDNode *NewBR =
11159             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11160           assert(NewBR == User);
11161           (void)NewBR;
11162           Dest = FalseBB;
11163
11164           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11165                                     Cond.getOperand(0), Cond.getOperand(1));
11166           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11167           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11168           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11169                               Chain, Dest, CC, Cmp);
11170           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11171           Cond = Cmp;
11172           addTest = false;
11173         }
11174       }
11175     } else if (Cond.getOpcode() == ISD::SETCC &&
11176                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11177       // For FCMP_UNE, we can emit
11178       // two branches instead of an explicit AND instruction with a
11179       // separate test. However, we only do this if this block doesn't
11180       // have a fall-through edge, because this requires an explicit
11181       // jmp when the condition is false.
11182       if (Op.getNode()->hasOneUse()) {
11183         SDNode *User = *Op.getNode()->use_begin();
11184         // Look for an unconditional branch following this conditional branch.
11185         // We need this because we need to reverse the successors in order
11186         // to implement FCMP_UNE.
11187         if (User->getOpcode() == ISD::BR) {
11188           SDValue FalseBB = User->getOperand(1);
11189           SDNode *NewBR =
11190             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11191           assert(NewBR == User);
11192           (void)NewBR;
11193
11194           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11195                                     Cond.getOperand(0), Cond.getOperand(1));
11196           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11197           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11198           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11199                               Chain, Dest, CC, Cmp);
11200           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11201           Cond = Cmp;
11202           addTest = false;
11203           Dest = FalseBB;
11204         }
11205       }
11206     }
11207   }
11208
11209   if (addTest) {
11210     // Look pass the truncate if the high bits are known zero.
11211     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11212         Cond = Cond.getOperand(0);
11213
11214     // We know the result of AND is compared against zero. Try to match
11215     // it to BT.
11216     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11217       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11218       if (NewSetCC.getNode()) {
11219         CC = NewSetCC.getOperand(0);
11220         Cond = NewSetCC.getOperand(1);
11221         addTest = false;
11222       }
11223     }
11224   }
11225
11226   if (addTest) {
11227     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11228     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11229   }
11230   Cond = ConvertCmpIfNecessary(Cond, DAG);
11231   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11232                      Chain, Dest, CC, Cond);
11233 }
11234
11235 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11236 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11237 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11238 // that the guard pages used by the OS virtual memory manager are allocated in
11239 // correct sequence.
11240 SDValue
11241 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11242                                            SelectionDAG &DAG) const {
11243   MachineFunction &MF = DAG.getMachineFunction();
11244   bool SplitStack = MF.shouldSplitStack();
11245   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11246                SplitStack;
11247   SDLoc dl(Op);
11248
11249   if (!Lower) {
11250     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11251     SDNode* Node = Op.getNode();
11252
11253     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11254     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11255         " not tell us which reg is the stack pointer!");
11256     EVT VT = Node->getValueType(0);
11257     SDValue Tmp1 = SDValue(Node, 0);
11258     SDValue Tmp2 = SDValue(Node, 1);
11259     SDValue Tmp3 = Node->getOperand(2);
11260     SDValue Chain = Tmp1.getOperand(0);
11261
11262     // Chain the dynamic stack allocation so that it doesn't modify the stack
11263     // pointer when other instructions are using the stack.
11264     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11265         SDLoc(Node));
11266
11267     SDValue Size = Tmp2.getOperand(1);
11268     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11269     Chain = SP.getValue(1);
11270     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11271     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11272     unsigned StackAlign = TFI.getStackAlignment();
11273     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11274     if (Align > StackAlign)
11275       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11276           DAG.getConstant(-(uint64_t)Align, VT));
11277     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11278
11279     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11280         DAG.getIntPtrConstant(0, true), SDValue(),
11281         SDLoc(Node));
11282
11283     SDValue Ops[2] = { Tmp1, Tmp2 };
11284     return DAG.getMergeValues(Ops, 2, dl);
11285   }
11286
11287   // Get the inputs.
11288   SDValue Chain = Op.getOperand(0);
11289   SDValue Size  = Op.getOperand(1);
11290   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11291   EVT VT = Op.getNode()->getValueType(0);
11292
11293   bool Is64Bit = Subtarget->is64Bit();
11294   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11295
11296   if (SplitStack) {
11297     MachineRegisterInfo &MRI = MF.getRegInfo();
11298
11299     if (Is64Bit) {
11300       // The 64 bit implementation of segmented stacks needs to clobber both r10
11301       // r11. This makes it impossible to use it along with nested parameters.
11302       const Function *F = MF.getFunction();
11303
11304       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11305            I != E; ++I)
11306         if (I->hasNestAttr())
11307           report_fatal_error("Cannot use segmented stacks with functions that "
11308                              "have nested arguments.");
11309     }
11310
11311     const TargetRegisterClass *AddrRegClass =
11312       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11313     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11314     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11315     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11316                                 DAG.getRegister(Vreg, SPTy));
11317     SDValue Ops1[2] = { Value, Chain };
11318     return DAG.getMergeValues(Ops1, 2, dl);
11319   } else {
11320     SDValue Flag;
11321     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11322
11323     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11324     Flag = Chain.getValue(1);
11325     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11326
11327     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11328
11329     const X86RegisterInfo *RegInfo =
11330       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11331     unsigned SPReg = RegInfo->getStackRegister();
11332     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11333     Chain = SP.getValue(1);
11334
11335     if (Align) {
11336       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11337                        DAG.getConstant(-(uint64_t)Align, VT));
11338       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11339     }
11340
11341     SDValue Ops1[2] = { SP, Chain };
11342     return DAG.getMergeValues(Ops1, 2, dl);
11343   }
11344 }
11345
11346 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11347   MachineFunction &MF = DAG.getMachineFunction();
11348   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11349
11350   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11351   SDLoc DL(Op);
11352
11353   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11354     // vastart just stores the address of the VarArgsFrameIndex slot into the
11355     // memory location argument.
11356     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11357                                    getPointerTy());
11358     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11359                         MachinePointerInfo(SV), false, false, 0);
11360   }
11361
11362   // __va_list_tag:
11363   //   gp_offset         (0 - 6 * 8)
11364   //   fp_offset         (48 - 48 + 8 * 16)
11365   //   overflow_arg_area (point to parameters coming in memory).
11366   //   reg_save_area
11367   SmallVector<SDValue, 8> MemOps;
11368   SDValue FIN = Op.getOperand(1);
11369   // Store gp_offset
11370   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11371                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11372                                                MVT::i32),
11373                                FIN, MachinePointerInfo(SV), false, false, 0);
11374   MemOps.push_back(Store);
11375
11376   // Store fp_offset
11377   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11378                     FIN, DAG.getIntPtrConstant(4));
11379   Store = DAG.getStore(Op.getOperand(0), DL,
11380                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11381                                        MVT::i32),
11382                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11383   MemOps.push_back(Store);
11384
11385   // Store ptr to overflow_arg_area
11386   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11387                     FIN, DAG.getIntPtrConstant(4));
11388   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11389                                     getPointerTy());
11390   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11391                        MachinePointerInfo(SV, 8),
11392                        false, false, 0);
11393   MemOps.push_back(Store);
11394
11395   // Store ptr to reg_save_area.
11396   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11397                     FIN, DAG.getIntPtrConstant(8));
11398   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11399                                     getPointerTy());
11400   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11401                        MachinePointerInfo(SV, 16), false, false, 0);
11402   MemOps.push_back(Store);
11403   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11404 }
11405
11406 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11407   assert(Subtarget->is64Bit() &&
11408          "LowerVAARG only handles 64-bit va_arg!");
11409   assert((Subtarget->isTargetLinux() ||
11410           Subtarget->isTargetDarwin()) &&
11411           "Unhandled target in LowerVAARG");
11412   assert(Op.getNode()->getNumOperands() == 4);
11413   SDValue Chain = Op.getOperand(0);
11414   SDValue SrcPtr = Op.getOperand(1);
11415   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11416   unsigned Align = Op.getConstantOperandVal(3);
11417   SDLoc dl(Op);
11418
11419   EVT ArgVT = Op.getNode()->getValueType(0);
11420   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11421   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11422   uint8_t ArgMode;
11423
11424   // Decide which area this value should be read from.
11425   // TODO: Implement the AMD64 ABI in its entirety. This simple
11426   // selection mechanism works only for the basic types.
11427   if (ArgVT == MVT::f80) {
11428     llvm_unreachable("va_arg for f80 not yet implemented");
11429   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11430     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11431   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11432     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11433   } else {
11434     llvm_unreachable("Unhandled argument type in LowerVAARG");
11435   }
11436
11437   if (ArgMode == 2) {
11438     // Sanity Check: Make sure using fp_offset makes sense.
11439     assert(!getTargetMachine().Options.UseSoftFloat &&
11440            !(DAG.getMachineFunction()
11441                 .getFunction()->getAttributes()
11442                 .hasAttribute(AttributeSet::FunctionIndex,
11443                               Attribute::NoImplicitFloat)) &&
11444            Subtarget->hasSSE1());
11445   }
11446
11447   // Insert VAARG_64 node into the DAG
11448   // VAARG_64 returns two values: Variable Argument Address, Chain
11449   SmallVector<SDValue, 11> InstOps;
11450   InstOps.push_back(Chain);
11451   InstOps.push_back(SrcPtr);
11452   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11453   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11454   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11455   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11456   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11457                                           VTs, InstOps, MVT::i64,
11458                                           MachinePointerInfo(SV),
11459                                           /*Align=*/0,
11460                                           /*Volatile=*/false,
11461                                           /*ReadMem=*/true,
11462                                           /*WriteMem=*/true);
11463   Chain = VAARG.getValue(1);
11464
11465   // Load the next argument and return it
11466   return DAG.getLoad(ArgVT, dl,
11467                      Chain,
11468                      VAARG,
11469                      MachinePointerInfo(),
11470                      false, false, false, 0);
11471 }
11472
11473 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11474                            SelectionDAG &DAG) {
11475   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11476   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11477   SDValue Chain = Op.getOperand(0);
11478   SDValue DstPtr = Op.getOperand(1);
11479   SDValue SrcPtr = Op.getOperand(2);
11480   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11481   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11482   SDLoc DL(Op);
11483
11484   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11485                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11486                        false,
11487                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11488 }
11489
11490 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11491 // amount is a constant. Takes immediate version of shift as input.
11492 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11493                                           SDValue SrcOp, uint64_t ShiftAmt,
11494                                           SelectionDAG &DAG) {
11495   MVT ElementType = VT.getVectorElementType();
11496
11497   // Check for ShiftAmt >= element width
11498   if (ShiftAmt >= ElementType.getSizeInBits()) {
11499     if (Opc == X86ISD::VSRAI)
11500       ShiftAmt = ElementType.getSizeInBits() - 1;
11501     else
11502       return DAG.getConstant(0, VT);
11503   }
11504
11505   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11506          && "Unknown target vector shift-by-constant node");
11507
11508   // Fold this packed vector shift into a build vector if SrcOp is a
11509   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11510   if (VT == SrcOp.getSimpleValueType() &&
11511       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11512     SmallVector<SDValue, 8> Elts;
11513     unsigned NumElts = SrcOp->getNumOperands();
11514     ConstantSDNode *ND;
11515
11516     switch(Opc) {
11517     default: llvm_unreachable(0);
11518     case X86ISD::VSHLI:
11519       for (unsigned i=0; i!=NumElts; ++i) {
11520         SDValue CurrentOp = SrcOp->getOperand(i);
11521         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11522           Elts.push_back(CurrentOp);
11523           continue;
11524         }
11525         ND = cast<ConstantSDNode>(CurrentOp);
11526         const APInt &C = ND->getAPIntValue();
11527         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11528       }
11529       break;
11530     case X86ISD::VSRLI:
11531       for (unsigned i=0; i!=NumElts; ++i) {
11532         SDValue CurrentOp = SrcOp->getOperand(i);
11533         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11534           Elts.push_back(CurrentOp);
11535           continue;
11536         }
11537         ND = cast<ConstantSDNode>(CurrentOp);
11538         const APInt &C = ND->getAPIntValue();
11539         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11540       }
11541       break;
11542     case X86ISD::VSRAI:
11543       for (unsigned i=0; i!=NumElts; ++i) {
11544         SDValue CurrentOp = SrcOp->getOperand(i);
11545         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11546           Elts.push_back(CurrentOp);
11547           continue;
11548         }
11549         ND = cast<ConstantSDNode>(CurrentOp);
11550         const APInt &C = ND->getAPIntValue();
11551         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11552       }
11553       break;
11554     }
11555
11556     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11557   }
11558
11559   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11560 }
11561
11562 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11563 // may or may not be a constant. Takes immediate version of shift as input.
11564 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11565                                    SDValue SrcOp, SDValue ShAmt,
11566                                    SelectionDAG &DAG) {
11567   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11568
11569   // Catch shift-by-constant.
11570   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11571     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11572                                       CShAmt->getZExtValue(), DAG);
11573
11574   // Change opcode to non-immediate version
11575   switch (Opc) {
11576     default: llvm_unreachable("Unknown target vector shift node");
11577     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11578     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11579     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11580   }
11581
11582   // Need to build a vector containing shift amount
11583   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11584   SDValue ShOps[4];
11585   ShOps[0] = ShAmt;
11586   ShOps[1] = DAG.getConstant(0, MVT::i32);
11587   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11588   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11589
11590   // The return type has to be a 128-bit type with the same element
11591   // type as the input type.
11592   MVT EltVT = VT.getVectorElementType();
11593   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11594
11595   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11596   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11597 }
11598
11599 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11600   SDLoc dl(Op);
11601   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11602   switch (IntNo) {
11603   default: return SDValue();    // Don't custom lower most intrinsics.
11604   // Comparison intrinsics.
11605   case Intrinsic::x86_sse_comieq_ss:
11606   case Intrinsic::x86_sse_comilt_ss:
11607   case Intrinsic::x86_sse_comile_ss:
11608   case Intrinsic::x86_sse_comigt_ss:
11609   case Intrinsic::x86_sse_comige_ss:
11610   case Intrinsic::x86_sse_comineq_ss:
11611   case Intrinsic::x86_sse_ucomieq_ss:
11612   case Intrinsic::x86_sse_ucomilt_ss:
11613   case Intrinsic::x86_sse_ucomile_ss:
11614   case Intrinsic::x86_sse_ucomigt_ss:
11615   case Intrinsic::x86_sse_ucomige_ss:
11616   case Intrinsic::x86_sse_ucomineq_ss:
11617   case Intrinsic::x86_sse2_comieq_sd:
11618   case Intrinsic::x86_sse2_comilt_sd:
11619   case Intrinsic::x86_sse2_comile_sd:
11620   case Intrinsic::x86_sse2_comigt_sd:
11621   case Intrinsic::x86_sse2_comige_sd:
11622   case Intrinsic::x86_sse2_comineq_sd:
11623   case Intrinsic::x86_sse2_ucomieq_sd:
11624   case Intrinsic::x86_sse2_ucomilt_sd:
11625   case Intrinsic::x86_sse2_ucomile_sd:
11626   case Intrinsic::x86_sse2_ucomigt_sd:
11627   case Intrinsic::x86_sse2_ucomige_sd:
11628   case Intrinsic::x86_sse2_ucomineq_sd: {
11629     unsigned Opc;
11630     ISD::CondCode CC;
11631     switch (IntNo) {
11632     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11633     case Intrinsic::x86_sse_comieq_ss:
11634     case Intrinsic::x86_sse2_comieq_sd:
11635       Opc = X86ISD::COMI;
11636       CC = ISD::SETEQ;
11637       break;
11638     case Intrinsic::x86_sse_comilt_ss:
11639     case Intrinsic::x86_sse2_comilt_sd:
11640       Opc = X86ISD::COMI;
11641       CC = ISD::SETLT;
11642       break;
11643     case Intrinsic::x86_sse_comile_ss:
11644     case Intrinsic::x86_sse2_comile_sd:
11645       Opc = X86ISD::COMI;
11646       CC = ISD::SETLE;
11647       break;
11648     case Intrinsic::x86_sse_comigt_ss:
11649     case Intrinsic::x86_sse2_comigt_sd:
11650       Opc = X86ISD::COMI;
11651       CC = ISD::SETGT;
11652       break;
11653     case Intrinsic::x86_sse_comige_ss:
11654     case Intrinsic::x86_sse2_comige_sd:
11655       Opc = X86ISD::COMI;
11656       CC = ISD::SETGE;
11657       break;
11658     case Intrinsic::x86_sse_comineq_ss:
11659     case Intrinsic::x86_sse2_comineq_sd:
11660       Opc = X86ISD::COMI;
11661       CC = ISD::SETNE;
11662       break;
11663     case Intrinsic::x86_sse_ucomieq_ss:
11664     case Intrinsic::x86_sse2_ucomieq_sd:
11665       Opc = X86ISD::UCOMI;
11666       CC = ISD::SETEQ;
11667       break;
11668     case Intrinsic::x86_sse_ucomilt_ss:
11669     case Intrinsic::x86_sse2_ucomilt_sd:
11670       Opc = X86ISD::UCOMI;
11671       CC = ISD::SETLT;
11672       break;
11673     case Intrinsic::x86_sse_ucomile_ss:
11674     case Intrinsic::x86_sse2_ucomile_sd:
11675       Opc = X86ISD::UCOMI;
11676       CC = ISD::SETLE;
11677       break;
11678     case Intrinsic::x86_sse_ucomigt_ss:
11679     case Intrinsic::x86_sse2_ucomigt_sd:
11680       Opc = X86ISD::UCOMI;
11681       CC = ISD::SETGT;
11682       break;
11683     case Intrinsic::x86_sse_ucomige_ss:
11684     case Intrinsic::x86_sse2_ucomige_sd:
11685       Opc = X86ISD::UCOMI;
11686       CC = ISD::SETGE;
11687       break;
11688     case Intrinsic::x86_sse_ucomineq_ss:
11689     case Intrinsic::x86_sse2_ucomineq_sd:
11690       Opc = X86ISD::UCOMI;
11691       CC = ISD::SETNE;
11692       break;
11693     }
11694
11695     SDValue LHS = Op.getOperand(1);
11696     SDValue RHS = Op.getOperand(2);
11697     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11698     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11699     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11700     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11701                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11702     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11703   }
11704
11705   // Arithmetic intrinsics.
11706   case Intrinsic::x86_sse2_pmulu_dq:
11707   case Intrinsic::x86_avx2_pmulu_dq:
11708     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11709                        Op.getOperand(1), Op.getOperand(2));
11710
11711   case Intrinsic::x86_sse41_pmuldq:
11712   case Intrinsic::x86_avx2_pmul_dq:
11713     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11714                        Op.getOperand(1), Op.getOperand(2));
11715
11716   case Intrinsic::x86_sse2_pmulhu_w:
11717   case Intrinsic::x86_avx2_pmulhu_w:
11718     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11719                        Op.getOperand(1), Op.getOperand(2));
11720
11721   case Intrinsic::x86_sse2_pmulh_w:
11722   case Intrinsic::x86_avx2_pmulh_w:
11723     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11724                        Op.getOperand(1), Op.getOperand(2));
11725
11726   // SSE2/AVX2 sub with unsigned saturation intrinsics
11727   case Intrinsic::x86_sse2_psubus_b:
11728   case Intrinsic::x86_sse2_psubus_w:
11729   case Intrinsic::x86_avx2_psubus_b:
11730   case Intrinsic::x86_avx2_psubus_w:
11731     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11732                        Op.getOperand(1), Op.getOperand(2));
11733
11734   // SSE3/AVX horizontal add/sub intrinsics
11735   case Intrinsic::x86_sse3_hadd_ps:
11736   case Intrinsic::x86_sse3_hadd_pd:
11737   case Intrinsic::x86_avx_hadd_ps_256:
11738   case Intrinsic::x86_avx_hadd_pd_256:
11739   case Intrinsic::x86_sse3_hsub_ps:
11740   case Intrinsic::x86_sse3_hsub_pd:
11741   case Intrinsic::x86_avx_hsub_ps_256:
11742   case Intrinsic::x86_avx_hsub_pd_256:
11743   case Intrinsic::x86_ssse3_phadd_w_128:
11744   case Intrinsic::x86_ssse3_phadd_d_128:
11745   case Intrinsic::x86_avx2_phadd_w:
11746   case Intrinsic::x86_avx2_phadd_d:
11747   case Intrinsic::x86_ssse3_phsub_w_128:
11748   case Intrinsic::x86_ssse3_phsub_d_128:
11749   case Intrinsic::x86_avx2_phsub_w:
11750   case Intrinsic::x86_avx2_phsub_d: {
11751     unsigned Opcode;
11752     switch (IntNo) {
11753     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11754     case Intrinsic::x86_sse3_hadd_ps:
11755     case Intrinsic::x86_sse3_hadd_pd:
11756     case Intrinsic::x86_avx_hadd_ps_256:
11757     case Intrinsic::x86_avx_hadd_pd_256:
11758       Opcode = X86ISD::FHADD;
11759       break;
11760     case Intrinsic::x86_sse3_hsub_ps:
11761     case Intrinsic::x86_sse3_hsub_pd:
11762     case Intrinsic::x86_avx_hsub_ps_256:
11763     case Intrinsic::x86_avx_hsub_pd_256:
11764       Opcode = X86ISD::FHSUB;
11765       break;
11766     case Intrinsic::x86_ssse3_phadd_w_128:
11767     case Intrinsic::x86_ssse3_phadd_d_128:
11768     case Intrinsic::x86_avx2_phadd_w:
11769     case Intrinsic::x86_avx2_phadd_d:
11770       Opcode = X86ISD::HADD;
11771       break;
11772     case Intrinsic::x86_ssse3_phsub_w_128:
11773     case Intrinsic::x86_ssse3_phsub_d_128:
11774     case Intrinsic::x86_avx2_phsub_w:
11775     case Intrinsic::x86_avx2_phsub_d:
11776       Opcode = X86ISD::HSUB;
11777       break;
11778     }
11779     return DAG.getNode(Opcode, dl, Op.getValueType(),
11780                        Op.getOperand(1), Op.getOperand(2));
11781   }
11782
11783   // SSE2/SSE41/AVX2 integer max/min intrinsics.
11784   case Intrinsic::x86_sse2_pmaxu_b:
11785   case Intrinsic::x86_sse41_pmaxuw:
11786   case Intrinsic::x86_sse41_pmaxud:
11787   case Intrinsic::x86_avx2_pmaxu_b:
11788   case Intrinsic::x86_avx2_pmaxu_w:
11789   case Intrinsic::x86_avx2_pmaxu_d:
11790   case Intrinsic::x86_sse2_pminu_b:
11791   case Intrinsic::x86_sse41_pminuw:
11792   case Intrinsic::x86_sse41_pminud:
11793   case Intrinsic::x86_avx2_pminu_b:
11794   case Intrinsic::x86_avx2_pminu_w:
11795   case Intrinsic::x86_avx2_pminu_d:
11796   case Intrinsic::x86_sse41_pmaxsb:
11797   case Intrinsic::x86_sse2_pmaxs_w:
11798   case Intrinsic::x86_sse41_pmaxsd:
11799   case Intrinsic::x86_avx2_pmaxs_b:
11800   case Intrinsic::x86_avx2_pmaxs_w:
11801   case Intrinsic::x86_avx2_pmaxs_d:
11802   case Intrinsic::x86_sse41_pminsb:
11803   case Intrinsic::x86_sse2_pmins_w:
11804   case Intrinsic::x86_sse41_pminsd:
11805   case Intrinsic::x86_avx2_pmins_b:
11806   case Intrinsic::x86_avx2_pmins_w:
11807   case Intrinsic::x86_avx2_pmins_d: {
11808     unsigned Opcode;
11809     switch (IntNo) {
11810     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11811     case Intrinsic::x86_sse2_pmaxu_b:
11812     case Intrinsic::x86_sse41_pmaxuw:
11813     case Intrinsic::x86_sse41_pmaxud:
11814     case Intrinsic::x86_avx2_pmaxu_b:
11815     case Intrinsic::x86_avx2_pmaxu_w:
11816     case Intrinsic::x86_avx2_pmaxu_d:
11817       Opcode = X86ISD::UMAX;
11818       break;
11819     case Intrinsic::x86_sse2_pminu_b:
11820     case Intrinsic::x86_sse41_pminuw:
11821     case Intrinsic::x86_sse41_pminud:
11822     case Intrinsic::x86_avx2_pminu_b:
11823     case Intrinsic::x86_avx2_pminu_w:
11824     case Intrinsic::x86_avx2_pminu_d:
11825       Opcode = X86ISD::UMIN;
11826       break;
11827     case Intrinsic::x86_sse41_pmaxsb:
11828     case Intrinsic::x86_sse2_pmaxs_w:
11829     case Intrinsic::x86_sse41_pmaxsd:
11830     case Intrinsic::x86_avx2_pmaxs_b:
11831     case Intrinsic::x86_avx2_pmaxs_w:
11832     case Intrinsic::x86_avx2_pmaxs_d:
11833       Opcode = X86ISD::SMAX;
11834       break;
11835     case Intrinsic::x86_sse41_pminsb:
11836     case Intrinsic::x86_sse2_pmins_w:
11837     case Intrinsic::x86_sse41_pminsd:
11838     case Intrinsic::x86_avx2_pmins_b:
11839     case Intrinsic::x86_avx2_pmins_w:
11840     case Intrinsic::x86_avx2_pmins_d:
11841       Opcode = X86ISD::SMIN;
11842       break;
11843     }
11844     return DAG.getNode(Opcode, dl, Op.getValueType(),
11845                        Op.getOperand(1), Op.getOperand(2));
11846   }
11847
11848   // SSE/SSE2/AVX floating point max/min intrinsics.
11849   case Intrinsic::x86_sse_max_ps:
11850   case Intrinsic::x86_sse2_max_pd:
11851   case Intrinsic::x86_avx_max_ps_256:
11852   case Intrinsic::x86_avx_max_pd_256:
11853   case Intrinsic::x86_sse_min_ps:
11854   case Intrinsic::x86_sse2_min_pd:
11855   case Intrinsic::x86_avx_min_ps_256:
11856   case Intrinsic::x86_avx_min_pd_256: {
11857     unsigned Opcode;
11858     switch (IntNo) {
11859     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11860     case Intrinsic::x86_sse_max_ps:
11861     case Intrinsic::x86_sse2_max_pd:
11862     case Intrinsic::x86_avx_max_ps_256:
11863     case Intrinsic::x86_avx_max_pd_256:
11864       Opcode = X86ISD::FMAX;
11865       break;
11866     case Intrinsic::x86_sse_min_ps:
11867     case Intrinsic::x86_sse2_min_pd:
11868     case Intrinsic::x86_avx_min_ps_256:
11869     case Intrinsic::x86_avx_min_pd_256:
11870       Opcode = X86ISD::FMIN;
11871       break;
11872     }
11873     return DAG.getNode(Opcode, dl, Op.getValueType(),
11874                        Op.getOperand(1), Op.getOperand(2));
11875   }
11876
11877   // AVX2 variable shift intrinsics
11878   case Intrinsic::x86_avx2_psllv_d:
11879   case Intrinsic::x86_avx2_psllv_q:
11880   case Intrinsic::x86_avx2_psllv_d_256:
11881   case Intrinsic::x86_avx2_psllv_q_256:
11882   case Intrinsic::x86_avx2_psrlv_d:
11883   case Intrinsic::x86_avx2_psrlv_q:
11884   case Intrinsic::x86_avx2_psrlv_d_256:
11885   case Intrinsic::x86_avx2_psrlv_q_256:
11886   case Intrinsic::x86_avx2_psrav_d:
11887   case Intrinsic::x86_avx2_psrav_d_256: {
11888     unsigned Opcode;
11889     switch (IntNo) {
11890     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11891     case Intrinsic::x86_avx2_psllv_d:
11892     case Intrinsic::x86_avx2_psllv_q:
11893     case Intrinsic::x86_avx2_psllv_d_256:
11894     case Intrinsic::x86_avx2_psllv_q_256:
11895       Opcode = ISD::SHL;
11896       break;
11897     case Intrinsic::x86_avx2_psrlv_d:
11898     case Intrinsic::x86_avx2_psrlv_q:
11899     case Intrinsic::x86_avx2_psrlv_d_256:
11900     case Intrinsic::x86_avx2_psrlv_q_256:
11901       Opcode = ISD::SRL;
11902       break;
11903     case Intrinsic::x86_avx2_psrav_d:
11904     case Intrinsic::x86_avx2_psrav_d_256:
11905       Opcode = ISD::SRA;
11906       break;
11907     }
11908     return DAG.getNode(Opcode, dl, Op.getValueType(),
11909                        Op.getOperand(1), Op.getOperand(2));
11910   }
11911
11912   case Intrinsic::x86_ssse3_pshuf_b_128:
11913   case Intrinsic::x86_avx2_pshuf_b:
11914     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
11915                        Op.getOperand(1), Op.getOperand(2));
11916
11917   case Intrinsic::x86_ssse3_psign_b_128:
11918   case Intrinsic::x86_ssse3_psign_w_128:
11919   case Intrinsic::x86_ssse3_psign_d_128:
11920   case Intrinsic::x86_avx2_psign_b:
11921   case Intrinsic::x86_avx2_psign_w:
11922   case Intrinsic::x86_avx2_psign_d:
11923     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
11924                        Op.getOperand(1), Op.getOperand(2));
11925
11926   case Intrinsic::x86_sse41_insertps:
11927     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
11928                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11929
11930   case Intrinsic::x86_avx_vperm2f128_ps_256:
11931   case Intrinsic::x86_avx_vperm2f128_pd_256:
11932   case Intrinsic::x86_avx_vperm2f128_si_256:
11933   case Intrinsic::x86_avx2_vperm2i128:
11934     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
11935                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
11936
11937   case Intrinsic::x86_avx2_permd:
11938   case Intrinsic::x86_avx2_permps:
11939     // Operands intentionally swapped. Mask is last operand to intrinsic,
11940     // but second operand for node/instruction.
11941     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
11942                        Op.getOperand(2), Op.getOperand(1));
11943
11944   case Intrinsic::x86_sse_sqrt_ps:
11945   case Intrinsic::x86_sse2_sqrt_pd:
11946   case Intrinsic::x86_avx_sqrt_ps_256:
11947   case Intrinsic::x86_avx_sqrt_pd_256:
11948     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
11949
11950   // ptest and testp intrinsics. The intrinsic these come from are designed to
11951   // return an integer value, not just an instruction so lower it to the ptest
11952   // or testp pattern and a setcc for the result.
11953   case Intrinsic::x86_sse41_ptestz:
11954   case Intrinsic::x86_sse41_ptestc:
11955   case Intrinsic::x86_sse41_ptestnzc:
11956   case Intrinsic::x86_avx_ptestz_256:
11957   case Intrinsic::x86_avx_ptestc_256:
11958   case Intrinsic::x86_avx_ptestnzc_256:
11959   case Intrinsic::x86_avx_vtestz_ps:
11960   case Intrinsic::x86_avx_vtestc_ps:
11961   case Intrinsic::x86_avx_vtestnzc_ps:
11962   case Intrinsic::x86_avx_vtestz_pd:
11963   case Intrinsic::x86_avx_vtestc_pd:
11964   case Intrinsic::x86_avx_vtestnzc_pd:
11965   case Intrinsic::x86_avx_vtestz_ps_256:
11966   case Intrinsic::x86_avx_vtestc_ps_256:
11967   case Intrinsic::x86_avx_vtestnzc_ps_256:
11968   case Intrinsic::x86_avx_vtestz_pd_256:
11969   case Intrinsic::x86_avx_vtestc_pd_256:
11970   case Intrinsic::x86_avx_vtestnzc_pd_256: {
11971     bool IsTestPacked = false;
11972     unsigned X86CC;
11973     switch (IntNo) {
11974     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
11975     case Intrinsic::x86_avx_vtestz_ps:
11976     case Intrinsic::x86_avx_vtestz_pd:
11977     case Intrinsic::x86_avx_vtestz_ps_256:
11978     case Intrinsic::x86_avx_vtestz_pd_256:
11979       IsTestPacked = true; // Fallthrough
11980     case Intrinsic::x86_sse41_ptestz:
11981     case Intrinsic::x86_avx_ptestz_256:
11982       // ZF = 1
11983       X86CC = X86::COND_E;
11984       break;
11985     case Intrinsic::x86_avx_vtestc_ps:
11986     case Intrinsic::x86_avx_vtestc_pd:
11987     case Intrinsic::x86_avx_vtestc_ps_256:
11988     case Intrinsic::x86_avx_vtestc_pd_256:
11989       IsTestPacked = true; // Fallthrough
11990     case Intrinsic::x86_sse41_ptestc:
11991     case Intrinsic::x86_avx_ptestc_256:
11992       // CF = 1
11993       X86CC = X86::COND_B;
11994       break;
11995     case Intrinsic::x86_avx_vtestnzc_ps:
11996     case Intrinsic::x86_avx_vtestnzc_pd:
11997     case Intrinsic::x86_avx_vtestnzc_ps_256:
11998     case Intrinsic::x86_avx_vtestnzc_pd_256:
11999       IsTestPacked = true; // Fallthrough
12000     case Intrinsic::x86_sse41_ptestnzc:
12001     case Intrinsic::x86_avx_ptestnzc_256:
12002       // ZF and CF = 0
12003       X86CC = X86::COND_A;
12004       break;
12005     }
12006
12007     SDValue LHS = Op.getOperand(1);
12008     SDValue RHS = Op.getOperand(2);
12009     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12010     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12011     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12012     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12013     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12014   }
12015   case Intrinsic::x86_avx512_kortestz_w:
12016   case Intrinsic::x86_avx512_kortestc_w: {
12017     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12018     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12019     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12020     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12021     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12022     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12023     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12024   }
12025
12026   // SSE/AVX shift intrinsics
12027   case Intrinsic::x86_sse2_psll_w:
12028   case Intrinsic::x86_sse2_psll_d:
12029   case Intrinsic::x86_sse2_psll_q:
12030   case Intrinsic::x86_avx2_psll_w:
12031   case Intrinsic::x86_avx2_psll_d:
12032   case Intrinsic::x86_avx2_psll_q:
12033   case Intrinsic::x86_sse2_psrl_w:
12034   case Intrinsic::x86_sse2_psrl_d:
12035   case Intrinsic::x86_sse2_psrl_q:
12036   case Intrinsic::x86_avx2_psrl_w:
12037   case Intrinsic::x86_avx2_psrl_d:
12038   case Intrinsic::x86_avx2_psrl_q:
12039   case Intrinsic::x86_sse2_psra_w:
12040   case Intrinsic::x86_sse2_psra_d:
12041   case Intrinsic::x86_avx2_psra_w:
12042   case Intrinsic::x86_avx2_psra_d: {
12043     unsigned Opcode;
12044     switch (IntNo) {
12045     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12046     case Intrinsic::x86_sse2_psll_w:
12047     case Intrinsic::x86_sse2_psll_d:
12048     case Intrinsic::x86_sse2_psll_q:
12049     case Intrinsic::x86_avx2_psll_w:
12050     case Intrinsic::x86_avx2_psll_d:
12051     case Intrinsic::x86_avx2_psll_q:
12052       Opcode = X86ISD::VSHL;
12053       break;
12054     case Intrinsic::x86_sse2_psrl_w:
12055     case Intrinsic::x86_sse2_psrl_d:
12056     case Intrinsic::x86_sse2_psrl_q:
12057     case Intrinsic::x86_avx2_psrl_w:
12058     case Intrinsic::x86_avx2_psrl_d:
12059     case Intrinsic::x86_avx2_psrl_q:
12060       Opcode = X86ISD::VSRL;
12061       break;
12062     case Intrinsic::x86_sse2_psra_w:
12063     case Intrinsic::x86_sse2_psra_d:
12064     case Intrinsic::x86_avx2_psra_w:
12065     case Intrinsic::x86_avx2_psra_d:
12066       Opcode = X86ISD::VSRA;
12067       break;
12068     }
12069     return DAG.getNode(Opcode, dl, Op.getValueType(),
12070                        Op.getOperand(1), Op.getOperand(2));
12071   }
12072
12073   // SSE/AVX immediate shift intrinsics
12074   case Intrinsic::x86_sse2_pslli_w:
12075   case Intrinsic::x86_sse2_pslli_d:
12076   case Intrinsic::x86_sse2_pslli_q:
12077   case Intrinsic::x86_avx2_pslli_w:
12078   case Intrinsic::x86_avx2_pslli_d:
12079   case Intrinsic::x86_avx2_pslli_q:
12080   case Intrinsic::x86_sse2_psrli_w:
12081   case Intrinsic::x86_sse2_psrli_d:
12082   case Intrinsic::x86_sse2_psrli_q:
12083   case Intrinsic::x86_avx2_psrli_w:
12084   case Intrinsic::x86_avx2_psrli_d:
12085   case Intrinsic::x86_avx2_psrli_q:
12086   case Intrinsic::x86_sse2_psrai_w:
12087   case Intrinsic::x86_sse2_psrai_d:
12088   case Intrinsic::x86_avx2_psrai_w:
12089   case Intrinsic::x86_avx2_psrai_d: {
12090     unsigned Opcode;
12091     switch (IntNo) {
12092     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12093     case Intrinsic::x86_sse2_pslli_w:
12094     case Intrinsic::x86_sse2_pslli_d:
12095     case Intrinsic::x86_sse2_pslli_q:
12096     case Intrinsic::x86_avx2_pslli_w:
12097     case Intrinsic::x86_avx2_pslli_d:
12098     case Intrinsic::x86_avx2_pslli_q:
12099       Opcode = X86ISD::VSHLI;
12100       break;
12101     case Intrinsic::x86_sse2_psrli_w:
12102     case Intrinsic::x86_sse2_psrli_d:
12103     case Intrinsic::x86_sse2_psrli_q:
12104     case Intrinsic::x86_avx2_psrli_w:
12105     case Intrinsic::x86_avx2_psrli_d:
12106     case Intrinsic::x86_avx2_psrli_q:
12107       Opcode = X86ISD::VSRLI;
12108       break;
12109     case Intrinsic::x86_sse2_psrai_w:
12110     case Intrinsic::x86_sse2_psrai_d:
12111     case Intrinsic::x86_avx2_psrai_w:
12112     case Intrinsic::x86_avx2_psrai_d:
12113       Opcode = X86ISD::VSRAI;
12114       break;
12115     }
12116     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12117                                Op.getOperand(1), Op.getOperand(2), DAG);
12118   }
12119
12120   case Intrinsic::x86_sse42_pcmpistria128:
12121   case Intrinsic::x86_sse42_pcmpestria128:
12122   case Intrinsic::x86_sse42_pcmpistric128:
12123   case Intrinsic::x86_sse42_pcmpestric128:
12124   case Intrinsic::x86_sse42_pcmpistrio128:
12125   case Intrinsic::x86_sse42_pcmpestrio128:
12126   case Intrinsic::x86_sse42_pcmpistris128:
12127   case Intrinsic::x86_sse42_pcmpestris128:
12128   case Intrinsic::x86_sse42_pcmpistriz128:
12129   case Intrinsic::x86_sse42_pcmpestriz128: {
12130     unsigned Opcode;
12131     unsigned X86CC;
12132     switch (IntNo) {
12133     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12134     case Intrinsic::x86_sse42_pcmpistria128:
12135       Opcode = X86ISD::PCMPISTRI;
12136       X86CC = X86::COND_A;
12137       break;
12138     case Intrinsic::x86_sse42_pcmpestria128:
12139       Opcode = X86ISD::PCMPESTRI;
12140       X86CC = X86::COND_A;
12141       break;
12142     case Intrinsic::x86_sse42_pcmpistric128:
12143       Opcode = X86ISD::PCMPISTRI;
12144       X86CC = X86::COND_B;
12145       break;
12146     case Intrinsic::x86_sse42_pcmpestric128:
12147       Opcode = X86ISD::PCMPESTRI;
12148       X86CC = X86::COND_B;
12149       break;
12150     case Intrinsic::x86_sse42_pcmpistrio128:
12151       Opcode = X86ISD::PCMPISTRI;
12152       X86CC = X86::COND_O;
12153       break;
12154     case Intrinsic::x86_sse42_pcmpestrio128:
12155       Opcode = X86ISD::PCMPESTRI;
12156       X86CC = X86::COND_O;
12157       break;
12158     case Intrinsic::x86_sse42_pcmpistris128:
12159       Opcode = X86ISD::PCMPISTRI;
12160       X86CC = X86::COND_S;
12161       break;
12162     case Intrinsic::x86_sse42_pcmpestris128:
12163       Opcode = X86ISD::PCMPESTRI;
12164       X86CC = X86::COND_S;
12165       break;
12166     case Intrinsic::x86_sse42_pcmpistriz128:
12167       Opcode = X86ISD::PCMPISTRI;
12168       X86CC = X86::COND_E;
12169       break;
12170     case Intrinsic::x86_sse42_pcmpestriz128:
12171       Opcode = X86ISD::PCMPESTRI;
12172       X86CC = X86::COND_E;
12173       break;
12174     }
12175     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12176     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12177     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12178     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12179                                 DAG.getConstant(X86CC, MVT::i8),
12180                                 SDValue(PCMP.getNode(), 1));
12181     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12182   }
12183
12184   case Intrinsic::x86_sse42_pcmpistri128:
12185   case Intrinsic::x86_sse42_pcmpestri128: {
12186     unsigned Opcode;
12187     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12188       Opcode = X86ISD::PCMPISTRI;
12189     else
12190       Opcode = X86ISD::PCMPESTRI;
12191
12192     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12193     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12194     return DAG.getNode(Opcode, dl, VTs, NewOps);
12195   }
12196   case Intrinsic::x86_fma_vfmadd_ps:
12197   case Intrinsic::x86_fma_vfmadd_pd:
12198   case Intrinsic::x86_fma_vfmsub_ps:
12199   case Intrinsic::x86_fma_vfmsub_pd:
12200   case Intrinsic::x86_fma_vfnmadd_ps:
12201   case Intrinsic::x86_fma_vfnmadd_pd:
12202   case Intrinsic::x86_fma_vfnmsub_ps:
12203   case Intrinsic::x86_fma_vfnmsub_pd:
12204   case Intrinsic::x86_fma_vfmaddsub_ps:
12205   case Intrinsic::x86_fma_vfmaddsub_pd:
12206   case Intrinsic::x86_fma_vfmsubadd_ps:
12207   case Intrinsic::x86_fma_vfmsubadd_pd:
12208   case Intrinsic::x86_fma_vfmadd_ps_256:
12209   case Intrinsic::x86_fma_vfmadd_pd_256:
12210   case Intrinsic::x86_fma_vfmsub_ps_256:
12211   case Intrinsic::x86_fma_vfmsub_pd_256:
12212   case Intrinsic::x86_fma_vfnmadd_ps_256:
12213   case Intrinsic::x86_fma_vfnmadd_pd_256:
12214   case Intrinsic::x86_fma_vfnmsub_ps_256:
12215   case Intrinsic::x86_fma_vfnmsub_pd_256:
12216   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12217   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12218   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12219   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12220   case Intrinsic::x86_fma_vfmadd_ps_512:
12221   case Intrinsic::x86_fma_vfmadd_pd_512:
12222   case Intrinsic::x86_fma_vfmsub_ps_512:
12223   case Intrinsic::x86_fma_vfmsub_pd_512:
12224   case Intrinsic::x86_fma_vfnmadd_ps_512:
12225   case Intrinsic::x86_fma_vfnmadd_pd_512:
12226   case Intrinsic::x86_fma_vfnmsub_ps_512:
12227   case Intrinsic::x86_fma_vfnmsub_pd_512:
12228   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12229   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12230   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12231   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12232     unsigned Opc;
12233     switch (IntNo) {
12234     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12235     case Intrinsic::x86_fma_vfmadd_ps:
12236     case Intrinsic::x86_fma_vfmadd_pd:
12237     case Intrinsic::x86_fma_vfmadd_ps_256:
12238     case Intrinsic::x86_fma_vfmadd_pd_256:
12239     case Intrinsic::x86_fma_vfmadd_ps_512:
12240     case Intrinsic::x86_fma_vfmadd_pd_512:
12241       Opc = X86ISD::FMADD;
12242       break;
12243     case Intrinsic::x86_fma_vfmsub_ps:
12244     case Intrinsic::x86_fma_vfmsub_pd:
12245     case Intrinsic::x86_fma_vfmsub_ps_256:
12246     case Intrinsic::x86_fma_vfmsub_pd_256:
12247     case Intrinsic::x86_fma_vfmsub_ps_512:
12248     case Intrinsic::x86_fma_vfmsub_pd_512:
12249       Opc = X86ISD::FMSUB;
12250       break;
12251     case Intrinsic::x86_fma_vfnmadd_ps:
12252     case Intrinsic::x86_fma_vfnmadd_pd:
12253     case Intrinsic::x86_fma_vfnmadd_ps_256:
12254     case Intrinsic::x86_fma_vfnmadd_pd_256:
12255     case Intrinsic::x86_fma_vfnmadd_ps_512:
12256     case Intrinsic::x86_fma_vfnmadd_pd_512:
12257       Opc = X86ISD::FNMADD;
12258       break;
12259     case Intrinsic::x86_fma_vfnmsub_ps:
12260     case Intrinsic::x86_fma_vfnmsub_pd:
12261     case Intrinsic::x86_fma_vfnmsub_ps_256:
12262     case Intrinsic::x86_fma_vfnmsub_pd_256:
12263     case Intrinsic::x86_fma_vfnmsub_ps_512:
12264     case Intrinsic::x86_fma_vfnmsub_pd_512:
12265       Opc = X86ISD::FNMSUB;
12266       break;
12267     case Intrinsic::x86_fma_vfmaddsub_ps:
12268     case Intrinsic::x86_fma_vfmaddsub_pd:
12269     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12270     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12271     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12272     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12273       Opc = X86ISD::FMADDSUB;
12274       break;
12275     case Intrinsic::x86_fma_vfmsubadd_ps:
12276     case Intrinsic::x86_fma_vfmsubadd_pd:
12277     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12278     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12279     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12280     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12281       Opc = X86ISD::FMSUBADD;
12282       break;
12283     }
12284
12285     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12286                        Op.getOperand(2), Op.getOperand(3));
12287   }
12288   }
12289 }
12290
12291 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12292                              SDValue Base, SDValue Index,
12293                              SDValue ScaleOp, SDValue Chain,
12294                              const X86Subtarget * Subtarget) {
12295   SDLoc dl(Op);
12296   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12297   assert(C && "Invalid scale type");
12298   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12299   SDValue Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12300   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12301                              Index.getSimpleValueType().getVectorNumElements());
12302   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12303   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12304   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12305   SDValue Segment = DAG.getRegister(0, MVT::i32);
12306   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12307   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12308   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12309   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12310 }
12311
12312 static SDValue getMGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12313                               SDValue Src, SDValue Mask, SDValue Base,
12314                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12315                               const X86Subtarget * Subtarget) {
12316   SDLoc dl(Op);
12317   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12318   assert(C && "Invalid scale type");
12319   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12320   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12321                              Index.getSimpleValueType().getVectorNumElements());
12322   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12323   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12324   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12325   SDValue Segment = DAG.getRegister(0, MVT::i32);
12326   if (Src.getOpcode() == ISD::UNDEF)
12327     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12328   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12329   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12330   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12331   return DAG.getMergeValues(RetOps, array_lengthof(RetOps), dl);
12332 }
12333
12334 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12335                               SDValue Src, SDValue Base, SDValue Index,
12336                               SDValue ScaleOp, SDValue Chain) {
12337   SDLoc dl(Op);
12338   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12339   assert(C && "Invalid scale type");
12340   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12341   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12342   SDValue Segment = DAG.getRegister(0, MVT::i32);
12343   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12344                              Index.getSimpleValueType().getVectorNumElements());
12345   SDValue MaskInReg = DAG.getConstant(~0, MaskVT);
12346   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12347   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12348   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12349   return SDValue(Res, 1);
12350 }
12351
12352 static SDValue getMScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12353                                SDValue Src, SDValue Mask, SDValue Base,
12354                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12355   SDLoc dl(Op);
12356   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12357   assert(C && "Invalid scale type");
12358   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12359   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12360   SDValue Segment = DAG.getRegister(0, MVT::i32);
12361   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12362                              Index.getSimpleValueType().getVectorNumElements());
12363   SDValue MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12364   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12365   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12366   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12367   return SDValue(Res, 1);
12368 }
12369
12370 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12371 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12372 // also used to custom lower READCYCLECOUNTER nodes.
12373 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12374                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12375                               SmallVectorImpl<SDValue> &Results) {
12376   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12377   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12378   SDValue LO, HI;
12379
12380   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12381   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12382   // and the EAX register is loaded with the low-order 32 bits.
12383   if (Subtarget->is64Bit()) {
12384     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12385     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12386                             LO.getValue(2));
12387   } else {
12388     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12389     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12390                             LO.getValue(2));
12391   }
12392   SDValue Chain = HI.getValue(1);
12393
12394   if (Opcode == X86ISD::RDTSCP_DAG) {
12395     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12396
12397     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12398     // the ECX register. Add 'ecx' explicitly to the chain.
12399     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12400                                      HI.getValue(2));
12401     // Explicitly store the content of ECX at the location passed in input
12402     // to the 'rdtscp' intrinsic.
12403     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12404                          MachinePointerInfo(), false, false, 0);
12405   }
12406
12407   if (Subtarget->is64Bit()) {
12408     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12409     // the EAX register is loaded with the low-order 32 bits.
12410     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12411                               DAG.getConstant(32, MVT::i8));
12412     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12413     Results.push_back(Chain);
12414     return;
12415   }
12416
12417   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12418   SDValue Ops[] = { LO, HI };
12419   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12420   Results.push_back(Pair);
12421   Results.push_back(Chain);
12422 }
12423
12424 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12425                                      SelectionDAG &DAG) {
12426   SmallVector<SDValue, 2> Results;
12427   SDLoc DL(Op);
12428   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12429                           Results);
12430   return DAG.getMergeValues(&Results[0], Results.size(), DL);
12431 }
12432
12433 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12434                                       SelectionDAG &DAG) {
12435   SDLoc dl(Op);
12436   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12437   switch (IntNo) {
12438   default: return SDValue();    // Don't custom lower most intrinsics.
12439
12440   // RDRAND/RDSEED intrinsics.
12441   case Intrinsic::x86_rdrand_16:
12442   case Intrinsic::x86_rdrand_32:
12443   case Intrinsic::x86_rdrand_64:
12444   case Intrinsic::x86_rdseed_16:
12445   case Intrinsic::x86_rdseed_32:
12446   case Intrinsic::x86_rdseed_64: {
12447     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
12448                        IntNo == Intrinsic::x86_rdseed_32 ||
12449                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
12450                                                             X86ISD::RDRAND;
12451     // Emit the node with the right value type.
12452     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12453     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
12454
12455     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12456     // Otherwise return the value from Rand, which is always 0, casted to i32.
12457     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12458                       DAG.getConstant(1, Op->getValueType(1)),
12459                       DAG.getConstant(X86::COND_B, MVT::i32),
12460                       SDValue(Result.getNode(), 1) };
12461     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12462                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12463                                   Ops);
12464
12465     // Return { result, isValid, chain }.
12466     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12467                        SDValue(Result.getNode(), 2));
12468   }
12469   //int_gather(index, base, scale);
12470   case Intrinsic::x86_avx512_gather_qpd_512:
12471   case Intrinsic::x86_avx512_gather_qps_512:
12472   case Intrinsic::x86_avx512_gather_dpd_512:
12473   case Intrinsic::x86_avx512_gather_qpi_512:
12474   case Intrinsic::x86_avx512_gather_qpq_512:
12475   case Intrinsic::x86_avx512_gather_dpq_512:
12476   case Intrinsic::x86_avx512_gather_dps_512:
12477   case Intrinsic::x86_avx512_gather_dpi_512: {
12478     unsigned Opc;
12479     switch (IntNo) {
12480     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12481     case Intrinsic::x86_avx512_gather_qps_512: Opc = X86::VGATHERQPSZrm; break;
12482     case Intrinsic::x86_avx512_gather_qpd_512: Opc = X86::VGATHERQPDZrm; break;
12483     case Intrinsic::x86_avx512_gather_dpd_512: Opc = X86::VGATHERDPDZrm; break;
12484     case Intrinsic::x86_avx512_gather_dps_512: Opc = X86::VGATHERDPSZrm; break;
12485     case Intrinsic::x86_avx512_gather_qpi_512: Opc = X86::VPGATHERQDZrm; break;
12486     case Intrinsic::x86_avx512_gather_qpq_512: Opc = X86::VPGATHERQQZrm; break;
12487     case Intrinsic::x86_avx512_gather_dpi_512: Opc = X86::VPGATHERDDZrm; break;
12488     case Intrinsic::x86_avx512_gather_dpq_512: Opc = X86::VPGATHERDQZrm; break;
12489     }
12490     SDValue Chain = Op.getOperand(0);
12491     SDValue Index = Op.getOperand(2);
12492     SDValue Base  = Op.getOperand(3);
12493     SDValue Scale = Op.getOperand(4);
12494     return getGatherNode(Opc, Op, DAG, Base, Index, Scale, Chain, Subtarget);
12495   }
12496   //int_gather_mask(v1, mask, index, base, scale);
12497   case Intrinsic::x86_avx512_gather_qps_mask_512:
12498   case Intrinsic::x86_avx512_gather_qpd_mask_512:
12499   case Intrinsic::x86_avx512_gather_dpd_mask_512:
12500   case Intrinsic::x86_avx512_gather_dps_mask_512:
12501   case Intrinsic::x86_avx512_gather_qpi_mask_512:
12502   case Intrinsic::x86_avx512_gather_qpq_mask_512:
12503   case Intrinsic::x86_avx512_gather_dpi_mask_512:
12504   case Intrinsic::x86_avx512_gather_dpq_mask_512: {
12505     unsigned Opc;
12506     switch (IntNo) {
12507     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12508     case Intrinsic::x86_avx512_gather_qps_mask_512:
12509       Opc = X86::VGATHERQPSZrm; break;
12510     case Intrinsic::x86_avx512_gather_qpd_mask_512:
12511       Opc = X86::VGATHERQPDZrm; break;
12512     case Intrinsic::x86_avx512_gather_dpd_mask_512:
12513       Opc = X86::VGATHERDPDZrm; break;
12514     case Intrinsic::x86_avx512_gather_dps_mask_512:
12515       Opc = X86::VGATHERDPSZrm; break;
12516     case Intrinsic::x86_avx512_gather_qpi_mask_512:
12517       Opc = X86::VPGATHERQDZrm; break;
12518     case Intrinsic::x86_avx512_gather_qpq_mask_512:
12519       Opc = X86::VPGATHERQQZrm; break;
12520     case Intrinsic::x86_avx512_gather_dpi_mask_512:
12521       Opc = X86::VPGATHERDDZrm; break;
12522     case Intrinsic::x86_avx512_gather_dpq_mask_512:
12523       Opc = X86::VPGATHERDQZrm; break;
12524     }
12525     SDValue Chain = Op.getOperand(0);
12526     SDValue Src   = Op.getOperand(2);
12527     SDValue Mask  = Op.getOperand(3);
12528     SDValue Index = Op.getOperand(4);
12529     SDValue Base  = Op.getOperand(5);
12530     SDValue Scale = Op.getOperand(6);
12531     return getMGatherNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12532                           Subtarget);
12533   }
12534   //int_scatter(base, index, v1, scale);
12535   case Intrinsic::x86_avx512_scatter_qpd_512:
12536   case Intrinsic::x86_avx512_scatter_qps_512:
12537   case Intrinsic::x86_avx512_scatter_dpd_512:
12538   case Intrinsic::x86_avx512_scatter_qpi_512:
12539   case Intrinsic::x86_avx512_scatter_qpq_512:
12540   case Intrinsic::x86_avx512_scatter_dpq_512:
12541   case Intrinsic::x86_avx512_scatter_dps_512:
12542   case Intrinsic::x86_avx512_scatter_dpi_512: {
12543     unsigned Opc;
12544     switch (IntNo) {
12545     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12546     case Intrinsic::x86_avx512_scatter_qpd_512:
12547       Opc = X86::VSCATTERQPDZmr; break;
12548     case Intrinsic::x86_avx512_scatter_qps_512:
12549       Opc = X86::VSCATTERQPSZmr; break;
12550     case Intrinsic::x86_avx512_scatter_dpd_512:
12551       Opc = X86::VSCATTERDPDZmr; break;
12552     case Intrinsic::x86_avx512_scatter_dps_512:
12553       Opc = X86::VSCATTERDPSZmr; break;
12554     case Intrinsic::x86_avx512_scatter_qpi_512:
12555       Opc = X86::VPSCATTERQDZmr; break;
12556     case Intrinsic::x86_avx512_scatter_qpq_512:
12557       Opc = X86::VPSCATTERQQZmr; break;
12558     case Intrinsic::x86_avx512_scatter_dpq_512:
12559       Opc = X86::VPSCATTERDQZmr; break;
12560     case Intrinsic::x86_avx512_scatter_dpi_512:
12561       Opc = X86::VPSCATTERDDZmr; break;
12562     }
12563     SDValue Chain = Op.getOperand(0);
12564     SDValue Base  = Op.getOperand(2);
12565     SDValue Index = Op.getOperand(3);
12566     SDValue Src   = Op.getOperand(4);
12567     SDValue Scale = Op.getOperand(5);
12568     return getScatterNode(Opc, Op, DAG, Src, Base, Index, Scale, Chain);
12569   }
12570   //int_scatter_mask(base, mask, index, v1, scale);
12571   case Intrinsic::x86_avx512_scatter_qps_mask_512:
12572   case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12573   case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12574   case Intrinsic::x86_avx512_scatter_dps_mask_512:
12575   case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12576   case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12577   case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12578   case Intrinsic::x86_avx512_scatter_dpq_mask_512: {
12579     unsigned Opc;
12580     switch (IntNo) {
12581     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12582     case Intrinsic::x86_avx512_scatter_qpd_mask_512:
12583       Opc = X86::VSCATTERQPDZmr; break;
12584     case Intrinsic::x86_avx512_scatter_qps_mask_512:
12585       Opc = X86::VSCATTERQPSZmr; break;
12586     case Intrinsic::x86_avx512_scatter_dpd_mask_512:
12587       Opc = X86::VSCATTERDPDZmr; break;
12588     case Intrinsic::x86_avx512_scatter_dps_mask_512:
12589       Opc = X86::VSCATTERDPSZmr; break;
12590     case Intrinsic::x86_avx512_scatter_qpi_mask_512:
12591       Opc = X86::VPSCATTERQDZmr; break;
12592     case Intrinsic::x86_avx512_scatter_qpq_mask_512:
12593       Opc = X86::VPSCATTERQQZmr; break;
12594     case Intrinsic::x86_avx512_scatter_dpq_mask_512:
12595       Opc = X86::VPSCATTERDQZmr; break;
12596     case Intrinsic::x86_avx512_scatter_dpi_mask_512:
12597       Opc = X86::VPSCATTERDDZmr; break;
12598     }
12599     SDValue Chain = Op.getOperand(0);
12600     SDValue Base  = Op.getOperand(2);
12601     SDValue Mask  = Op.getOperand(3);
12602     SDValue Index = Op.getOperand(4);
12603     SDValue Src   = Op.getOperand(5);
12604     SDValue Scale = Op.getOperand(6);
12605     return getMScatterNode(Opc, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12606   }
12607   // Read Time Stamp Counter (RDTSC).
12608   case Intrinsic::x86_rdtsc:
12609   // Read Time Stamp Counter and Processor ID (RDTSCP).
12610   case Intrinsic::x86_rdtscp: {
12611     unsigned Opc;
12612     switch (IntNo) {
12613     default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12614     case Intrinsic::x86_rdtsc:
12615       Opc = X86ISD::RDTSC_DAG; break;
12616     case Intrinsic::x86_rdtscp:
12617       Opc = X86ISD::RDTSCP_DAG; break;
12618     }
12619     SmallVector<SDValue, 2> Results;
12620     getReadTimeStampCounter(Op.getNode(), dl, Opc, DAG, Subtarget, Results);
12621     return DAG.getMergeValues(&Results[0], Results.size(), dl);
12622   }
12623   // XTEST intrinsics.
12624   case Intrinsic::x86_xtest: {
12625     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12626     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12627     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12628                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12629                                 InTrans);
12630     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12631     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12632                        Ret, SDValue(InTrans.getNode(), 1));
12633   }
12634   }
12635 }
12636
12637 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12638                                            SelectionDAG &DAG) const {
12639   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12640   MFI->setReturnAddressIsTaken(true);
12641
12642   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12643     return SDValue();
12644
12645   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12646   SDLoc dl(Op);
12647   EVT PtrVT = getPointerTy();
12648
12649   if (Depth > 0) {
12650     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12651     const X86RegisterInfo *RegInfo =
12652       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12653     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12654     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12655                        DAG.getNode(ISD::ADD, dl, PtrVT,
12656                                    FrameAddr, Offset),
12657                        MachinePointerInfo(), false, false, false, 0);
12658   }
12659
12660   // Just load the return address.
12661   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12662   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12663                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12664 }
12665
12666 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12667   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12668   MFI->setFrameAddressIsTaken(true);
12669
12670   EVT VT = Op.getValueType();
12671   SDLoc dl(Op);  // FIXME probably not meaningful
12672   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12673   const X86RegisterInfo *RegInfo =
12674     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12675   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12676   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12677           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12678          "Invalid Frame Register!");
12679   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12680   while (Depth--)
12681     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12682                             MachinePointerInfo(),
12683                             false, false, false, 0);
12684   return FrameAddr;
12685 }
12686
12687 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12688                                                      SelectionDAG &DAG) const {
12689   const X86RegisterInfo *RegInfo =
12690     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12691   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12692 }
12693
12694 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12695   SDValue Chain     = Op.getOperand(0);
12696   SDValue Offset    = Op.getOperand(1);
12697   SDValue Handler   = Op.getOperand(2);
12698   SDLoc dl      (Op);
12699
12700   EVT PtrVT = getPointerTy();
12701   const X86RegisterInfo *RegInfo =
12702     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12703   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12704   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12705           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12706          "Invalid Frame Register!");
12707   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12708   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12709
12710   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12711                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12712   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12713   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12714                        false, false, 0);
12715   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12716
12717   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12718                      DAG.getRegister(StoreAddrReg, PtrVT));
12719 }
12720
12721 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12722                                                SelectionDAG &DAG) const {
12723   SDLoc DL(Op);
12724   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12725                      DAG.getVTList(MVT::i32, MVT::Other),
12726                      Op.getOperand(0), Op.getOperand(1));
12727 }
12728
12729 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12730                                                 SelectionDAG &DAG) const {
12731   SDLoc DL(Op);
12732   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12733                      Op.getOperand(0), Op.getOperand(1));
12734 }
12735
12736 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12737   return Op.getOperand(0);
12738 }
12739
12740 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12741                                                 SelectionDAG &DAG) const {
12742   SDValue Root = Op.getOperand(0);
12743   SDValue Trmp = Op.getOperand(1); // trampoline
12744   SDValue FPtr = Op.getOperand(2); // nested function
12745   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12746   SDLoc dl (Op);
12747
12748   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12749   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12750
12751   if (Subtarget->is64Bit()) {
12752     SDValue OutChains[6];
12753
12754     // Large code-model.
12755     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
12756     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
12757
12758     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
12759     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
12760
12761     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
12762
12763     // Load the pointer to the nested function into R11.
12764     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
12765     SDValue Addr = Trmp;
12766     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12767                                 Addr, MachinePointerInfo(TrmpAddr),
12768                                 false, false, 0);
12769
12770     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12771                        DAG.getConstant(2, MVT::i64));
12772     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
12773                                 MachinePointerInfo(TrmpAddr, 2),
12774                                 false, false, 2);
12775
12776     // Load the 'nest' parameter value into R10.
12777     // R10 is specified in X86CallingConv.td
12778     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
12779     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12780                        DAG.getConstant(10, MVT::i64));
12781     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12782                                 Addr, MachinePointerInfo(TrmpAddr, 10),
12783                                 false, false, 0);
12784
12785     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12786                        DAG.getConstant(12, MVT::i64));
12787     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
12788                                 MachinePointerInfo(TrmpAddr, 12),
12789                                 false, false, 2);
12790
12791     // Jump to the nested function.
12792     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
12793     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12794                        DAG.getConstant(20, MVT::i64));
12795     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
12796                                 Addr, MachinePointerInfo(TrmpAddr, 20),
12797                                 false, false, 0);
12798
12799     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
12800     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
12801                        DAG.getConstant(22, MVT::i64));
12802     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
12803                                 MachinePointerInfo(TrmpAddr, 22),
12804                                 false, false, 0);
12805
12806     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12807   } else {
12808     const Function *Func =
12809       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
12810     CallingConv::ID CC = Func->getCallingConv();
12811     unsigned NestReg;
12812
12813     switch (CC) {
12814     default:
12815       llvm_unreachable("Unsupported calling convention");
12816     case CallingConv::C:
12817     case CallingConv::X86_StdCall: {
12818       // Pass 'nest' parameter in ECX.
12819       // Must be kept in sync with X86CallingConv.td
12820       NestReg = X86::ECX;
12821
12822       // Check that ECX wasn't needed by an 'inreg' parameter.
12823       FunctionType *FTy = Func->getFunctionType();
12824       const AttributeSet &Attrs = Func->getAttributes();
12825
12826       if (!Attrs.isEmpty() && !Func->isVarArg()) {
12827         unsigned InRegCount = 0;
12828         unsigned Idx = 1;
12829
12830         for (FunctionType::param_iterator I = FTy->param_begin(),
12831              E = FTy->param_end(); I != E; ++I, ++Idx)
12832           if (Attrs.hasAttribute(Idx, Attribute::InReg))
12833             // FIXME: should only count parameters that are lowered to integers.
12834             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
12835
12836         if (InRegCount > 2) {
12837           report_fatal_error("Nest register in use - reduce number of inreg"
12838                              " parameters!");
12839         }
12840       }
12841       break;
12842     }
12843     case CallingConv::X86_FastCall:
12844     case CallingConv::X86_ThisCall:
12845     case CallingConv::Fast:
12846       // Pass 'nest' parameter in EAX.
12847       // Must be kept in sync with X86CallingConv.td
12848       NestReg = X86::EAX;
12849       break;
12850     }
12851
12852     SDValue OutChains[4];
12853     SDValue Addr, Disp;
12854
12855     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12856                        DAG.getConstant(10, MVT::i32));
12857     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
12858
12859     // This is storing the opcode for MOV32ri.
12860     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
12861     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
12862     OutChains[0] = DAG.getStore(Root, dl,
12863                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
12864                                 Trmp, MachinePointerInfo(TrmpAddr),
12865                                 false, false, 0);
12866
12867     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12868                        DAG.getConstant(1, MVT::i32));
12869     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
12870                                 MachinePointerInfo(TrmpAddr, 1),
12871                                 false, false, 1);
12872
12873     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
12874     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12875                        DAG.getConstant(5, MVT::i32));
12876     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
12877                                 MachinePointerInfo(TrmpAddr, 5),
12878                                 false, false, 1);
12879
12880     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
12881                        DAG.getConstant(6, MVT::i32));
12882     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
12883                                 MachinePointerInfo(TrmpAddr, 6),
12884                                 false, false, 1);
12885
12886     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
12887   }
12888 }
12889
12890 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
12891                                             SelectionDAG &DAG) const {
12892   /*
12893    The rounding mode is in bits 11:10 of FPSR, and has the following
12894    settings:
12895      00 Round to nearest
12896      01 Round to -inf
12897      10 Round to +inf
12898      11 Round to 0
12899
12900   FLT_ROUNDS, on the other hand, expects the following:
12901     -1 Undefined
12902      0 Round to 0
12903      1 Round to nearest
12904      2 Round to +inf
12905      3 Round to -inf
12906
12907   To perform the conversion, we do:
12908     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
12909   */
12910
12911   MachineFunction &MF = DAG.getMachineFunction();
12912   const TargetMachine &TM = MF.getTarget();
12913   const TargetFrameLowering &TFI = *TM.getFrameLowering();
12914   unsigned StackAlignment = TFI.getStackAlignment();
12915   MVT VT = Op.getSimpleValueType();
12916   SDLoc DL(Op);
12917
12918   // Save FP Control Word to stack slot
12919   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
12920   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12921
12922   MachineMemOperand *MMO =
12923    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12924                            MachineMemOperand::MOStore, 2, 2);
12925
12926   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
12927   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
12928                                           DAG.getVTList(MVT::Other),
12929                                           Ops, MVT::i16, MMO);
12930
12931   // Load FP Control Word from stack slot
12932   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
12933                             MachinePointerInfo(), false, false, false, 0);
12934
12935   // Transform as necessary
12936   SDValue CWD1 =
12937     DAG.getNode(ISD::SRL, DL, MVT::i16,
12938                 DAG.getNode(ISD::AND, DL, MVT::i16,
12939                             CWD, DAG.getConstant(0x800, MVT::i16)),
12940                 DAG.getConstant(11, MVT::i8));
12941   SDValue CWD2 =
12942     DAG.getNode(ISD::SRL, DL, MVT::i16,
12943                 DAG.getNode(ISD::AND, DL, MVT::i16,
12944                             CWD, DAG.getConstant(0x400, MVT::i16)),
12945                 DAG.getConstant(9, MVT::i8));
12946
12947   SDValue RetVal =
12948     DAG.getNode(ISD::AND, DL, MVT::i16,
12949                 DAG.getNode(ISD::ADD, DL, MVT::i16,
12950                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
12951                             DAG.getConstant(1, MVT::i16)),
12952                 DAG.getConstant(3, MVT::i16));
12953
12954   return DAG.getNode((VT.getSizeInBits() < 16 ?
12955                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
12956 }
12957
12958 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
12959   MVT VT = Op.getSimpleValueType();
12960   EVT OpVT = VT;
12961   unsigned NumBits = VT.getSizeInBits();
12962   SDLoc dl(Op);
12963
12964   Op = Op.getOperand(0);
12965   if (VT == MVT::i8) {
12966     // Zero extend to i32 since there is not an i8 bsr.
12967     OpVT = MVT::i32;
12968     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
12969   }
12970
12971   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
12972   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12973   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
12974
12975   // If src is zero (i.e. bsr sets ZF), returns NumBits.
12976   SDValue Ops[] = {
12977     Op,
12978     DAG.getConstant(NumBits+NumBits-1, OpVT),
12979     DAG.getConstant(X86::COND_E, MVT::i8),
12980     Op.getValue(1)
12981   };
12982   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
12983
12984   // Finally xor with NumBits-1.
12985   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
12986
12987   if (VT == MVT::i8)
12988     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
12989   return Op;
12990 }
12991
12992 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
12993   MVT VT = Op.getSimpleValueType();
12994   EVT OpVT = VT;
12995   unsigned NumBits = VT.getSizeInBits();
12996   SDLoc dl(Op);
12997
12998   Op = Op.getOperand(0);
12999   if (VT == MVT::i8) {
13000     // Zero extend to i32 since there is not an i8 bsr.
13001     OpVT = MVT::i32;
13002     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13003   }
13004
13005   // Issue a bsr (scan bits in reverse).
13006   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13007   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13008
13009   // And xor with NumBits-1.
13010   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13011
13012   if (VT == MVT::i8)
13013     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13014   return Op;
13015 }
13016
13017 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13018   MVT VT = Op.getSimpleValueType();
13019   unsigned NumBits = VT.getSizeInBits();
13020   SDLoc dl(Op);
13021   Op = Op.getOperand(0);
13022
13023   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13024   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13025   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13026
13027   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13028   SDValue Ops[] = {
13029     Op,
13030     DAG.getConstant(NumBits, VT),
13031     DAG.getConstant(X86::COND_E, MVT::i8),
13032     Op.getValue(1)
13033   };
13034   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13035 }
13036
13037 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13038 // ones, and then concatenate the result back.
13039 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13040   MVT VT = Op.getSimpleValueType();
13041
13042   assert(VT.is256BitVector() && VT.isInteger() &&
13043          "Unsupported value type for operation");
13044
13045   unsigned NumElems = VT.getVectorNumElements();
13046   SDLoc dl(Op);
13047
13048   // Extract the LHS vectors
13049   SDValue LHS = Op.getOperand(0);
13050   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13051   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13052
13053   // Extract the RHS vectors
13054   SDValue RHS = Op.getOperand(1);
13055   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13056   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13057
13058   MVT EltVT = VT.getVectorElementType();
13059   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13060
13061   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13062                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13063                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13064 }
13065
13066 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13067   assert(Op.getSimpleValueType().is256BitVector() &&
13068          Op.getSimpleValueType().isInteger() &&
13069          "Only handle AVX 256-bit vector integer operation");
13070   return Lower256IntArith(Op, DAG);
13071 }
13072
13073 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13074   assert(Op.getSimpleValueType().is256BitVector() &&
13075          Op.getSimpleValueType().isInteger() &&
13076          "Only handle AVX 256-bit vector integer operation");
13077   return Lower256IntArith(Op, DAG);
13078 }
13079
13080 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13081                         SelectionDAG &DAG) {
13082   SDLoc dl(Op);
13083   MVT VT = Op.getSimpleValueType();
13084
13085   // Decompose 256-bit ops into smaller 128-bit ops.
13086   if (VT.is256BitVector() && !Subtarget->hasInt256())
13087     return Lower256IntArith(Op, DAG);
13088
13089   SDValue A = Op.getOperand(0);
13090   SDValue B = Op.getOperand(1);
13091
13092   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13093   if (VT == MVT::v4i32) {
13094     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13095            "Should not custom lower when pmuldq is available!");
13096
13097     // Extract the odd parts.
13098     static const int UnpackMask[] = { 1, -1, 3, -1 };
13099     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13100     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13101
13102     // Multiply the even parts.
13103     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13104     // Now multiply odd parts.
13105     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13106
13107     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13108     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13109
13110     // Merge the two vectors back together with a shuffle. This expands into 2
13111     // shuffles.
13112     static const int ShufMask[] = { 0, 4, 2, 6 };
13113     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13114   }
13115
13116   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13117          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13118
13119   //  Ahi = psrlqi(a, 32);
13120   //  Bhi = psrlqi(b, 32);
13121   //
13122   //  AloBlo = pmuludq(a, b);
13123   //  AloBhi = pmuludq(a, Bhi);
13124   //  AhiBlo = pmuludq(Ahi, b);
13125
13126   //  AloBhi = psllqi(AloBhi, 32);
13127   //  AhiBlo = psllqi(AhiBlo, 32);
13128   //  return AloBlo + AloBhi + AhiBlo;
13129
13130   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13131   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13132
13133   // Bit cast to 32-bit vectors for MULUDQ
13134   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13135                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13136   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13137   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13138   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13139   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13140
13141   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13142   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13143   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13144
13145   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13146   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13147
13148   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13149   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13150 }
13151
13152 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13153                              SelectionDAG &DAG) {
13154   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13155   EVT VT = Op0.getValueType();
13156   SDLoc dl(Op);
13157
13158   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13159          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13160
13161   // Get the high parts.
13162   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13163   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13164   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13165
13166   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13167   // ints.
13168   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13169   unsigned Opcode =
13170       Op->getOpcode() == ISD::UMUL_LOHI ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13171   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13172                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13173   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13174                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13175
13176   // Shuffle it back into the right order.
13177   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13178   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13179   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13180   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13181
13182   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13183 }
13184
13185 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13186                                          const X86Subtarget *Subtarget) {
13187   MVT VT = Op.getSimpleValueType();
13188   SDLoc dl(Op);
13189   SDValue R = Op.getOperand(0);
13190   SDValue Amt = Op.getOperand(1);
13191
13192   // Optimize shl/srl/sra with constant shift amount.
13193   if (isSplatVector(Amt.getNode())) {
13194     SDValue SclrAmt = Amt->getOperand(0);
13195     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13196       uint64_t ShiftAmt = C->getZExtValue();
13197
13198       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13199           (Subtarget->hasInt256() &&
13200            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13201           (Subtarget->hasAVX512() &&
13202            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13203         if (Op.getOpcode() == ISD::SHL)
13204           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13205                                             DAG);
13206         if (Op.getOpcode() == ISD::SRL)
13207           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13208                                             DAG);
13209         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13210           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13211                                             DAG);
13212       }
13213
13214       if (VT == MVT::v16i8) {
13215         if (Op.getOpcode() == ISD::SHL) {
13216           // Make a large shift.
13217           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13218                                                    MVT::v8i16, R, ShiftAmt,
13219                                                    DAG);
13220           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13221           // Zero out the rightmost bits.
13222           SmallVector<SDValue, 16> V(16,
13223                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13224                                                      MVT::i8));
13225           return DAG.getNode(ISD::AND, dl, VT, SHL,
13226                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13227         }
13228         if (Op.getOpcode() == ISD::SRL) {
13229           // Make a large shift.
13230           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13231                                                    MVT::v8i16, R, ShiftAmt,
13232                                                    DAG);
13233           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13234           // Zero out the leftmost bits.
13235           SmallVector<SDValue, 16> V(16,
13236                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13237                                                      MVT::i8));
13238           return DAG.getNode(ISD::AND, dl, VT, SRL,
13239                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13240         }
13241         if (Op.getOpcode() == ISD::SRA) {
13242           if (ShiftAmt == 7) {
13243             // R s>> 7  ===  R s< 0
13244             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13245             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13246           }
13247
13248           // R s>> a === ((R u>> a) ^ m) - m
13249           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13250           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13251                                                          MVT::i8));
13252           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13253           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13254           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13255           return Res;
13256         }
13257         llvm_unreachable("Unknown shift opcode.");
13258       }
13259
13260       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13261         if (Op.getOpcode() == ISD::SHL) {
13262           // Make a large shift.
13263           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13264                                                    MVT::v16i16, R, ShiftAmt,
13265                                                    DAG);
13266           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13267           // Zero out the rightmost bits.
13268           SmallVector<SDValue, 32> V(32,
13269                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13270                                                      MVT::i8));
13271           return DAG.getNode(ISD::AND, dl, VT, SHL,
13272                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13273         }
13274         if (Op.getOpcode() == ISD::SRL) {
13275           // Make a large shift.
13276           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13277                                                    MVT::v16i16, R, ShiftAmt,
13278                                                    DAG);
13279           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13280           // Zero out the leftmost bits.
13281           SmallVector<SDValue, 32> V(32,
13282                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13283                                                      MVT::i8));
13284           return DAG.getNode(ISD::AND, dl, VT, SRL,
13285                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13286         }
13287         if (Op.getOpcode() == ISD::SRA) {
13288           if (ShiftAmt == 7) {
13289             // R s>> 7  ===  R s< 0
13290             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13291             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13292           }
13293
13294           // R s>> a === ((R u>> a) ^ m) - m
13295           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13296           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13297                                                          MVT::i8));
13298           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13299           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13300           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13301           return Res;
13302         }
13303         llvm_unreachable("Unknown shift opcode.");
13304       }
13305     }
13306   }
13307
13308   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13309   if (!Subtarget->is64Bit() &&
13310       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13311       Amt.getOpcode() == ISD::BITCAST &&
13312       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13313     Amt = Amt.getOperand(0);
13314     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13315                      VT.getVectorNumElements();
13316     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13317     uint64_t ShiftAmt = 0;
13318     for (unsigned i = 0; i != Ratio; ++i) {
13319       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13320       if (!C)
13321         return SDValue();
13322       // 6 == Log2(64)
13323       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13324     }
13325     // Check remaining shift amounts.
13326     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13327       uint64_t ShAmt = 0;
13328       for (unsigned j = 0; j != Ratio; ++j) {
13329         ConstantSDNode *C =
13330           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13331         if (!C)
13332           return SDValue();
13333         // 6 == Log2(64)
13334         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13335       }
13336       if (ShAmt != ShiftAmt)
13337         return SDValue();
13338     }
13339     switch (Op.getOpcode()) {
13340     default:
13341       llvm_unreachable("Unknown shift opcode!");
13342     case ISD::SHL:
13343       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13344                                         DAG);
13345     case ISD::SRL:
13346       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13347                                         DAG);
13348     case ISD::SRA:
13349       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13350                                         DAG);
13351     }
13352   }
13353
13354   return SDValue();
13355 }
13356
13357 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13358                                         const X86Subtarget* Subtarget) {
13359   MVT VT = Op.getSimpleValueType();
13360   SDLoc dl(Op);
13361   SDValue R = Op.getOperand(0);
13362   SDValue Amt = Op.getOperand(1);
13363
13364   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13365       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13366       (Subtarget->hasInt256() &&
13367        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13368         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13369        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13370     SDValue BaseShAmt;
13371     EVT EltVT = VT.getVectorElementType();
13372
13373     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13374       unsigned NumElts = VT.getVectorNumElements();
13375       unsigned i, j;
13376       for (i = 0; i != NumElts; ++i) {
13377         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13378           continue;
13379         break;
13380       }
13381       for (j = i; j != NumElts; ++j) {
13382         SDValue Arg = Amt.getOperand(j);
13383         if (Arg.getOpcode() == ISD::UNDEF) continue;
13384         if (Arg != Amt.getOperand(i))
13385           break;
13386       }
13387       if (i != NumElts && j == NumElts)
13388         BaseShAmt = Amt.getOperand(i);
13389     } else {
13390       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13391         Amt = Amt.getOperand(0);
13392       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13393                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13394         SDValue InVec = Amt.getOperand(0);
13395         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13396           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13397           unsigned i = 0;
13398           for (; i != NumElts; ++i) {
13399             SDValue Arg = InVec.getOperand(i);
13400             if (Arg.getOpcode() == ISD::UNDEF) continue;
13401             BaseShAmt = Arg;
13402             break;
13403           }
13404         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13405            if (ConstantSDNode *C =
13406                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13407              unsigned SplatIdx =
13408                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13409              if (C->getZExtValue() == SplatIdx)
13410                BaseShAmt = InVec.getOperand(1);
13411            }
13412         }
13413         if (!BaseShAmt.getNode())
13414           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13415                                   DAG.getIntPtrConstant(0));
13416       }
13417     }
13418
13419     if (BaseShAmt.getNode()) {
13420       if (EltVT.bitsGT(MVT::i32))
13421         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13422       else if (EltVT.bitsLT(MVT::i32))
13423         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13424
13425       switch (Op.getOpcode()) {
13426       default:
13427         llvm_unreachable("Unknown shift opcode!");
13428       case ISD::SHL:
13429         switch (VT.SimpleTy) {
13430         default: return SDValue();
13431         case MVT::v2i64:
13432         case MVT::v4i32:
13433         case MVT::v8i16:
13434         case MVT::v4i64:
13435         case MVT::v8i32:
13436         case MVT::v16i16:
13437         case MVT::v16i32:
13438         case MVT::v8i64:
13439           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13440         }
13441       case ISD::SRA:
13442         switch (VT.SimpleTy) {
13443         default: return SDValue();
13444         case MVT::v4i32:
13445         case MVT::v8i16:
13446         case MVT::v8i32:
13447         case MVT::v16i16:
13448         case MVT::v16i32:
13449         case MVT::v8i64:
13450           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13451         }
13452       case ISD::SRL:
13453         switch (VT.SimpleTy) {
13454         default: return SDValue();
13455         case MVT::v2i64:
13456         case MVT::v4i32:
13457         case MVT::v8i16:
13458         case MVT::v4i64:
13459         case MVT::v8i32:
13460         case MVT::v16i16:
13461         case MVT::v16i32:
13462         case MVT::v8i64:
13463           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13464         }
13465       }
13466     }
13467   }
13468
13469   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13470   if (!Subtarget->is64Bit() &&
13471       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13472       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13473       Amt.getOpcode() == ISD::BITCAST &&
13474       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13475     Amt = Amt.getOperand(0);
13476     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13477                      VT.getVectorNumElements();
13478     std::vector<SDValue> Vals(Ratio);
13479     for (unsigned i = 0; i != Ratio; ++i)
13480       Vals[i] = Amt.getOperand(i);
13481     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13482       for (unsigned j = 0; j != Ratio; ++j)
13483         if (Vals[j] != Amt.getOperand(i + j))
13484           return SDValue();
13485     }
13486     switch (Op.getOpcode()) {
13487     default:
13488       llvm_unreachable("Unknown shift opcode!");
13489     case ISD::SHL:
13490       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13491     case ISD::SRL:
13492       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13493     case ISD::SRA:
13494       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13495     }
13496   }
13497
13498   return SDValue();
13499 }
13500
13501 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13502                           SelectionDAG &DAG) {
13503
13504   MVT VT = Op.getSimpleValueType();
13505   SDLoc dl(Op);
13506   SDValue R = Op.getOperand(0);
13507   SDValue Amt = Op.getOperand(1);
13508   SDValue V;
13509
13510   if (!Subtarget->hasSSE2())
13511     return SDValue();
13512
13513   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13514   if (V.getNode())
13515     return V;
13516
13517   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13518   if (V.getNode())
13519       return V;
13520
13521   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13522     return Op;
13523   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13524   if (Subtarget->hasInt256()) {
13525     if (Op.getOpcode() == ISD::SRL &&
13526         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13527          VT == MVT::v4i64 || VT == MVT::v8i32))
13528       return Op;
13529     if (Op.getOpcode() == ISD::SHL &&
13530         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13531          VT == MVT::v4i64 || VT == MVT::v8i32))
13532       return Op;
13533     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13534       return Op;
13535   }
13536
13537   // If possible, lower this packed shift into a vector multiply instead of
13538   // expanding it into a sequence of scalar shifts.
13539   // Do this only if the vector shift count is a constant build_vector.
13540   if (Op.getOpcode() == ISD::SHL && 
13541       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13542        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13543       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13544     SmallVector<SDValue, 8> Elts;
13545     EVT SVT = VT.getScalarType();
13546     unsigned SVTBits = SVT.getSizeInBits();
13547     const APInt &One = APInt(SVTBits, 1);
13548     unsigned NumElems = VT.getVectorNumElements();
13549
13550     for (unsigned i=0; i !=NumElems; ++i) {
13551       SDValue Op = Amt->getOperand(i);
13552       if (Op->getOpcode() == ISD::UNDEF) {
13553         Elts.push_back(Op);
13554         continue;
13555       }
13556
13557       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13558       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13559       uint64_t ShAmt = C.getZExtValue();
13560       if (ShAmt >= SVTBits) {
13561         Elts.push_back(DAG.getUNDEF(SVT));
13562         continue;
13563       }
13564       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13565     }
13566     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13567     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13568   }
13569
13570   // Lower SHL with variable shift amount.
13571   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13572     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13573
13574     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13575     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13576     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13577     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13578   }
13579
13580   // If possible, lower this shift as a sequence of two shifts by
13581   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13582   // Example:
13583   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13584   //
13585   // Could be rewritten as:
13586   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13587   //
13588   // The advantage is that the two shifts from the example would be
13589   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13590   // the vector shift into four scalar shifts plus four pairs of vector
13591   // insert/extract.
13592   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13593       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13594     unsigned TargetOpcode = X86ISD::MOVSS;
13595     bool CanBeSimplified;
13596     // The splat value for the first packed shift (the 'X' from the example).
13597     SDValue Amt1 = Amt->getOperand(0);
13598     // The splat value for the second packed shift (the 'Y' from the example).
13599     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13600                                         Amt->getOperand(2);
13601
13602     // See if it is possible to replace this node with a sequence of
13603     // two shifts followed by a MOVSS/MOVSD
13604     if (VT == MVT::v4i32) {
13605       // Check if it is legal to use a MOVSS.
13606       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13607                         Amt2 == Amt->getOperand(3);
13608       if (!CanBeSimplified) {
13609         // Otherwise, check if we can still simplify this node using a MOVSD.
13610         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13611                           Amt->getOperand(2) == Amt->getOperand(3);
13612         TargetOpcode = X86ISD::MOVSD;
13613         Amt2 = Amt->getOperand(2);
13614       }
13615     } else {
13616       // Do similar checks for the case where the machine value type
13617       // is MVT::v8i16.
13618       CanBeSimplified = Amt1 == Amt->getOperand(1);
13619       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13620         CanBeSimplified = Amt2 == Amt->getOperand(i);
13621
13622       if (!CanBeSimplified) {
13623         TargetOpcode = X86ISD::MOVSD;
13624         CanBeSimplified = true;
13625         Amt2 = Amt->getOperand(4);
13626         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13627           CanBeSimplified = Amt1 == Amt->getOperand(i);
13628         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13629           CanBeSimplified = Amt2 == Amt->getOperand(j);
13630       }
13631     }
13632     
13633     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13634         isa<ConstantSDNode>(Amt2)) {
13635       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13636       EVT CastVT = MVT::v4i32;
13637       SDValue Splat1 = 
13638         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13639       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13640       SDValue Splat2 = 
13641         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13642       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13643       if (TargetOpcode == X86ISD::MOVSD)
13644         CastVT = MVT::v2i64;
13645       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13646       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13647       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13648                                             BitCast1, DAG);
13649       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13650     }
13651   }
13652
13653   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13654     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13655
13656     // a = a << 5;
13657     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13658     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13659
13660     // Turn 'a' into a mask suitable for VSELECT
13661     SDValue VSelM = DAG.getConstant(0x80, VT);
13662     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13663     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13664
13665     SDValue CM1 = DAG.getConstant(0x0f, VT);
13666     SDValue CM2 = DAG.getConstant(0x3f, VT);
13667
13668     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13669     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13670     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13671     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13672     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13673
13674     // a += a
13675     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13676     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13677     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13678
13679     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13680     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13681     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13682     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13683     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13684
13685     // a += a
13686     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13687     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13688     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13689
13690     // return VSELECT(r, r+r, a);
13691     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13692                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13693     return R;
13694   }
13695
13696   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13697   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13698   // solution better.
13699   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13700     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13701     unsigned ExtOpc =
13702         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13703     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13704     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13705     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13706                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13707     }
13708
13709   // Decompose 256-bit shifts into smaller 128-bit shifts.
13710   if (VT.is256BitVector()) {
13711     unsigned NumElems = VT.getVectorNumElements();
13712     MVT EltVT = VT.getVectorElementType();
13713     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13714
13715     // Extract the two vectors
13716     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13717     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13718
13719     // Recreate the shift amount vectors
13720     SDValue Amt1, Amt2;
13721     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13722       // Constant shift amount
13723       SmallVector<SDValue, 4> Amt1Csts;
13724       SmallVector<SDValue, 4> Amt2Csts;
13725       for (unsigned i = 0; i != NumElems/2; ++i)
13726         Amt1Csts.push_back(Amt->getOperand(i));
13727       for (unsigned i = NumElems/2; i != NumElems; ++i)
13728         Amt2Csts.push_back(Amt->getOperand(i));
13729
13730       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13731       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13732     } else {
13733       // Variable shift amount
13734       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13735       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13736     }
13737
13738     // Issue new vector shifts for the smaller types
13739     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13740     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13741
13742     // Concatenate the result back
13743     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13744   }
13745
13746   return SDValue();
13747 }
13748
13749 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13750   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13751   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13752   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13753   // has only one use.
13754   SDNode *N = Op.getNode();
13755   SDValue LHS = N->getOperand(0);
13756   SDValue RHS = N->getOperand(1);
13757   unsigned BaseOp = 0;
13758   unsigned Cond = 0;
13759   SDLoc DL(Op);
13760   switch (Op.getOpcode()) {
13761   default: llvm_unreachable("Unknown ovf instruction!");
13762   case ISD::SADDO:
13763     // A subtract of one will be selected as a INC. Note that INC doesn't
13764     // set CF, so we can't do this for UADDO.
13765     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13766       if (C->isOne()) {
13767         BaseOp = X86ISD::INC;
13768         Cond = X86::COND_O;
13769         break;
13770       }
13771     BaseOp = X86ISD::ADD;
13772     Cond = X86::COND_O;
13773     break;
13774   case ISD::UADDO:
13775     BaseOp = X86ISD::ADD;
13776     Cond = X86::COND_B;
13777     break;
13778   case ISD::SSUBO:
13779     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13780     // set CF, so we can't do this for USUBO.
13781     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13782       if (C->isOne()) {
13783         BaseOp = X86ISD::DEC;
13784         Cond = X86::COND_O;
13785         break;
13786       }
13787     BaseOp = X86ISD::SUB;
13788     Cond = X86::COND_O;
13789     break;
13790   case ISD::USUBO:
13791     BaseOp = X86ISD::SUB;
13792     Cond = X86::COND_B;
13793     break;
13794   case ISD::SMULO:
13795     BaseOp = X86ISD::SMUL;
13796     Cond = X86::COND_O;
13797     break;
13798   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13799     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13800                                  MVT::i32);
13801     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13802
13803     SDValue SetCC =
13804       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13805                   DAG.getConstant(X86::COND_O, MVT::i32),
13806                   SDValue(Sum.getNode(), 2));
13807
13808     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13809   }
13810   }
13811
13812   // Also sets EFLAGS.
13813   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13814   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13815
13816   SDValue SetCC =
13817     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13818                 DAG.getConstant(Cond, MVT::i32),
13819                 SDValue(Sum.getNode(), 1));
13820
13821   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13822 }
13823
13824 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13825                                                   SelectionDAG &DAG) const {
13826   SDLoc dl(Op);
13827   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13828   MVT VT = Op.getSimpleValueType();
13829
13830   if (!Subtarget->hasSSE2() || !VT.isVector())
13831     return SDValue();
13832
13833   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13834                       ExtraVT.getScalarType().getSizeInBits();
13835
13836   switch (VT.SimpleTy) {
13837     default: return SDValue();
13838     case MVT::v8i32:
13839     case MVT::v16i16:
13840       if (!Subtarget->hasFp256())
13841         return SDValue();
13842       if (!Subtarget->hasInt256()) {
13843         // needs to be split
13844         unsigned NumElems = VT.getVectorNumElements();
13845
13846         // Extract the LHS vectors
13847         SDValue LHS = Op.getOperand(0);
13848         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13849         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13850
13851         MVT EltVT = VT.getVectorElementType();
13852         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13853
13854         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13855         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13856         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13857                                    ExtraNumElems/2);
13858         SDValue Extra = DAG.getValueType(ExtraVT);
13859
13860         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13861         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13862
13863         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13864       }
13865       // fall through
13866     case MVT::v4i32:
13867     case MVT::v8i16: {
13868       SDValue Op0 = Op.getOperand(0);
13869       SDValue Op00 = Op0.getOperand(0);
13870       SDValue Tmp1;
13871       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13872       if (Op0.getOpcode() == ISD::BITCAST &&
13873           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13874         // (sext (vzext x)) -> (vsext x)
13875         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13876         if (Tmp1.getNode()) {
13877           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13878           // This folding is only valid when the in-reg type is a vector of i8,
13879           // i16, or i32.
13880           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13881               ExtraEltVT == MVT::i32) {
13882             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13883             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13884                    "This optimization is invalid without a VZEXT.");
13885             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13886           }
13887           Op0 = Tmp1;
13888         }
13889       }
13890
13891       // If the above didn't work, then just use Shift-Left + Shift-Right.
13892       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13893                                         DAG);
13894       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13895                                         DAG);
13896     }
13897   }
13898 }
13899
13900 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13901                                  SelectionDAG &DAG) {
13902   SDLoc dl(Op);
13903   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13904     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13905   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13906     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13907
13908   // The only fence that needs an instruction is a sequentially-consistent
13909   // cross-thread fence.
13910   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13911     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13912     // no-sse2). There isn't any reason to disable it if the target processor
13913     // supports it.
13914     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13915       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13916
13917     SDValue Chain = Op.getOperand(0);
13918     SDValue Zero = DAG.getConstant(0, MVT::i32);
13919     SDValue Ops[] = {
13920       DAG.getRegister(X86::ESP, MVT::i32), // Base
13921       DAG.getTargetConstant(1, MVT::i8),   // Scale
13922       DAG.getRegister(0, MVT::i32),        // Index
13923       DAG.getTargetConstant(0, MVT::i32),  // Disp
13924       DAG.getRegister(0, MVT::i32),        // Segment.
13925       Zero,
13926       Chain
13927     };
13928     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13929     return SDValue(Res, 0);
13930   }
13931
13932   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13933   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13934 }
13935
13936 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13937                              SelectionDAG &DAG) {
13938   MVT T = Op.getSimpleValueType();
13939   SDLoc DL(Op);
13940   unsigned Reg = 0;
13941   unsigned size = 0;
13942   switch(T.SimpleTy) {
13943   default: llvm_unreachable("Invalid value type!");
13944   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13945   case MVT::i16: Reg = X86::AX;  size = 2; break;
13946   case MVT::i32: Reg = X86::EAX; size = 4; break;
13947   case MVT::i64:
13948     assert(Subtarget->is64Bit() && "Node not type legal!");
13949     Reg = X86::RAX; size = 8;
13950     break;
13951   }
13952   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13953                                     Op.getOperand(2), SDValue());
13954   SDValue Ops[] = { cpIn.getValue(0),
13955                     Op.getOperand(1),
13956                     Op.getOperand(3),
13957                     DAG.getTargetConstant(size, MVT::i8),
13958                     cpIn.getValue(1) };
13959   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13960   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13961   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13962                                            Ops, T, MMO);
13963   SDValue cpOut =
13964     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13965   return cpOut;
13966 }
13967
13968 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13969                             SelectionDAG &DAG) {
13970   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13971   MVT DstVT = Op.getSimpleValueType();
13972   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13973          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13974   assert((DstVT == MVT::i64 ||
13975           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13976          "Unexpected custom BITCAST");
13977   // i64 <=> MMX conversions are Legal.
13978   if (SrcVT==MVT::i64 && DstVT.isVector())
13979     return Op;
13980   if (DstVT==MVT::i64 && SrcVT.isVector())
13981     return Op;
13982   // MMX <=> MMX conversions are Legal.
13983   if (SrcVT.isVector() && DstVT.isVector())
13984     return Op;
13985   // All other conversions need to be expanded.
13986   return SDValue();
13987 }
13988
13989 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
13990   SDNode *Node = Op.getNode();
13991   SDLoc dl(Node);
13992   EVT T = Node->getValueType(0);
13993   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
13994                               DAG.getConstant(0, T), Node->getOperand(2));
13995   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
13996                        cast<AtomicSDNode>(Node)->getMemoryVT(),
13997                        Node->getOperand(0),
13998                        Node->getOperand(1), negOp,
13999                        cast<AtomicSDNode>(Node)->getMemOperand(),
14000                        cast<AtomicSDNode>(Node)->getOrdering(),
14001                        cast<AtomicSDNode>(Node)->getSynchScope());
14002 }
14003
14004 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14005   SDNode *Node = Op.getNode();
14006   SDLoc dl(Node);
14007   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14008
14009   // Convert seq_cst store -> xchg
14010   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14011   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14012   //        (The only way to get a 16-byte store is cmpxchg16b)
14013   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14014   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14015       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14016     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14017                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14018                                  Node->getOperand(0),
14019                                  Node->getOperand(1), Node->getOperand(2),
14020                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14021                                  cast<AtomicSDNode>(Node)->getOrdering(),
14022                                  cast<AtomicSDNode>(Node)->getSynchScope());
14023     return Swap.getValue(1);
14024   }
14025   // Other atomic stores have a simple pattern.
14026   return Op;
14027 }
14028
14029 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14030   EVT VT = Op.getNode()->getSimpleValueType(0);
14031
14032   // Let legalize expand this if it isn't a legal type yet.
14033   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14034     return SDValue();
14035
14036   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14037
14038   unsigned Opc;
14039   bool ExtraOp = false;
14040   switch (Op.getOpcode()) {
14041   default: llvm_unreachable("Invalid code");
14042   case ISD::ADDC: Opc = X86ISD::ADD; break;
14043   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14044   case ISD::SUBC: Opc = X86ISD::SUB; break;
14045   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14046   }
14047
14048   if (!ExtraOp)
14049     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14050                        Op.getOperand(1));
14051   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14052                      Op.getOperand(1), Op.getOperand(2));
14053 }
14054
14055 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14056                             SelectionDAG &DAG) {
14057   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14058
14059   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14060   // which returns the values as { float, float } (in XMM0) or
14061   // { double, double } (which is returned in XMM0, XMM1).
14062   SDLoc dl(Op);
14063   SDValue Arg = Op.getOperand(0);
14064   EVT ArgVT = Arg.getValueType();
14065   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14066
14067   TargetLowering::ArgListTy Args;
14068   TargetLowering::ArgListEntry Entry;
14069
14070   Entry.Node = Arg;
14071   Entry.Ty = ArgTy;
14072   Entry.isSExt = false;
14073   Entry.isZExt = false;
14074   Args.push_back(Entry);
14075
14076   bool isF64 = ArgVT == MVT::f64;
14077   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14078   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14079   // the results are returned via SRet in memory.
14080   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14081   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14082   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14083
14084   Type *RetTy = isF64
14085     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14086     : (Type*)VectorType::get(ArgTy, 4);
14087   TargetLowering::
14088     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14089                          false, false, false, false, 0,
14090                          CallingConv::C, /*isTaillCall=*/false,
14091                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14092                          Callee, Args, DAG, dl);
14093   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14094
14095   if (isF64)
14096     // Returned in xmm0 and xmm1.
14097     return CallResult.first;
14098
14099   // Returned in bits 0:31 and 32:64 xmm0.
14100   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14101                                CallResult.first, DAG.getIntPtrConstant(0));
14102   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14103                                CallResult.first, DAG.getIntPtrConstant(1));
14104   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14105   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14106 }
14107
14108 /// LowerOperation - Provide custom lowering hooks for some operations.
14109 ///
14110 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14111   switch (Op.getOpcode()) {
14112   default: llvm_unreachable("Should not custom lower this!");
14113   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14114   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14115   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14116   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14117   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14118   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14119   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14120   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14121   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14122   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14123   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14124   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14125   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14126   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14127   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14128   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14129   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14130   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14131   case ISD::SHL_PARTS:
14132   case ISD::SRA_PARTS:
14133   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14134   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14135   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14136   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14137   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14138   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14139   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14140   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14141   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14142   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14143   case ISD::FABS:               return LowerFABS(Op, DAG);
14144   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14145   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14146   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14147   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14148   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14149   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14150   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14151   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14152   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14153   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14154   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14155   case ISD::INTRINSIC_VOID:
14156   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14157   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14158   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14159   case ISD::FRAME_TO_ARGS_OFFSET:
14160                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14161   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14162   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14163   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14164   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14165   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14166   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14167   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14168   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14169   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14170   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14171   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14172   case ISD::UMUL_LOHI:
14173   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14174   case ISD::SRA:
14175   case ISD::SRL:
14176   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14177   case ISD::SADDO:
14178   case ISD::UADDO:
14179   case ISD::SSUBO:
14180   case ISD::USUBO:
14181   case ISD::SMULO:
14182   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14183   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14184   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14185   case ISD::ADDC:
14186   case ISD::ADDE:
14187   case ISD::SUBC:
14188   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14189   case ISD::ADD:                return LowerADD(Op, DAG);
14190   case ISD::SUB:                return LowerSUB(Op, DAG);
14191   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14192   }
14193 }
14194
14195 static void ReplaceATOMIC_LOAD(SDNode *Node,
14196                                   SmallVectorImpl<SDValue> &Results,
14197                                   SelectionDAG &DAG) {
14198   SDLoc dl(Node);
14199   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14200
14201   // Convert wide load -> cmpxchg8b/cmpxchg16b
14202   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14203   //        (The only way to get a 16-byte load is cmpxchg16b)
14204   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14205   SDValue Zero = DAG.getConstant(0, VT);
14206   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14207                                Node->getOperand(0),
14208                                Node->getOperand(1), Zero, Zero,
14209                                cast<AtomicSDNode>(Node)->getMemOperand(),
14210                                cast<AtomicSDNode>(Node)->getOrdering(),
14211                                cast<AtomicSDNode>(Node)->getOrdering(),
14212                                cast<AtomicSDNode>(Node)->getSynchScope());
14213   Results.push_back(Swap.getValue(0));
14214   Results.push_back(Swap.getValue(1));
14215 }
14216
14217 static void
14218 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14219                         SelectionDAG &DAG, unsigned NewOp) {
14220   SDLoc dl(Node);
14221   assert (Node->getValueType(0) == MVT::i64 &&
14222           "Only know how to expand i64 atomics");
14223
14224   SDValue Chain = Node->getOperand(0);
14225   SDValue In1 = Node->getOperand(1);
14226   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14227                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14228   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14229                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14230   SDValue Ops[] = { Chain, In1, In2L, In2H };
14231   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14232   SDValue Result =
14233     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14234                             cast<MemSDNode>(Node)->getMemOperand());
14235   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14236   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14237   Results.push_back(Result.getValue(2));
14238 }
14239
14240 /// ReplaceNodeResults - Replace a node with an illegal result type
14241 /// with a new node built out of custom code.
14242 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14243                                            SmallVectorImpl<SDValue>&Results,
14244                                            SelectionDAG &DAG) const {
14245   SDLoc dl(N);
14246   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14247   switch (N->getOpcode()) {
14248   default:
14249     llvm_unreachable("Do not know how to custom type legalize this operation!");
14250   case ISD::SIGN_EXTEND_INREG:
14251   case ISD::ADDC:
14252   case ISD::ADDE:
14253   case ISD::SUBC:
14254   case ISD::SUBE:
14255     // We don't want to expand or promote these.
14256     return;
14257   case ISD::FP_TO_SINT:
14258   case ISD::FP_TO_UINT: {
14259     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14260
14261     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14262       return;
14263
14264     std::pair<SDValue,SDValue> Vals =
14265         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14266     SDValue FIST = Vals.first, StackSlot = Vals.second;
14267     if (FIST.getNode()) {
14268       EVT VT = N->getValueType(0);
14269       // Return a load from the stack slot.
14270       if (StackSlot.getNode())
14271         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14272                                       MachinePointerInfo(),
14273                                       false, false, false, 0));
14274       else
14275         Results.push_back(FIST);
14276     }
14277     return;
14278   }
14279   case ISD::UINT_TO_FP: {
14280     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14281     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14282         N->getValueType(0) != MVT::v2f32)
14283       return;
14284     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14285                                  N->getOperand(0));
14286     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14287                                      MVT::f64);
14288     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14289     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14290                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14291     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14292     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14293     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14294     return;
14295   }
14296   case ISD::FP_ROUND: {
14297     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14298         return;
14299     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14300     Results.push_back(V);
14301     return;
14302   }
14303   case ISD::INTRINSIC_W_CHAIN: {
14304     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14305     switch (IntNo) {
14306     default : llvm_unreachable("Do not know how to custom type "
14307                                "legalize this intrinsic operation!");
14308     case Intrinsic::x86_rdtsc:
14309       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14310                                      Results);
14311     case Intrinsic::x86_rdtscp:
14312       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14313                                      Results);
14314     }
14315   }
14316   case ISD::READCYCLECOUNTER: {
14317     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14318                                    Results);
14319   }
14320   case ISD::ATOMIC_CMP_SWAP: {
14321     EVT T = N->getValueType(0);
14322     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14323     bool Regs64bit = T == MVT::i128;
14324     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14325     SDValue cpInL, cpInH;
14326     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14327                         DAG.getConstant(0, HalfT));
14328     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14329                         DAG.getConstant(1, HalfT));
14330     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14331                              Regs64bit ? X86::RAX : X86::EAX,
14332                              cpInL, SDValue());
14333     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14334                              Regs64bit ? X86::RDX : X86::EDX,
14335                              cpInH, cpInL.getValue(1));
14336     SDValue swapInL, swapInH;
14337     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14338                           DAG.getConstant(0, HalfT));
14339     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14340                           DAG.getConstant(1, HalfT));
14341     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14342                                Regs64bit ? X86::RBX : X86::EBX,
14343                                swapInL, cpInH.getValue(1));
14344     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14345                                Regs64bit ? X86::RCX : X86::ECX,
14346                                swapInH, swapInL.getValue(1));
14347     SDValue Ops[] = { swapInH.getValue(0),
14348                       N->getOperand(1),
14349                       swapInH.getValue(1) };
14350     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14351     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14352     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14353                                   X86ISD::LCMPXCHG8_DAG;
14354     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14355     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14356                                         Regs64bit ? X86::RAX : X86::EAX,
14357                                         HalfT, Result.getValue(1));
14358     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14359                                         Regs64bit ? X86::RDX : X86::EDX,
14360                                         HalfT, cpOutL.getValue(2));
14361     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14362     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14363     Results.push_back(cpOutH.getValue(1));
14364     return;
14365   }
14366   case ISD::ATOMIC_LOAD_ADD:
14367   case ISD::ATOMIC_LOAD_AND:
14368   case ISD::ATOMIC_LOAD_NAND:
14369   case ISD::ATOMIC_LOAD_OR:
14370   case ISD::ATOMIC_LOAD_SUB:
14371   case ISD::ATOMIC_LOAD_XOR:
14372   case ISD::ATOMIC_LOAD_MAX:
14373   case ISD::ATOMIC_LOAD_MIN:
14374   case ISD::ATOMIC_LOAD_UMAX:
14375   case ISD::ATOMIC_LOAD_UMIN:
14376   case ISD::ATOMIC_SWAP: {
14377     unsigned Opc;
14378     switch (N->getOpcode()) {
14379     default: llvm_unreachable("Unexpected opcode");
14380     case ISD::ATOMIC_LOAD_ADD:
14381       Opc = X86ISD::ATOMADD64_DAG;
14382       break;
14383     case ISD::ATOMIC_LOAD_AND:
14384       Opc = X86ISD::ATOMAND64_DAG;
14385       break;
14386     case ISD::ATOMIC_LOAD_NAND:
14387       Opc = X86ISD::ATOMNAND64_DAG;
14388       break;
14389     case ISD::ATOMIC_LOAD_OR:
14390       Opc = X86ISD::ATOMOR64_DAG;
14391       break;
14392     case ISD::ATOMIC_LOAD_SUB:
14393       Opc = X86ISD::ATOMSUB64_DAG;
14394       break;
14395     case ISD::ATOMIC_LOAD_XOR:
14396       Opc = X86ISD::ATOMXOR64_DAG;
14397       break;
14398     case ISD::ATOMIC_LOAD_MAX:
14399       Opc = X86ISD::ATOMMAX64_DAG;
14400       break;
14401     case ISD::ATOMIC_LOAD_MIN:
14402       Opc = X86ISD::ATOMMIN64_DAG;
14403       break;
14404     case ISD::ATOMIC_LOAD_UMAX:
14405       Opc = X86ISD::ATOMUMAX64_DAG;
14406       break;
14407     case ISD::ATOMIC_LOAD_UMIN:
14408       Opc = X86ISD::ATOMUMIN64_DAG;
14409       break;
14410     case ISD::ATOMIC_SWAP:
14411       Opc = X86ISD::ATOMSWAP64_DAG;
14412       break;
14413     }
14414     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14415     return;
14416   }
14417   case ISD::ATOMIC_LOAD:
14418     ReplaceATOMIC_LOAD(N, Results, DAG);
14419   }
14420 }
14421
14422 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14423   switch (Opcode) {
14424   default: return nullptr;
14425   case X86ISD::BSF:                return "X86ISD::BSF";
14426   case X86ISD::BSR:                return "X86ISD::BSR";
14427   case X86ISD::SHLD:               return "X86ISD::SHLD";
14428   case X86ISD::SHRD:               return "X86ISD::SHRD";
14429   case X86ISD::FAND:               return "X86ISD::FAND";
14430   case X86ISD::FANDN:              return "X86ISD::FANDN";
14431   case X86ISD::FOR:                return "X86ISD::FOR";
14432   case X86ISD::FXOR:               return "X86ISD::FXOR";
14433   case X86ISD::FSRL:               return "X86ISD::FSRL";
14434   case X86ISD::FILD:               return "X86ISD::FILD";
14435   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14436   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14437   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14438   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14439   case X86ISD::FLD:                return "X86ISD::FLD";
14440   case X86ISD::FST:                return "X86ISD::FST";
14441   case X86ISD::CALL:               return "X86ISD::CALL";
14442   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14443   case X86ISD::BT:                 return "X86ISD::BT";
14444   case X86ISD::CMP:                return "X86ISD::CMP";
14445   case X86ISD::COMI:               return "X86ISD::COMI";
14446   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14447   case X86ISD::CMPM:               return "X86ISD::CMPM";
14448   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14449   case X86ISD::SETCC:              return "X86ISD::SETCC";
14450   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14451   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14452   case X86ISD::CMOV:               return "X86ISD::CMOV";
14453   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14454   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14455   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14456   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14457   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14458   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14459   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14460   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14461   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14462   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14463   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14464   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14465   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14466   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14467   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14468   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14469   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14470   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14471   case X86ISD::HADD:               return "X86ISD::HADD";
14472   case X86ISD::HSUB:               return "X86ISD::HSUB";
14473   case X86ISD::FHADD:              return "X86ISD::FHADD";
14474   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14475   case X86ISD::UMAX:               return "X86ISD::UMAX";
14476   case X86ISD::UMIN:               return "X86ISD::UMIN";
14477   case X86ISD::SMAX:               return "X86ISD::SMAX";
14478   case X86ISD::SMIN:               return "X86ISD::SMIN";
14479   case X86ISD::FMAX:               return "X86ISD::FMAX";
14480   case X86ISD::FMIN:               return "X86ISD::FMIN";
14481   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14482   case X86ISD::FMINC:              return "X86ISD::FMINC";
14483   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14484   case X86ISD::FRCP:               return "X86ISD::FRCP";
14485   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14486   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14487   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14488   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14489   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14490   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14491   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14492   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14493   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14494   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14495   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14496   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14497   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14498   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14499   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14500   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14501   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14502   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14503   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14504   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14505   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14506   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14507   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14508   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14509   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14510   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14511   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14512   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14513   case X86ISD::VSHL:               return "X86ISD::VSHL";
14514   case X86ISD::VSRL:               return "X86ISD::VSRL";
14515   case X86ISD::VSRA:               return "X86ISD::VSRA";
14516   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14517   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14518   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14519   case X86ISD::CMPP:               return "X86ISD::CMPP";
14520   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14521   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14522   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14523   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14524   case X86ISD::ADD:                return "X86ISD::ADD";
14525   case X86ISD::SUB:                return "X86ISD::SUB";
14526   case X86ISD::ADC:                return "X86ISD::ADC";
14527   case X86ISD::SBB:                return "X86ISD::SBB";
14528   case X86ISD::SMUL:               return "X86ISD::SMUL";
14529   case X86ISD::UMUL:               return "X86ISD::UMUL";
14530   case X86ISD::INC:                return "X86ISD::INC";
14531   case X86ISD::DEC:                return "X86ISD::DEC";
14532   case X86ISD::OR:                 return "X86ISD::OR";
14533   case X86ISD::XOR:                return "X86ISD::XOR";
14534   case X86ISD::AND:                return "X86ISD::AND";
14535   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14536   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14537   case X86ISD::PTEST:              return "X86ISD::PTEST";
14538   case X86ISD::TESTP:              return "X86ISD::TESTP";
14539   case X86ISD::TESTM:              return "X86ISD::TESTM";
14540   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14541   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14542   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14543   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14544   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14545   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14546   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14547   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14548   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14549   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14550   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14551   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14552   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14553   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14554   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14555   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14556   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14557   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14558   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14559   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14560   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14561   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14562   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14563   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14564   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14565   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14566   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14567   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14568   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14569   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
14570   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14571   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14572   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14573   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14574   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14575   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14576   case X86ISD::SAHF:               return "X86ISD::SAHF";
14577   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14578   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14579   case X86ISD::FMADD:              return "X86ISD::FMADD";
14580   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14581   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14582   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14583   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14584   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14585   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14586   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14587   case X86ISD::XTEST:              return "X86ISD::XTEST";
14588   }
14589 }
14590
14591 // isLegalAddressingMode - Return true if the addressing mode represented
14592 // by AM is legal for this target, for a load/store of the specified type.
14593 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14594                                               Type *Ty) const {
14595   // X86 supports extremely general addressing modes.
14596   CodeModel::Model M = getTargetMachine().getCodeModel();
14597   Reloc::Model R = getTargetMachine().getRelocationModel();
14598
14599   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14600   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14601     return false;
14602
14603   if (AM.BaseGV) {
14604     unsigned GVFlags =
14605       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14606
14607     // If a reference to this global requires an extra load, we can't fold it.
14608     if (isGlobalStubReference(GVFlags))
14609       return false;
14610
14611     // If BaseGV requires a register for the PIC base, we cannot also have a
14612     // BaseReg specified.
14613     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14614       return false;
14615
14616     // If lower 4G is not available, then we must use rip-relative addressing.
14617     if ((M != CodeModel::Small || R != Reloc::Static) &&
14618         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14619       return false;
14620   }
14621
14622   switch (AM.Scale) {
14623   case 0:
14624   case 1:
14625   case 2:
14626   case 4:
14627   case 8:
14628     // These scales always work.
14629     break;
14630   case 3:
14631   case 5:
14632   case 9:
14633     // These scales are formed with basereg+scalereg.  Only accept if there is
14634     // no basereg yet.
14635     if (AM.HasBaseReg)
14636       return false;
14637     break;
14638   default:  // Other stuff never works.
14639     return false;
14640   }
14641
14642   return true;
14643 }
14644
14645 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14646   unsigned Bits = Ty->getScalarSizeInBits();
14647
14648   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14649   // particularly cheaper than those without.
14650   if (Bits == 8)
14651     return false;
14652
14653   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14654   // variable shifts just as cheap as scalar ones.
14655   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14656     return false;
14657
14658   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14659   // fully general vector.
14660   return true;
14661 }
14662
14663 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14664   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14665     return false;
14666   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14667   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14668   return NumBits1 > NumBits2;
14669 }
14670
14671 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14672   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14673     return false;
14674
14675   if (!isTypeLegal(EVT::getEVT(Ty1)))
14676     return false;
14677
14678   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14679
14680   // Assuming the caller doesn't have a zeroext or signext return parameter,
14681   // truncation all the way down to i1 is valid.
14682   return true;
14683 }
14684
14685 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14686   return isInt<32>(Imm);
14687 }
14688
14689 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14690   // Can also use sub to handle negated immediates.
14691   return isInt<32>(Imm);
14692 }
14693
14694 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14695   if (!VT1.isInteger() || !VT2.isInteger())
14696     return false;
14697   unsigned NumBits1 = VT1.getSizeInBits();
14698   unsigned NumBits2 = VT2.getSizeInBits();
14699   return NumBits1 > NumBits2;
14700 }
14701
14702 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14703   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14704   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14705 }
14706
14707 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14708   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14709   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14710 }
14711
14712 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14713   EVT VT1 = Val.getValueType();
14714   if (isZExtFree(VT1, VT2))
14715     return true;
14716
14717   if (Val.getOpcode() != ISD::LOAD)
14718     return false;
14719
14720   if (!VT1.isSimple() || !VT1.isInteger() ||
14721       !VT2.isSimple() || !VT2.isInteger())
14722     return false;
14723
14724   switch (VT1.getSimpleVT().SimpleTy) {
14725   default: break;
14726   case MVT::i8:
14727   case MVT::i16:
14728   case MVT::i32:
14729     // X86 has 8, 16, and 32-bit zero-extending loads.
14730     return true;
14731   }
14732
14733   return false;
14734 }
14735
14736 bool
14737 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14738   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14739     return false;
14740
14741   VT = VT.getScalarType();
14742
14743   if (!VT.isSimple())
14744     return false;
14745
14746   switch (VT.getSimpleVT().SimpleTy) {
14747   case MVT::f32:
14748   case MVT::f64:
14749     return true;
14750   default:
14751     break;
14752   }
14753
14754   return false;
14755 }
14756
14757 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14758   // i16 instructions are longer (0x66 prefix) and potentially slower.
14759   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14760 }
14761
14762 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14763 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14764 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14765 /// are assumed to be legal.
14766 bool
14767 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14768                                       EVT VT) const {
14769   if (!VT.isSimple())
14770     return false;
14771
14772   MVT SVT = VT.getSimpleVT();
14773
14774   // Very little shuffling can be done for 64-bit vectors right now.
14775   if (VT.getSizeInBits() == 64)
14776     return false;
14777
14778   // FIXME: pshufb, blends, shifts.
14779   return (SVT.getVectorNumElements() == 2 ||
14780           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14781           isMOVLMask(M, SVT) ||
14782           isSHUFPMask(M, SVT) ||
14783           isPSHUFDMask(M, SVT) ||
14784           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14785           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14786           isPALIGNRMask(M, SVT, Subtarget) ||
14787           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14788           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14789           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14790           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14791 }
14792
14793 bool
14794 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14795                                           EVT VT) const {
14796   if (!VT.isSimple())
14797     return false;
14798
14799   MVT SVT = VT.getSimpleVT();
14800   unsigned NumElts = SVT.getVectorNumElements();
14801   // FIXME: This collection of masks seems suspect.
14802   if (NumElts == 2)
14803     return true;
14804   if (NumElts == 4 && SVT.is128BitVector()) {
14805     return (isMOVLMask(Mask, SVT)  ||
14806             isCommutedMOVLMask(Mask, SVT, true) ||
14807             isSHUFPMask(Mask, SVT) ||
14808             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14809   }
14810   return false;
14811 }
14812
14813 //===----------------------------------------------------------------------===//
14814 //                           X86 Scheduler Hooks
14815 //===----------------------------------------------------------------------===//
14816
14817 /// Utility function to emit xbegin specifying the start of an RTM region.
14818 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14819                                      const TargetInstrInfo *TII) {
14820   DebugLoc DL = MI->getDebugLoc();
14821
14822   const BasicBlock *BB = MBB->getBasicBlock();
14823   MachineFunction::iterator I = MBB;
14824   ++I;
14825
14826   // For the v = xbegin(), we generate
14827   //
14828   // thisMBB:
14829   //  xbegin sinkMBB
14830   //
14831   // mainMBB:
14832   //  eax = -1
14833   //
14834   // sinkMBB:
14835   //  v = eax
14836
14837   MachineBasicBlock *thisMBB = MBB;
14838   MachineFunction *MF = MBB->getParent();
14839   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14840   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14841   MF->insert(I, mainMBB);
14842   MF->insert(I, sinkMBB);
14843
14844   // Transfer the remainder of BB and its successor edges to sinkMBB.
14845   sinkMBB->splice(sinkMBB->begin(), MBB,
14846                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14847   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14848
14849   // thisMBB:
14850   //  xbegin sinkMBB
14851   //  # fallthrough to mainMBB
14852   //  # abortion to sinkMBB
14853   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14854   thisMBB->addSuccessor(mainMBB);
14855   thisMBB->addSuccessor(sinkMBB);
14856
14857   // mainMBB:
14858   //  EAX = -1
14859   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14860   mainMBB->addSuccessor(sinkMBB);
14861
14862   // sinkMBB:
14863   // EAX is live into the sinkMBB
14864   sinkMBB->addLiveIn(X86::EAX);
14865   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14866           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14867     .addReg(X86::EAX);
14868
14869   MI->eraseFromParent();
14870   return sinkMBB;
14871 }
14872
14873 // Get CMPXCHG opcode for the specified data type.
14874 static unsigned getCmpXChgOpcode(EVT VT) {
14875   switch (VT.getSimpleVT().SimpleTy) {
14876   case MVT::i8:  return X86::LCMPXCHG8;
14877   case MVT::i16: return X86::LCMPXCHG16;
14878   case MVT::i32: return X86::LCMPXCHG32;
14879   case MVT::i64: return X86::LCMPXCHG64;
14880   default:
14881     break;
14882   }
14883   llvm_unreachable("Invalid operand size!");
14884 }
14885
14886 // Get LOAD opcode for the specified data type.
14887 static unsigned getLoadOpcode(EVT VT) {
14888   switch (VT.getSimpleVT().SimpleTy) {
14889   case MVT::i8:  return X86::MOV8rm;
14890   case MVT::i16: return X86::MOV16rm;
14891   case MVT::i32: return X86::MOV32rm;
14892   case MVT::i64: return X86::MOV64rm;
14893   default:
14894     break;
14895   }
14896   llvm_unreachable("Invalid operand size!");
14897 }
14898
14899 // Get opcode of the non-atomic one from the specified atomic instruction.
14900 static unsigned getNonAtomicOpcode(unsigned Opc) {
14901   switch (Opc) {
14902   case X86::ATOMAND8:  return X86::AND8rr;
14903   case X86::ATOMAND16: return X86::AND16rr;
14904   case X86::ATOMAND32: return X86::AND32rr;
14905   case X86::ATOMAND64: return X86::AND64rr;
14906   case X86::ATOMOR8:   return X86::OR8rr;
14907   case X86::ATOMOR16:  return X86::OR16rr;
14908   case X86::ATOMOR32:  return X86::OR32rr;
14909   case X86::ATOMOR64:  return X86::OR64rr;
14910   case X86::ATOMXOR8:  return X86::XOR8rr;
14911   case X86::ATOMXOR16: return X86::XOR16rr;
14912   case X86::ATOMXOR32: return X86::XOR32rr;
14913   case X86::ATOMXOR64: return X86::XOR64rr;
14914   }
14915   llvm_unreachable("Unhandled atomic-load-op opcode!");
14916 }
14917
14918 // Get opcode of the non-atomic one from the specified atomic instruction with
14919 // extra opcode.
14920 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14921                                                unsigned &ExtraOpc) {
14922   switch (Opc) {
14923   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14924   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14925   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14926   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14927   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14928   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14929   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14930   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14931   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14932   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14933   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14934   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14935   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14936   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14937   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14938   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14939   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14940   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14941   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14942   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14943   }
14944   llvm_unreachable("Unhandled atomic-load-op opcode!");
14945 }
14946
14947 // Get opcode of the non-atomic one from the specified atomic instruction for
14948 // 64-bit data type on 32-bit target.
14949 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14950   switch (Opc) {
14951   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14952   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14953   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14954   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14955   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14956   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14957   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14958   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14959   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14960   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14961   }
14962   llvm_unreachable("Unhandled atomic-load-op opcode!");
14963 }
14964
14965 // Get opcode of the non-atomic one from the specified atomic instruction for
14966 // 64-bit data type on 32-bit target with extra opcode.
14967 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14968                                                    unsigned &HiOpc,
14969                                                    unsigned &ExtraOpc) {
14970   switch (Opc) {
14971   case X86::ATOMNAND6432:
14972     ExtraOpc = X86::NOT32r;
14973     HiOpc = X86::AND32rr;
14974     return X86::AND32rr;
14975   }
14976   llvm_unreachable("Unhandled atomic-load-op opcode!");
14977 }
14978
14979 // Get pseudo CMOV opcode from the specified data type.
14980 static unsigned getPseudoCMOVOpc(EVT VT) {
14981   switch (VT.getSimpleVT().SimpleTy) {
14982   case MVT::i8:  return X86::CMOV_GR8;
14983   case MVT::i16: return X86::CMOV_GR16;
14984   case MVT::i32: return X86::CMOV_GR32;
14985   default:
14986     break;
14987   }
14988   llvm_unreachable("Unknown CMOV opcode!");
14989 }
14990
14991 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
14992 // They will be translated into a spin-loop or compare-exchange loop from
14993 //
14994 //    ...
14995 //    dst = atomic-fetch-op MI.addr, MI.val
14996 //    ...
14997 //
14998 // to
14999 //
15000 //    ...
15001 //    t1 = LOAD MI.addr
15002 // loop:
15003 //    t4 = phi(t1, t3 / loop)
15004 //    t2 = OP MI.val, t4
15005 //    EAX = t4
15006 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15007 //    t3 = EAX
15008 //    JNE loop
15009 // sink:
15010 //    dst = t3
15011 //    ...
15012 MachineBasicBlock *
15013 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15014                                        MachineBasicBlock *MBB) const {
15015   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15016   DebugLoc DL = MI->getDebugLoc();
15017
15018   MachineFunction *MF = MBB->getParent();
15019   MachineRegisterInfo &MRI = MF->getRegInfo();
15020
15021   const BasicBlock *BB = MBB->getBasicBlock();
15022   MachineFunction::iterator I = MBB;
15023   ++I;
15024
15025   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15026          "Unexpected number of operands");
15027
15028   assert(MI->hasOneMemOperand() &&
15029          "Expected atomic-load-op to have one memoperand");
15030
15031   // Memory Reference
15032   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15033   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15034
15035   unsigned DstReg, SrcReg;
15036   unsigned MemOpndSlot;
15037
15038   unsigned CurOp = 0;
15039
15040   DstReg = MI->getOperand(CurOp++).getReg();
15041   MemOpndSlot = CurOp;
15042   CurOp += X86::AddrNumOperands;
15043   SrcReg = MI->getOperand(CurOp++).getReg();
15044
15045   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15046   MVT::SimpleValueType VT = *RC->vt_begin();
15047   unsigned t1 = MRI.createVirtualRegister(RC);
15048   unsigned t2 = MRI.createVirtualRegister(RC);
15049   unsigned t3 = MRI.createVirtualRegister(RC);
15050   unsigned t4 = MRI.createVirtualRegister(RC);
15051   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15052
15053   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15054   unsigned LOADOpc = getLoadOpcode(VT);
15055
15056   // For the atomic load-arith operator, we generate
15057   //
15058   //  thisMBB:
15059   //    t1 = LOAD [MI.addr]
15060   //  mainMBB:
15061   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15062   //    t1 = OP MI.val, EAX
15063   //    EAX = t4
15064   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15065   //    t3 = EAX
15066   //    JNE mainMBB
15067   //  sinkMBB:
15068   //    dst = t3
15069
15070   MachineBasicBlock *thisMBB = MBB;
15071   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15072   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15073   MF->insert(I, mainMBB);
15074   MF->insert(I, sinkMBB);
15075
15076   MachineInstrBuilder MIB;
15077
15078   // Transfer the remainder of BB and its successor edges to sinkMBB.
15079   sinkMBB->splice(sinkMBB->begin(), MBB,
15080                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15081   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15082
15083   // thisMBB:
15084   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15085   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15086     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15087     if (NewMO.isReg())
15088       NewMO.setIsKill(false);
15089     MIB.addOperand(NewMO);
15090   }
15091   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15092     unsigned flags = (*MMOI)->getFlags();
15093     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15094     MachineMemOperand *MMO =
15095       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15096                                (*MMOI)->getSize(),
15097                                (*MMOI)->getBaseAlignment(),
15098                                (*MMOI)->getTBAAInfo(),
15099                                (*MMOI)->getRanges());
15100     MIB.addMemOperand(MMO);
15101   }
15102
15103   thisMBB->addSuccessor(mainMBB);
15104
15105   // mainMBB:
15106   MachineBasicBlock *origMainMBB = mainMBB;
15107
15108   // Add a PHI.
15109   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15110                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15111
15112   unsigned Opc = MI->getOpcode();
15113   switch (Opc) {
15114   default:
15115     llvm_unreachable("Unhandled atomic-load-op opcode!");
15116   case X86::ATOMAND8:
15117   case X86::ATOMAND16:
15118   case X86::ATOMAND32:
15119   case X86::ATOMAND64:
15120   case X86::ATOMOR8:
15121   case X86::ATOMOR16:
15122   case X86::ATOMOR32:
15123   case X86::ATOMOR64:
15124   case X86::ATOMXOR8:
15125   case X86::ATOMXOR16:
15126   case X86::ATOMXOR32:
15127   case X86::ATOMXOR64: {
15128     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15129     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15130       .addReg(t4);
15131     break;
15132   }
15133   case X86::ATOMNAND8:
15134   case X86::ATOMNAND16:
15135   case X86::ATOMNAND32:
15136   case X86::ATOMNAND64: {
15137     unsigned Tmp = MRI.createVirtualRegister(RC);
15138     unsigned NOTOpc;
15139     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15140     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15141       .addReg(t4);
15142     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15143     break;
15144   }
15145   case X86::ATOMMAX8:
15146   case X86::ATOMMAX16:
15147   case X86::ATOMMAX32:
15148   case X86::ATOMMAX64:
15149   case X86::ATOMMIN8:
15150   case X86::ATOMMIN16:
15151   case X86::ATOMMIN32:
15152   case X86::ATOMMIN64:
15153   case X86::ATOMUMAX8:
15154   case X86::ATOMUMAX16:
15155   case X86::ATOMUMAX32:
15156   case X86::ATOMUMAX64:
15157   case X86::ATOMUMIN8:
15158   case X86::ATOMUMIN16:
15159   case X86::ATOMUMIN32:
15160   case X86::ATOMUMIN64: {
15161     unsigned CMPOpc;
15162     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15163
15164     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15165       .addReg(SrcReg)
15166       .addReg(t4);
15167
15168     if (Subtarget->hasCMov()) {
15169       if (VT != MVT::i8) {
15170         // Native support
15171         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15172           .addReg(SrcReg)
15173           .addReg(t4);
15174       } else {
15175         // Promote i8 to i32 to use CMOV32
15176         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15177         const TargetRegisterClass *RC32 =
15178           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15179         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15180         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15181         unsigned Tmp = MRI.createVirtualRegister(RC32);
15182
15183         unsigned Undef = MRI.createVirtualRegister(RC32);
15184         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15185
15186         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15187           .addReg(Undef)
15188           .addReg(SrcReg)
15189           .addImm(X86::sub_8bit);
15190         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15191           .addReg(Undef)
15192           .addReg(t4)
15193           .addImm(X86::sub_8bit);
15194
15195         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15196           .addReg(SrcReg32)
15197           .addReg(AccReg32);
15198
15199         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15200           .addReg(Tmp, 0, X86::sub_8bit);
15201       }
15202     } else {
15203       // Use pseudo select and lower them.
15204       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15205              "Invalid atomic-load-op transformation!");
15206       unsigned SelOpc = getPseudoCMOVOpc(VT);
15207       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15208       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15209       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15210               .addReg(SrcReg).addReg(t4)
15211               .addImm(CC);
15212       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15213       // Replace the original PHI node as mainMBB is changed after CMOV
15214       // lowering.
15215       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15216         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15217       Phi->eraseFromParent();
15218     }
15219     break;
15220   }
15221   }
15222
15223   // Copy PhyReg back from virtual register.
15224   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15225     .addReg(t4);
15226
15227   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15228   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15229     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15230     if (NewMO.isReg())
15231       NewMO.setIsKill(false);
15232     MIB.addOperand(NewMO);
15233   }
15234   MIB.addReg(t2);
15235   MIB.setMemRefs(MMOBegin, MMOEnd);
15236
15237   // Copy PhyReg back to virtual register.
15238   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15239     .addReg(PhyReg);
15240
15241   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15242
15243   mainMBB->addSuccessor(origMainMBB);
15244   mainMBB->addSuccessor(sinkMBB);
15245
15246   // sinkMBB:
15247   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15248           TII->get(TargetOpcode::COPY), DstReg)
15249     .addReg(t3);
15250
15251   MI->eraseFromParent();
15252   return sinkMBB;
15253 }
15254
15255 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15256 // instructions. They will be translated into a spin-loop or compare-exchange
15257 // loop from
15258 //
15259 //    ...
15260 //    dst = atomic-fetch-op MI.addr, MI.val
15261 //    ...
15262 //
15263 // to
15264 //
15265 //    ...
15266 //    t1L = LOAD [MI.addr + 0]
15267 //    t1H = LOAD [MI.addr + 4]
15268 // loop:
15269 //    t4L = phi(t1L, t3L / loop)
15270 //    t4H = phi(t1H, t3H / loop)
15271 //    t2L = OP MI.val.lo, t4L
15272 //    t2H = OP MI.val.hi, t4H
15273 //    EAX = t4L
15274 //    EDX = t4H
15275 //    EBX = t2L
15276 //    ECX = t2H
15277 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15278 //    t3L = EAX
15279 //    t3H = EDX
15280 //    JNE loop
15281 // sink:
15282 //    dstL = t3L
15283 //    dstH = t3H
15284 //    ...
15285 MachineBasicBlock *
15286 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15287                                            MachineBasicBlock *MBB) const {
15288   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15289   DebugLoc DL = MI->getDebugLoc();
15290
15291   MachineFunction *MF = MBB->getParent();
15292   MachineRegisterInfo &MRI = MF->getRegInfo();
15293
15294   const BasicBlock *BB = MBB->getBasicBlock();
15295   MachineFunction::iterator I = MBB;
15296   ++I;
15297
15298   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15299          "Unexpected number of operands");
15300
15301   assert(MI->hasOneMemOperand() &&
15302          "Expected atomic-load-op32 to have one memoperand");
15303
15304   // Memory Reference
15305   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15306   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15307
15308   unsigned DstLoReg, DstHiReg;
15309   unsigned SrcLoReg, SrcHiReg;
15310   unsigned MemOpndSlot;
15311
15312   unsigned CurOp = 0;
15313
15314   DstLoReg = MI->getOperand(CurOp++).getReg();
15315   DstHiReg = MI->getOperand(CurOp++).getReg();
15316   MemOpndSlot = CurOp;
15317   CurOp += X86::AddrNumOperands;
15318   SrcLoReg = MI->getOperand(CurOp++).getReg();
15319   SrcHiReg = MI->getOperand(CurOp++).getReg();
15320
15321   const TargetRegisterClass *RC = &X86::GR32RegClass;
15322   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15323
15324   unsigned t1L = MRI.createVirtualRegister(RC);
15325   unsigned t1H = MRI.createVirtualRegister(RC);
15326   unsigned t2L = MRI.createVirtualRegister(RC);
15327   unsigned t2H = MRI.createVirtualRegister(RC);
15328   unsigned t3L = MRI.createVirtualRegister(RC);
15329   unsigned t3H = MRI.createVirtualRegister(RC);
15330   unsigned t4L = MRI.createVirtualRegister(RC);
15331   unsigned t4H = MRI.createVirtualRegister(RC);
15332
15333   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15334   unsigned LOADOpc = X86::MOV32rm;
15335
15336   // For the atomic load-arith operator, we generate
15337   //
15338   //  thisMBB:
15339   //    t1L = LOAD [MI.addr + 0]
15340   //    t1H = LOAD [MI.addr + 4]
15341   //  mainMBB:
15342   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15343   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15344   //    t2L = OP MI.val.lo, t4L
15345   //    t2H = OP MI.val.hi, t4H
15346   //    EBX = t2L
15347   //    ECX = t2H
15348   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15349   //    t3L = EAX
15350   //    t3H = EDX
15351   //    JNE loop
15352   //  sinkMBB:
15353   //    dstL = t3L
15354   //    dstH = t3H
15355
15356   MachineBasicBlock *thisMBB = MBB;
15357   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15358   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15359   MF->insert(I, mainMBB);
15360   MF->insert(I, sinkMBB);
15361
15362   MachineInstrBuilder MIB;
15363
15364   // Transfer the remainder of BB and its successor edges to sinkMBB.
15365   sinkMBB->splice(sinkMBB->begin(), MBB,
15366                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15367   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15368
15369   // thisMBB:
15370   // Lo
15371   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15372   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15373     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15374     if (NewMO.isReg())
15375       NewMO.setIsKill(false);
15376     MIB.addOperand(NewMO);
15377   }
15378   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15379     unsigned flags = (*MMOI)->getFlags();
15380     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15381     MachineMemOperand *MMO =
15382       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15383                                (*MMOI)->getSize(),
15384                                (*MMOI)->getBaseAlignment(),
15385                                (*MMOI)->getTBAAInfo(),
15386                                (*MMOI)->getRanges());
15387     MIB.addMemOperand(MMO);
15388   };
15389   MachineInstr *LowMI = MIB;
15390
15391   // Hi
15392   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15393   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15394     if (i == X86::AddrDisp) {
15395       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15396     } else {
15397       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15398       if (NewMO.isReg())
15399         NewMO.setIsKill(false);
15400       MIB.addOperand(NewMO);
15401     }
15402   }
15403   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15404
15405   thisMBB->addSuccessor(mainMBB);
15406
15407   // mainMBB:
15408   MachineBasicBlock *origMainMBB = mainMBB;
15409
15410   // Add PHIs.
15411   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15412                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15413   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15414                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15415
15416   unsigned Opc = MI->getOpcode();
15417   switch (Opc) {
15418   default:
15419     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15420   case X86::ATOMAND6432:
15421   case X86::ATOMOR6432:
15422   case X86::ATOMXOR6432:
15423   case X86::ATOMADD6432:
15424   case X86::ATOMSUB6432: {
15425     unsigned HiOpc;
15426     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15427     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15428       .addReg(SrcLoReg);
15429     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15430       .addReg(SrcHiReg);
15431     break;
15432   }
15433   case X86::ATOMNAND6432: {
15434     unsigned HiOpc, NOTOpc;
15435     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15436     unsigned TmpL = MRI.createVirtualRegister(RC);
15437     unsigned TmpH = MRI.createVirtualRegister(RC);
15438     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15439       .addReg(t4L);
15440     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15441       .addReg(t4H);
15442     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15443     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15444     break;
15445   }
15446   case X86::ATOMMAX6432:
15447   case X86::ATOMMIN6432:
15448   case X86::ATOMUMAX6432:
15449   case X86::ATOMUMIN6432: {
15450     unsigned HiOpc;
15451     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15452     unsigned cL = MRI.createVirtualRegister(RC8);
15453     unsigned cH = MRI.createVirtualRegister(RC8);
15454     unsigned cL32 = MRI.createVirtualRegister(RC);
15455     unsigned cH32 = MRI.createVirtualRegister(RC);
15456     unsigned cc = MRI.createVirtualRegister(RC);
15457     // cl := cmp src_lo, lo
15458     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15459       .addReg(SrcLoReg).addReg(t4L);
15460     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15461     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15462     // ch := cmp src_hi, hi
15463     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15464       .addReg(SrcHiReg).addReg(t4H);
15465     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15466     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15467     // cc := if (src_hi == hi) ? cl : ch;
15468     if (Subtarget->hasCMov()) {
15469       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15470         .addReg(cH32).addReg(cL32);
15471     } else {
15472       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15473               .addReg(cH32).addReg(cL32)
15474               .addImm(X86::COND_E);
15475       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15476     }
15477     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15478     if (Subtarget->hasCMov()) {
15479       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15480         .addReg(SrcLoReg).addReg(t4L);
15481       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15482         .addReg(SrcHiReg).addReg(t4H);
15483     } else {
15484       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15485               .addReg(SrcLoReg).addReg(t4L)
15486               .addImm(X86::COND_NE);
15487       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15488       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15489       // 2nd CMOV lowering.
15490       mainMBB->addLiveIn(X86::EFLAGS);
15491       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15492               .addReg(SrcHiReg).addReg(t4H)
15493               .addImm(X86::COND_NE);
15494       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15495       // Replace the original PHI node as mainMBB is changed after CMOV
15496       // lowering.
15497       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15498         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15499       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15500         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15501       PhiL->eraseFromParent();
15502       PhiH->eraseFromParent();
15503     }
15504     break;
15505   }
15506   case X86::ATOMSWAP6432: {
15507     unsigned HiOpc;
15508     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15509     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15510     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15511     break;
15512   }
15513   }
15514
15515   // Copy EDX:EAX back from HiReg:LoReg
15516   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15517   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15518   // Copy ECX:EBX from t1H:t1L
15519   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15520   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15521
15522   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15523   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15524     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15525     if (NewMO.isReg())
15526       NewMO.setIsKill(false);
15527     MIB.addOperand(NewMO);
15528   }
15529   MIB.setMemRefs(MMOBegin, MMOEnd);
15530
15531   // Copy EDX:EAX back to t3H:t3L
15532   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15533   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15534
15535   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15536
15537   mainMBB->addSuccessor(origMainMBB);
15538   mainMBB->addSuccessor(sinkMBB);
15539
15540   // sinkMBB:
15541   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15542           TII->get(TargetOpcode::COPY), DstLoReg)
15543     .addReg(t3L);
15544   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15545           TII->get(TargetOpcode::COPY), DstHiReg)
15546     .addReg(t3H);
15547
15548   MI->eraseFromParent();
15549   return sinkMBB;
15550 }
15551
15552 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15553 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15554 // in the .td file.
15555 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15556                                        const TargetInstrInfo *TII) {
15557   unsigned Opc;
15558   switch (MI->getOpcode()) {
15559   default: llvm_unreachable("illegal opcode!");
15560   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15561   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15562   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15563   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15564   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15565   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15566   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15567   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15568   }
15569
15570   DebugLoc dl = MI->getDebugLoc();
15571   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15572
15573   unsigned NumArgs = MI->getNumOperands();
15574   for (unsigned i = 1; i < NumArgs; ++i) {
15575     MachineOperand &Op = MI->getOperand(i);
15576     if (!(Op.isReg() && Op.isImplicit()))
15577       MIB.addOperand(Op);
15578   }
15579   if (MI->hasOneMemOperand())
15580     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15581
15582   BuildMI(*BB, MI, dl,
15583     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15584     .addReg(X86::XMM0);
15585
15586   MI->eraseFromParent();
15587   return BB;
15588 }
15589
15590 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15591 // defs in an instruction pattern
15592 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15593                                        const TargetInstrInfo *TII) {
15594   unsigned Opc;
15595   switch (MI->getOpcode()) {
15596   default: llvm_unreachable("illegal opcode!");
15597   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15598   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15599   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15600   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15601   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15602   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15603   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15604   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15605   }
15606
15607   DebugLoc dl = MI->getDebugLoc();
15608   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15609
15610   unsigned NumArgs = MI->getNumOperands(); // remove the results
15611   for (unsigned i = 1; i < NumArgs; ++i) {
15612     MachineOperand &Op = MI->getOperand(i);
15613     if (!(Op.isReg() && Op.isImplicit()))
15614       MIB.addOperand(Op);
15615   }
15616   if (MI->hasOneMemOperand())
15617     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15618
15619   BuildMI(*BB, MI, dl,
15620     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15621     .addReg(X86::ECX);
15622
15623   MI->eraseFromParent();
15624   return BB;
15625 }
15626
15627 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15628                                        const TargetInstrInfo *TII,
15629                                        const X86Subtarget* Subtarget) {
15630   DebugLoc dl = MI->getDebugLoc();
15631
15632   // Address into RAX/EAX, other two args into ECX, EDX.
15633   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15634   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15635   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15636   for (int i = 0; i < X86::AddrNumOperands; ++i)
15637     MIB.addOperand(MI->getOperand(i));
15638
15639   unsigned ValOps = X86::AddrNumOperands;
15640   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15641     .addReg(MI->getOperand(ValOps).getReg());
15642   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15643     .addReg(MI->getOperand(ValOps+1).getReg());
15644
15645   // The instruction doesn't actually take any operands though.
15646   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15647
15648   MI->eraseFromParent(); // The pseudo is gone now.
15649   return BB;
15650 }
15651
15652 MachineBasicBlock *
15653 X86TargetLowering::EmitVAARG64WithCustomInserter(
15654                    MachineInstr *MI,
15655                    MachineBasicBlock *MBB) const {
15656   // Emit va_arg instruction on X86-64.
15657
15658   // Operands to this pseudo-instruction:
15659   // 0  ) Output        : destination address (reg)
15660   // 1-5) Input         : va_list address (addr, i64mem)
15661   // 6  ) ArgSize       : Size (in bytes) of vararg type
15662   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15663   // 8  ) Align         : Alignment of type
15664   // 9  ) EFLAGS (implicit-def)
15665
15666   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15667   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15668
15669   unsigned DestReg = MI->getOperand(0).getReg();
15670   MachineOperand &Base = MI->getOperand(1);
15671   MachineOperand &Scale = MI->getOperand(2);
15672   MachineOperand &Index = MI->getOperand(3);
15673   MachineOperand &Disp = MI->getOperand(4);
15674   MachineOperand &Segment = MI->getOperand(5);
15675   unsigned ArgSize = MI->getOperand(6).getImm();
15676   unsigned ArgMode = MI->getOperand(7).getImm();
15677   unsigned Align = MI->getOperand(8).getImm();
15678
15679   // Memory Reference
15680   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15681   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15682   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15683
15684   // Machine Information
15685   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15686   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15687   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15688   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15689   DebugLoc DL = MI->getDebugLoc();
15690
15691   // struct va_list {
15692   //   i32   gp_offset
15693   //   i32   fp_offset
15694   //   i64   overflow_area (address)
15695   //   i64   reg_save_area (address)
15696   // }
15697   // sizeof(va_list) = 24
15698   // alignment(va_list) = 8
15699
15700   unsigned TotalNumIntRegs = 6;
15701   unsigned TotalNumXMMRegs = 8;
15702   bool UseGPOffset = (ArgMode == 1);
15703   bool UseFPOffset = (ArgMode == 2);
15704   unsigned MaxOffset = TotalNumIntRegs * 8 +
15705                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15706
15707   /* Align ArgSize to a multiple of 8 */
15708   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15709   bool NeedsAlign = (Align > 8);
15710
15711   MachineBasicBlock *thisMBB = MBB;
15712   MachineBasicBlock *overflowMBB;
15713   MachineBasicBlock *offsetMBB;
15714   MachineBasicBlock *endMBB;
15715
15716   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15717   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15718   unsigned OffsetReg = 0;
15719
15720   if (!UseGPOffset && !UseFPOffset) {
15721     // If we only pull from the overflow region, we don't create a branch.
15722     // We don't need to alter control flow.
15723     OffsetDestReg = 0; // unused
15724     OverflowDestReg = DestReg;
15725
15726     offsetMBB = nullptr;
15727     overflowMBB = thisMBB;
15728     endMBB = thisMBB;
15729   } else {
15730     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15731     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15732     // If not, pull from overflow_area. (branch to overflowMBB)
15733     //
15734     //       thisMBB
15735     //         |     .
15736     //         |        .
15737     //     offsetMBB   overflowMBB
15738     //         |        .
15739     //         |     .
15740     //        endMBB
15741
15742     // Registers for the PHI in endMBB
15743     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15744     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15745
15746     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15747     MachineFunction *MF = MBB->getParent();
15748     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15749     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15750     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15751
15752     MachineFunction::iterator MBBIter = MBB;
15753     ++MBBIter;
15754
15755     // Insert the new basic blocks
15756     MF->insert(MBBIter, offsetMBB);
15757     MF->insert(MBBIter, overflowMBB);
15758     MF->insert(MBBIter, endMBB);
15759
15760     // Transfer the remainder of MBB and its successor edges to endMBB.
15761     endMBB->splice(endMBB->begin(), thisMBB,
15762                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15763     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15764
15765     // Make offsetMBB and overflowMBB successors of thisMBB
15766     thisMBB->addSuccessor(offsetMBB);
15767     thisMBB->addSuccessor(overflowMBB);
15768
15769     // endMBB is a successor of both offsetMBB and overflowMBB
15770     offsetMBB->addSuccessor(endMBB);
15771     overflowMBB->addSuccessor(endMBB);
15772
15773     // Load the offset value into a register
15774     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15775     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15776       .addOperand(Base)
15777       .addOperand(Scale)
15778       .addOperand(Index)
15779       .addDisp(Disp, UseFPOffset ? 4 : 0)
15780       .addOperand(Segment)
15781       .setMemRefs(MMOBegin, MMOEnd);
15782
15783     // Check if there is enough room left to pull this argument.
15784     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15785       .addReg(OffsetReg)
15786       .addImm(MaxOffset + 8 - ArgSizeA8);
15787
15788     // Branch to "overflowMBB" if offset >= max
15789     // Fall through to "offsetMBB" otherwise
15790     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15791       .addMBB(overflowMBB);
15792   }
15793
15794   // In offsetMBB, emit code to use the reg_save_area.
15795   if (offsetMBB) {
15796     assert(OffsetReg != 0);
15797
15798     // Read the reg_save_area address.
15799     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15800     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15801       .addOperand(Base)
15802       .addOperand(Scale)
15803       .addOperand(Index)
15804       .addDisp(Disp, 16)
15805       .addOperand(Segment)
15806       .setMemRefs(MMOBegin, MMOEnd);
15807
15808     // Zero-extend the offset
15809     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15810       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15811         .addImm(0)
15812         .addReg(OffsetReg)
15813         .addImm(X86::sub_32bit);
15814
15815     // Add the offset to the reg_save_area to get the final address.
15816     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15817       .addReg(OffsetReg64)
15818       .addReg(RegSaveReg);
15819
15820     // Compute the offset for the next argument
15821     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15822     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15823       .addReg(OffsetReg)
15824       .addImm(UseFPOffset ? 16 : 8);
15825
15826     // Store it back into the va_list.
15827     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15828       .addOperand(Base)
15829       .addOperand(Scale)
15830       .addOperand(Index)
15831       .addDisp(Disp, UseFPOffset ? 4 : 0)
15832       .addOperand(Segment)
15833       .addReg(NextOffsetReg)
15834       .setMemRefs(MMOBegin, MMOEnd);
15835
15836     // Jump to endMBB
15837     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15838       .addMBB(endMBB);
15839   }
15840
15841   //
15842   // Emit code to use overflow area
15843   //
15844
15845   // Load the overflow_area address into a register.
15846   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15847   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15848     .addOperand(Base)
15849     .addOperand(Scale)
15850     .addOperand(Index)
15851     .addDisp(Disp, 8)
15852     .addOperand(Segment)
15853     .setMemRefs(MMOBegin, MMOEnd);
15854
15855   // If we need to align it, do so. Otherwise, just copy the address
15856   // to OverflowDestReg.
15857   if (NeedsAlign) {
15858     // Align the overflow address
15859     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15860     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15861
15862     // aligned_addr = (addr + (align-1)) & ~(align-1)
15863     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15864       .addReg(OverflowAddrReg)
15865       .addImm(Align-1);
15866
15867     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15868       .addReg(TmpReg)
15869       .addImm(~(uint64_t)(Align-1));
15870   } else {
15871     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15872       .addReg(OverflowAddrReg);
15873   }
15874
15875   // Compute the next overflow address after this argument.
15876   // (the overflow address should be kept 8-byte aligned)
15877   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15878   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15879     .addReg(OverflowDestReg)
15880     .addImm(ArgSizeA8);
15881
15882   // Store the new overflow address.
15883   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15884     .addOperand(Base)
15885     .addOperand(Scale)
15886     .addOperand(Index)
15887     .addDisp(Disp, 8)
15888     .addOperand(Segment)
15889     .addReg(NextAddrReg)
15890     .setMemRefs(MMOBegin, MMOEnd);
15891
15892   // If we branched, emit the PHI to the front of endMBB.
15893   if (offsetMBB) {
15894     BuildMI(*endMBB, endMBB->begin(), DL,
15895             TII->get(X86::PHI), DestReg)
15896       .addReg(OffsetDestReg).addMBB(offsetMBB)
15897       .addReg(OverflowDestReg).addMBB(overflowMBB);
15898   }
15899
15900   // Erase the pseudo instruction
15901   MI->eraseFromParent();
15902
15903   return endMBB;
15904 }
15905
15906 MachineBasicBlock *
15907 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15908                                                  MachineInstr *MI,
15909                                                  MachineBasicBlock *MBB) const {
15910   // Emit code to save XMM registers to the stack. The ABI says that the
15911   // number of registers to save is given in %al, so it's theoretically
15912   // possible to do an indirect jump trick to avoid saving all of them,
15913   // however this code takes a simpler approach and just executes all
15914   // of the stores if %al is non-zero. It's less code, and it's probably
15915   // easier on the hardware branch predictor, and stores aren't all that
15916   // expensive anyway.
15917
15918   // Create the new basic blocks. One block contains all the XMM stores,
15919   // and one block is the final destination regardless of whether any
15920   // stores were performed.
15921   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15922   MachineFunction *F = MBB->getParent();
15923   MachineFunction::iterator MBBIter = MBB;
15924   ++MBBIter;
15925   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15926   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15927   F->insert(MBBIter, XMMSaveMBB);
15928   F->insert(MBBIter, EndMBB);
15929
15930   // Transfer the remainder of MBB and its successor edges to EndMBB.
15931   EndMBB->splice(EndMBB->begin(), MBB,
15932                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15933   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15934
15935   // The original block will now fall through to the XMM save block.
15936   MBB->addSuccessor(XMMSaveMBB);
15937   // The XMMSaveMBB will fall through to the end block.
15938   XMMSaveMBB->addSuccessor(EndMBB);
15939
15940   // Now add the instructions.
15941   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15942   DebugLoc DL = MI->getDebugLoc();
15943
15944   unsigned CountReg = MI->getOperand(0).getReg();
15945   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15946   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15947
15948   if (!Subtarget->isTargetWin64()) {
15949     // If %al is 0, branch around the XMM save block.
15950     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15951     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15952     MBB->addSuccessor(EndMBB);
15953   }
15954
15955   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15956   // that was just emitted, but clearly shouldn't be "saved".
15957   assert((MI->getNumOperands() <= 3 ||
15958           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15959           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15960          && "Expected last argument to be EFLAGS");
15961   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15962   // In the XMM save block, save all the XMM argument registers.
15963   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15964     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15965     MachineMemOperand *MMO =
15966       F->getMachineMemOperand(
15967           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15968         MachineMemOperand::MOStore,
15969         /*Size=*/16, /*Align=*/16);
15970     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15971       .addFrameIndex(RegSaveFrameIndex)
15972       .addImm(/*Scale=*/1)
15973       .addReg(/*IndexReg=*/0)
15974       .addImm(/*Disp=*/Offset)
15975       .addReg(/*Segment=*/0)
15976       .addReg(MI->getOperand(i).getReg())
15977       .addMemOperand(MMO);
15978   }
15979
15980   MI->eraseFromParent();   // The pseudo instruction is gone now.
15981
15982   return EndMBB;
15983 }
15984
15985 // The EFLAGS operand of SelectItr might be missing a kill marker
15986 // because there were multiple uses of EFLAGS, and ISel didn't know
15987 // which to mark. Figure out whether SelectItr should have had a
15988 // kill marker, and set it if it should. Returns the correct kill
15989 // marker value.
15990 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
15991                                      MachineBasicBlock* BB,
15992                                      const TargetRegisterInfo* TRI) {
15993   // Scan forward through BB for a use/def of EFLAGS.
15994   MachineBasicBlock::iterator miI(std::next(SelectItr));
15995   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
15996     const MachineInstr& mi = *miI;
15997     if (mi.readsRegister(X86::EFLAGS))
15998       return false;
15999     if (mi.definesRegister(X86::EFLAGS))
16000       break; // Should have kill-flag - update below.
16001   }
16002
16003   // If we hit the end of the block, check whether EFLAGS is live into a
16004   // successor.
16005   if (miI == BB->end()) {
16006     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16007                                           sEnd = BB->succ_end();
16008          sItr != sEnd; ++sItr) {
16009       MachineBasicBlock* succ = *sItr;
16010       if (succ->isLiveIn(X86::EFLAGS))
16011         return false;
16012     }
16013   }
16014
16015   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16016   // out. SelectMI should have a kill flag on EFLAGS.
16017   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16018   return true;
16019 }
16020
16021 MachineBasicBlock *
16022 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16023                                      MachineBasicBlock *BB) const {
16024   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16025   DebugLoc DL = MI->getDebugLoc();
16026
16027   // To "insert" a SELECT_CC instruction, we actually have to insert the
16028   // diamond control-flow pattern.  The incoming instruction knows the
16029   // destination vreg to set, the condition code register to branch on, the
16030   // true/false values to select between, and a branch opcode to use.
16031   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16032   MachineFunction::iterator It = BB;
16033   ++It;
16034
16035   //  thisMBB:
16036   //  ...
16037   //   TrueVal = ...
16038   //   cmpTY ccX, r1, r2
16039   //   bCC copy1MBB
16040   //   fallthrough --> copy0MBB
16041   MachineBasicBlock *thisMBB = BB;
16042   MachineFunction *F = BB->getParent();
16043   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16044   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16045   F->insert(It, copy0MBB);
16046   F->insert(It, sinkMBB);
16047
16048   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16049   // live into the sink and copy blocks.
16050   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16051   if (!MI->killsRegister(X86::EFLAGS) &&
16052       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16053     copy0MBB->addLiveIn(X86::EFLAGS);
16054     sinkMBB->addLiveIn(X86::EFLAGS);
16055   }
16056
16057   // Transfer the remainder of BB and its successor edges to sinkMBB.
16058   sinkMBB->splice(sinkMBB->begin(), BB,
16059                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16060   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16061
16062   // Add the true and fallthrough blocks as its successors.
16063   BB->addSuccessor(copy0MBB);
16064   BB->addSuccessor(sinkMBB);
16065
16066   // Create the conditional branch instruction.
16067   unsigned Opc =
16068     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16069   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16070
16071   //  copy0MBB:
16072   //   %FalseValue = ...
16073   //   # fallthrough to sinkMBB
16074   copy0MBB->addSuccessor(sinkMBB);
16075
16076   //  sinkMBB:
16077   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16078   //  ...
16079   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16080           TII->get(X86::PHI), MI->getOperand(0).getReg())
16081     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16082     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16083
16084   MI->eraseFromParent();   // The pseudo instruction is gone now.
16085   return sinkMBB;
16086 }
16087
16088 MachineBasicBlock *
16089 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16090                                         bool Is64Bit) const {
16091   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16092   DebugLoc DL = MI->getDebugLoc();
16093   MachineFunction *MF = BB->getParent();
16094   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16095
16096   assert(MF->shouldSplitStack());
16097
16098   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16099   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16100
16101   // BB:
16102   //  ... [Till the alloca]
16103   // If stacklet is not large enough, jump to mallocMBB
16104   //
16105   // bumpMBB:
16106   //  Allocate by subtracting from RSP
16107   //  Jump to continueMBB
16108   //
16109   // mallocMBB:
16110   //  Allocate by call to runtime
16111   //
16112   // continueMBB:
16113   //  ...
16114   //  [rest of original BB]
16115   //
16116
16117   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16118   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16119   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16120
16121   MachineRegisterInfo &MRI = MF->getRegInfo();
16122   const TargetRegisterClass *AddrRegClass =
16123     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16124
16125   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16126     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16127     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16128     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16129     sizeVReg = MI->getOperand(1).getReg(),
16130     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16131
16132   MachineFunction::iterator MBBIter = BB;
16133   ++MBBIter;
16134
16135   MF->insert(MBBIter, bumpMBB);
16136   MF->insert(MBBIter, mallocMBB);
16137   MF->insert(MBBIter, continueMBB);
16138
16139   continueMBB->splice(continueMBB->begin(), BB,
16140                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16141   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16142
16143   // Add code to the main basic block to check if the stack limit has been hit,
16144   // and if so, jump to mallocMBB otherwise to bumpMBB.
16145   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16146   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16147     .addReg(tmpSPVReg).addReg(sizeVReg);
16148   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16149     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16150     .addReg(SPLimitVReg);
16151   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16152
16153   // bumpMBB simply decreases the stack pointer, since we know the current
16154   // stacklet has enough space.
16155   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16156     .addReg(SPLimitVReg);
16157   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16158     .addReg(SPLimitVReg);
16159   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16160
16161   // Calls into a routine in libgcc to allocate more space from the heap.
16162   const uint32_t *RegMask =
16163     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16164   if (Is64Bit) {
16165     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16166       .addReg(sizeVReg);
16167     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16168       .addExternalSymbol("__morestack_allocate_stack_space")
16169       .addRegMask(RegMask)
16170       .addReg(X86::RDI, RegState::Implicit)
16171       .addReg(X86::RAX, RegState::ImplicitDefine);
16172   } else {
16173     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16174       .addImm(12);
16175     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16176     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16177       .addExternalSymbol("__morestack_allocate_stack_space")
16178       .addRegMask(RegMask)
16179       .addReg(X86::EAX, RegState::ImplicitDefine);
16180   }
16181
16182   if (!Is64Bit)
16183     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16184       .addImm(16);
16185
16186   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16187     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16188   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16189
16190   // Set up the CFG correctly.
16191   BB->addSuccessor(bumpMBB);
16192   BB->addSuccessor(mallocMBB);
16193   mallocMBB->addSuccessor(continueMBB);
16194   bumpMBB->addSuccessor(continueMBB);
16195
16196   // Take care of the PHI nodes.
16197   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16198           MI->getOperand(0).getReg())
16199     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16200     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16201
16202   // Delete the original pseudo instruction.
16203   MI->eraseFromParent();
16204
16205   // And we're done.
16206   return continueMBB;
16207 }
16208
16209 MachineBasicBlock *
16210 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16211                                           MachineBasicBlock *BB) const {
16212   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16213   DebugLoc DL = MI->getDebugLoc();
16214
16215   assert(!Subtarget->isTargetMacho());
16216
16217   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16218   // non-trivial part is impdef of ESP.
16219
16220   if (Subtarget->isTargetWin64()) {
16221     if (Subtarget->isTargetCygMing()) {
16222       // ___chkstk(Mingw64):
16223       // Clobbers R10, R11, RAX and EFLAGS.
16224       // Updates RSP.
16225       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16226         .addExternalSymbol("___chkstk")
16227         .addReg(X86::RAX, RegState::Implicit)
16228         .addReg(X86::RSP, RegState::Implicit)
16229         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16230         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16231         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16232     } else {
16233       // __chkstk(MSVCRT): does not update stack pointer.
16234       // Clobbers R10, R11 and EFLAGS.
16235       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16236         .addExternalSymbol("__chkstk")
16237         .addReg(X86::RAX, RegState::Implicit)
16238         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16239       // RAX has the offset to be subtracted from RSP.
16240       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16241         .addReg(X86::RSP)
16242         .addReg(X86::RAX);
16243     }
16244   } else {
16245     const char *StackProbeSymbol =
16246       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16247
16248     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16249       .addExternalSymbol(StackProbeSymbol)
16250       .addReg(X86::EAX, RegState::Implicit)
16251       .addReg(X86::ESP, RegState::Implicit)
16252       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16253       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16254       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16255   }
16256
16257   MI->eraseFromParent();   // The pseudo instruction is gone now.
16258   return BB;
16259 }
16260
16261 MachineBasicBlock *
16262 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16263                                       MachineBasicBlock *BB) const {
16264   // This is pretty easy.  We're taking the value that we received from
16265   // our load from the relocation, sticking it in either RDI (x86-64)
16266   // or EAX and doing an indirect call.  The return value will then
16267   // be in the normal return register.
16268   const X86InstrInfo *TII
16269     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16270   DebugLoc DL = MI->getDebugLoc();
16271   MachineFunction *F = BB->getParent();
16272
16273   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16274   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16275
16276   // Get a register mask for the lowered call.
16277   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16278   // proper register mask.
16279   const uint32_t *RegMask =
16280     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16281   if (Subtarget->is64Bit()) {
16282     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16283                                       TII->get(X86::MOV64rm), X86::RDI)
16284     .addReg(X86::RIP)
16285     .addImm(0).addReg(0)
16286     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16287                       MI->getOperand(3).getTargetFlags())
16288     .addReg(0);
16289     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16290     addDirectMem(MIB, X86::RDI);
16291     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16292   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16293     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16294                                       TII->get(X86::MOV32rm), X86::EAX)
16295     .addReg(0)
16296     .addImm(0).addReg(0)
16297     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16298                       MI->getOperand(3).getTargetFlags())
16299     .addReg(0);
16300     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16301     addDirectMem(MIB, X86::EAX);
16302     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16303   } else {
16304     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16305                                       TII->get(X86::MOV32rm), X86::EAX)
16306     .addReg(TII->getGlobalBaseReg(F))
16307     .addImm(0).addReg(0)
16308     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16309                       MI->getOperand(3).getTargetFlags())
16310     .addReg(0);
16311     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16312     addDirectMem(MIB, X86::EAX);
16313     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16314   }
16315
16316   MI->eraseFromParent(); // The pseudo instruction is gone now.
16317   return BB;
16318 }
16319
16320 MachineBasicBlock *
16321 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16322                                     MachineBasicBlock *MBB) const {
16323   DebugLoc DL = MI->getDebugLoc();
16324   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16325
16326   MachineFunction *MF = MBB->getParent();
16327   MachineRegisterInfo &MRI = MF->getRegInfo();
16328
16329   const BasicBlock *BB = MBB->getBasicBlock();
16330   MachineFunction::iterator I = MBB;
16331   ++I;
16332
16333   // Memory Reference
16334   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16335   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16336
16337   unsigned DstReg;
16338   unsigned MemOpndSlot = 0;
16339
16340   unsigned CurOp = 0;
16341
16342   DstReg = MI->getOperand(CurOp++).getReg();
16343   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16344   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16345   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16346   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16347
16348   MemOpndSlot = CurOp;
16349
16350   MVT PVT = getPointerTy();
16351   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16352          "Invalid Pointer Size!");
16353
16354   // For v = setjmp(buf), we generate
16355   //
16356   // thisMBB:
16357   //  buf[LabelOffset] = restoreMBB
16358   //  SjLjSetup restoreMBB
16359   //
16360   // mainMBB:
16361   //  v_main = 0
16362   //
16363   // sinkMBB:
16364   //  v = phi(main, restore)
16365   //
16366   // restoreMBB:
16367   //  v_restore = 1
16368
16369   MachineBasicBlock *thisMBB = MBB;
16370   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16371   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16372   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16373   MF->insert(I, mainMBB);
16374   MF->insert(I, sinkMBB);
16375   MF->push_back(restoreMBB);
16376
16377   MachineInstrBuilder MIB;
16378
16379   // Transfer the remainder of BB and its successor edges to sinkMBB.
16380   sinkMBB->splice(sinkMBB->begin(), MBB,
16381                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16382   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16383
16384   // thisMBB:
16385   unsigned PtrStoreOpc = 0;
16386   unsigned LabelReg = 0;
16387   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16388   Reloc::Model RM = getTargetMachine().getRelocationModel();
16389   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16390                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16391
16392   // Prepare IP either in reg or imm.
16393   if (!UseImmLabel) {
16394     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16395     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16396     LabelReg = MRI.createVirtualRegister(PtrRC);
16397     if (Subtarget->is64Bit()) {
16398       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16399               .addReg(X86::RIP)
16400               .addImm(0)
16401               .addReg(0)
16402               .addMBB(restoreMBB)
16403               .addReg(0);
16404     } else {
16405       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16406       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16407               .addReg(XII->getGlobalBaseReg(MF))
16408               .addImm(0)
16409               .addReg(0)
16410               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16411               .addReg(0);
16412     }
16413   } else
16414     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16415   // Store IP
16416   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16417   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16418     if (i == X86::AddrDisp)
16419       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16420     else
16421       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16422   }
16423   if (!UseImmLabel)
16424     MIB.addReg(LabelReg);
16425   else
16426     MIB.addMBB(restoreMBB);
16427   MIB.setMemRefs(MMOBegin, MMOEnd);
16428   // Setup
16429   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16430           .addMBB(restoreMBB);
16431
16432   const X86RegisterInfo *RegInfo =
16433     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16434   MIB.addRegMask(RegInfo->getNoPreservedMask());
16435   thisMBB->addSuccessor(mainMBB);
16436   thisMBB->addSuccessor(restoreMBB);
16437
16438   // mainMBB:
16439   //  EAX = 0
16440   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16441   mainMBB->addSuccessor(sinkMBB);
16442
16443   // sinkMBB:
16444   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16445           TII->get(X86::PHI), DstReg)
16446     .addReg(mainDstReg).addMBB(mainMBB)
16447     .addReg(restoreDstReg).addMBB(restoreMBB);
16448
16449   // restoreMBB:
16450   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16451   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16452   restoreMBB->addSuccessor(sinkMBB);
16453
16454   MI->eraseFromParent();
16455   return sinkMBB;
16456 }
16457
16458 MachineBasicBlock *
16459 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16460                                      MachineBasicBlock *MBB) const {
16461   DebugLoc DL = MI->getDebugLoc();
16462   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16463
16464   MachineFunction *MF = MBB->getParent();
16465   MachineRegisterInfo &MRI = MF->getRegInfo();
16466
16467   // Memory Reference
16468   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16469   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16470
16471   MVT PVT = getPointerTy();
16472   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16473          "Invalid Pointer Size!");
16474
16475   const TargetRegisterClass *RC =
16476     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16477   unsigned Tmp = MRI.createVirtualRegister(RC);
16478   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16479   const X86RegisterInfo *RegInfo =
16480     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16481   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16482   unsigned SP = RegInfo->getStackRegister();
16483
16484   MachineInstrBuilder MIB;
16485
16486   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16487   const int64_t SPOffset = 2 * PVT.getStoreSize();
16488
16489   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16490   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16491
16492   // Reload FP
16493   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16494   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16495     MIB.addOperand(MI->getOperand(i));
16496   MIB.setMemRefs(MMOBegin, MMOEnd);
16497   // Reload IP
16498   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16499   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16500     if (i == X86::AddrDisp)
16501       MIB.addDisp(MI->getOperand(i), LabelOffset);
16502     else
16503       MIB.addOperand(MI->getOperand(i));
16504   }
16505   MIB.setMemRefs(MMOBegin, MMOEnd);
16506   // Reload SP
16507   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16508   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16509     if (i == X86::AddrDisp)
16510       MIB.addDisp(MI->getOperand(i), SPOffset);
16511     else
16512       MIB.addOperand(MI->getOperand(i));
16513   }
16514   MIB.setMemRefs(MMOBegin, MMOEnd);
16515   // Jump
16516   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16517
16518   MI->eraseFromParent();
16519   return MBB;
16520 }
16521
16522 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16523 // accumulator loops. Writing back to the accumulator allows the coalescer
16524 // to remove extra copies in the loop.   
16525 MachineBasicBlock *
16526 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16527                                  MachineBasicBlock *MBB) const {
16528   MachineOperand &AddendOp = MI->getOperand(3);
16529
16530   // Bail out early if the addend isn't a register - we can't switch these.
16531   if (!AddendOp.isReg())
16532     return MBB;
16533
16534   MachineFunction &MF = *MBB->getParent();
16535   MachineRegisterInfo &MRI = MF.getRegInfo();
16536
16537   // Check whether the addend is defined by a PHI:
16538   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16539   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16540   if (!AddendDef.isPHI())
16541     return MBB;
16542
16543   // Look for the following pattern:
16544   // loop:
16545   //   %addend = phi [%entry, 0], [%loop, %result]
16546   //   ...
16547   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16548
16549   // Replace with:
16550   //   loop:
16551   //   %addend = phi [%entry, 0], [%loop, %result]
16552   //   ...
16553   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16554
16555   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16556     assert(AddendDef.getOperand(i).isReg());
16557     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16558     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16559     if (&PHISrcInst == MI) {
16560       // Found a matching instruction.
16561       unsigned NewFMAOpc = 0;
16562       switch (MI->getOpcode()) {
16563         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16564         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16565         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16566         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16567         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16568         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16569         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16570         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16571         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16572         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16573         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16574         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16575         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16576         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16577         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16578         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16579         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16580         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16581         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16582         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16583         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16584         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16585         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16586         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16587         default: llvm_unreachable("Unrecognized FMA variant.");
16588       }
16589
16590       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16591       MachineInstrBuilder MIB =
16592         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16593         .addOperand(MI->getOperand(0))
16594         .addOperand(MI->getOperand(3))
16595         .addOperand(MI->getOperand(2))
16596         .addOperand(MI->getOperand(1));
16597       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16598       MI->eraseFromParent();
16599     }
16600   }
16601
16602   return MBB;
16603 }
16604
16605 MachineBasicBlock *
16606 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16607                                                MachineBasicBlock *BB) const {
16608   switch (MI->getOpcode()) {
16609   default: llvm_unreachable("Unexpected instr type to insert");
16610   case X86::TAILJMPd64:
16611   case X86::TAILJMPr64:
16612   case X86::TAILJMPm64:
16613     llvm_unreachable("TAILJMP64 would not be touched here.");
16614   case X86::TCRETURNdi64:
16615   case X86::TCRETURNri64:
16616   case X86::TCRETURNmi64:
16617     return BB;
16618   case X86::WIN_ALLOCA:
16619     return EmitLoweredWinAlloca(MI, BB);
16620   case X86::SEG_ALLOCA_32:
16621     return EmitLoweredSegAlloca(MI, BB, false);
16622   case X86::SEG_ALLOCA_64:
16623     return EmitLoweredSegAlloca(MI, BB, true);
16624   case X86::TLSCall_32:
16625   case X86::TLSCall_64:
16626     return EmitLoweredTLSCall(MI, BB);
16627   case X86::CMOV_GR8:
16628   case X86::CMOV_FR32:
16629   case X86::CMOV_FR64:
16630   case X86::CMOV_V4F32:
16631   case X86::CMOV_V2F64:
16632   case X86::CMOV_V2I64:
16633   case X86::CMOV_V8F32:
16634   case X86::CMOV_V4F64:
16635   case X86::CMOV_V4I64:
16636   case X86::CMOV_V16F32:
16637   case X86::CMOV_V8F64:
16638   case X86::CMOV_V8I64:
16639   case X86::CMOV_GR16:
16640   case X86::CMOV_GR32:
16641   case X86::CMOV_RFP32:
16642   case X86::CMOV_RFP64:
16643   case X86::CMOV_RFP80:
16644     return EmitLoweredSelect(MI, BB);
16645
16646   case X86::FP32_TO_INT16_IN_MEM:
16647   case X86::FP32_TO_INT32_IN_MEM:
16648   case X86::FP32_TO_INT64_IN_MEM:
16649   case X86::FP64_TO_INT16_IN_MEM:
16650   case X86::FP64_TO_INT32_IN_MEM:
16651   case X86::FP64_TO_INT64_IN_MEM:
16652   case X86::FP80_TO_INT16_IN_MEM:
16653   case X86::FP80_TO_INT32_IN_MEM:
16654   case X86::FP80_TO_INT64_IN_MEM: {
16655     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16656     DebugLoc DL = MI->getDebugLoc();
16657
16658     // Change the floating point control register to use "round towards zero"
16659     // mode when truncating to an integer value.
16660     MachineFunction *F = BB->getParent();
16661     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16662     addFrameReference(BuildMI(*BB, MI, DL,
16663                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16664
16665     // Load the old value of the high byte of the control word...
16666     unsigned OldCW =
16667       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16668     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16669                       CWFrameIdx);
16670
16671     // Set the high part to be round to zero...
16672     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16673       .addImm(0xC7F);
16674
16675     // Reload the modified control word now...
16676     addFrameReference(BuildMI(*BB, MI, DL,
16677                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16678
16679     // Restore the memory image of control word to original value
16680     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16681       .addReg(OldCW);
16682
16683     // Get the X86 opcode to use.
16684     unsigned Opc;
16685     switch (MI->getOpcode()) {
16686     default: llvm_unreachable("illegal opcode!");
16687     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16688     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16689     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16690     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16691     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16692     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16693     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16694     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16695     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16696     }
16697
16698     X86AddressMode AM;
16699     MachineOperand &Op = MI->getOperand(0);
16700     if (Op.isReg()) {
16701       AM.BaseType = X86AddressMode::RegBase;
16702       AM.Base.Reg = Op.getReg();
16703     } else {
16704       AM.BaseType = X86AddressMode::FrameIndexBase;
16705       AM.Base.FrameIndex = Op.getIndex();
16706     }
16707     Op = MI->getOperand(1);
16708     if (Op.isImm())
16709       AM.Scale = Op.getImm();
16710     Op = MI->getOperand(2);
16711     if (Op.isImm())
16712       AM.IndexReg = Op.getImm();
16713     Op = MI->getOperand(3);
16714     if (Op.isGlobal()) {
16715       AM.GV = Op.getGlobal();
16716     } else {
16717       AM.Disp = Op.getImm();
16718     }
16719     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16720                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16721
16722     // Reload the original control word now.
16723     addFrameReference(BuildMI(*BB, MI, DL,
16724                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16725
16726     MI->eraseFromParent();   // The pseudo instruction is gone now.
16727     return BB;
16728   }
16729     // String/text processing lowering.
16730   case X86::PCMPISTRM128REG:
16731   case X86::VPCMPISTRM128REG:
16732   case X86::PCMPISTRM128MEM:
16733   case X86::VPCMPISTRM128MEM:
16734   case X86::PCMPESTRM128REG:
16735   case X86::VPCMPESTRM128REG:
16736   case X86::PCMPESTRM128MEM:
16737   case X86::VPCMPESTRM128MEM:
16738     assert(Subtarget->hasSSE42() &&
16739            "Target must have SSE4.2 or AVX features enabled");
16740     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16741
16742   // String/text processing lowering.
16743   case X86::PCMPISTRIREG:
16744   case X86::VPCMPISTRIREG:
16745   case X86::PCMPISTRIMEM:
16746   case X86::VPCMPISTRIMEM:
16747   case X86::PCMPESTRIREG:
16748   case X86::VPCMPESTRIREG:
16749   case X86::PCMPESTRIMEM:
16750   case X86::VPCMPESTRIMEM:
16751     assert(Subtarget->hasSSE42() &&
16752            "Target must have SSE4.2 or AVX features enabled");
16753     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16754
16755   // Thread synchronization.
16756   case X86::MONITOR:
16757     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16758
16759   // xbegin
16760   case X86::XBEGIN:
16761     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16762
16763   // Atomic Lowering.
16764   case X86::ATOMAND8:
16765   case X86::ATOMAND16:
16766   case X86::ATOMAND32:
16767   case X86::ATOMAND64:
16768     // Fall through
16769   case X86::ATOMOR8:
16770   case X86::ATOMOR16:
16771   case X86::ATOMOR32:
16772   case X86::ATOMOR64:
16773     // Fall through
16774   case X86::ATOMXOR16:
16775   case X86::ATOMXOR8:
16776   case X86::ATOMXOR32:
16777   case X86::ATOMXOR64:
16778     // Fall through
16779   case X86::ATOMNAND8:
16780   case X86::ATOMNAND16:
16781   case X86::ATOMNAND32:
16782   case X86::ATOMNAND64:
16783     // Fall through
16784   case X86::ATOMMAX8:
16785   case X86::ATOMMAX16:
16786   case X86::ATOMMAX32:
16787   case X86::ATOMMAX64:
16788     // Fall through
16789   case X86::ATOMMIN8:
16790   case X86::ATOMMIN16:
16791   case X86::ATOMMIN32:
16792   case X86::ATOMMIN64:
16793     // Fall through
16794   case X86::ATOMUMAX8:
16795   case X86::ATOMUMAX16:
16796   case X86::ATOMUMAX32:
16797   case X86::ATOMUMAX64:
16798     // Fall through
16799   case X86::ATOMUMIN8:
16800   case X86::ATOMUMIN16:
16801   case X86::ATOMUMIN32:
16802   case X86::ATOMUMIN64:
16803     return EmitAtomicLoadArith(MI, BB);
16804
16805   // This group does 64-bit operations on a 32-bit host.
16806   case X86::ATOMAND6432:
16807   case X86::ATOMOR6432:
16808   case X86::ATOMXOR6432:
16809   case X86::ATOMNAND6432:
16810   case X86::ATOMADD6432:
16811   case X86::ATOMSUB6432:
16812   case X86::ATOMMAX6432:
16813   case X86::ATOMMIN6432:
16814   case X86::ATOMUMAX6432:
16815   case X86::ATOMUMIN6432:
16816   case X86::ATOMSWAP6432:
16817     return EmitAtomicLoadArith6432(MI, BB);
16818
16819   case X86::VASTART_SAVE_XMM_REGS:
16820     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16821
16822   case X86::VAARG_64:
16823     return EmitVAARG64WithCustomInserter(MI, BB);
16824
16825   case X86::EH_SjLj_SetJmp32:
16826   case X86::EH_SjLj_SetJmp64:
16827     return emitEHSjLjSetJmp(MI, BB);
16828
16829   case X86::EH_SjLj_LongJmp32:
16830   case X86::EH_SjLj_LongJmp64:
16831     return emitEHSjLjLongJmp(MI, BB);
16832
16833   case TargetOpcode::STACKMAP:
16834   case TargetOpcode::PATCHPOINT:
16835     return emitPatchPoint(MI, BB);
16836
16837   case X86::VFMADDPDr213r:
16838   case X86::VFMADDPSr213r:
16839   case X86::VFMADDSDr213r:
16840   case X86::VFMADDSSr213r:
16841   case X86::VFMSUBPDr213r:
16842   case X86::VFMSUBPSr213r:
16843   case X86::VFMSUBSDr213r:
16844   case X86::VFMSUBSSr213r:
16845   case X86::VFNMADDPDr213r:
16846   case X86::VFNMADDPSr213r:
16847   case X86::VFNMADDSDr213r:
16848   case X86::VFNMADDSSr213r:
16849   case X86::VFNMSUBPDr213r:
16850   case X86::VFNMSUBPSr213r:
16851   case X86::VFNMSUBSDr213r:
16852   case X86::VFNMSUBSSr213r:
16853   case X86::VFMADDPDr213rY:
16854   case X86::VFMADDPSr213rY:
16855   case X86::VFMSUBPDr213rY:
16856   case X86::VFMSUBPSr213rY:
16857   case X86::VFNMADDPDr213rY:
16858   case X86::VFNMADDPSr213rY:
16859   case X86::VFNMSUBPDr213rY:
16860   case X86::VFNMSUBPSr213rY:
16861     return emitFMA3Instr(MI, BB);
16862   }
16863 }
16864
16865 //===----------------------------------------------------------------------===//
16866 //                           X86 Optimization Hooks
16867 //===----------------------------------------------------------------------===//
16868
16869 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16870                                                        APInt &KnownZero,
16871                                                        APInt &KnownOne,
16872                                                        const SelectionDAG &DAG,
16873                                                        unsigned Depth) const {
16874   unsigned BitWidth = KnownZero.getBitWidth();
16875   unsigned Opc = Op.getOpcode();
16876   assert((Opc >= ISD::BUILTIN_OP_END ||
16877           Opc == ISD::INTRINSIC_WO_CHAIN ||
16878           Opc == ISD::INTRINSIC_W_CHAIN ||
16879           Opc == ISD::INTRINSIC_VOID) &&
16880          "Should use MaskedValueIsZero if you don't know whether Op"
16881          " is a target node!");
16882
16883   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16884   switch (Opc) {
16885   default: break;
16886   case X86ISD::ADD:
16887   case X86ISD::SUB:
16888   case X86ISD::ADC:
16889   case X86ISD::SBB:
16890   case X86ISD::SMUL:
16891   case X86ISD::UMUL:
16892   case X86ISD::INC:
16893   case X86ISD::DEC:
16894   case X86ISD::OR:
16895   case X86ISD::XOR:
16896   case X86ISD::AND:
16897     // These nodes' second result is a boolean.
16898     if (Op.getResNo() == 0)
16899       break;
16900     // Fallthrough
16901   case X86ISD::SETCC:
16902     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16903     break;
16904   case ISD::INTRINSIC_WO_CHAIN: {
16905     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16906     unsigned NumLoBits = 0;
16907     switch (IntId) {
16908     default: break;
16909     case Intrinsic::x86_sse_movmsk_ps:
16910     case Intrinsic::x86_avx_movmsk_ps_256:
16911     case Intrinsic::x86_sse2_movmsk_pd:
16912     case Intrinsic::x86_avx_movmsk_pd_256:
16913     case Intrinsic::x86_mmx_pmovmskb:
16914     case Intrinsic::x86_sse2_pmovmskb_128:
16915     case Intrinsic::x86_avx2_pmovmskb: {
16916       // High bits of movmskp{s|d}, pmovmskb are known zero.
16917       switch (IntId) {
16918         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16919         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16920         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16921         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16922         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16923         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16924         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16925         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16926       }
16927       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16928       break;
16929     }
16930     }
16931     break;
16932   }
16933   }
16934 }
16935
16936 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16937   SDValue Op,
16938   const SelectionDAG &,
16939   unsigned Depth) const {
16940   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16941   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16942     return Op.getValueType().getScalarType().getSizeInBits();
16943
16944   // Fallback case.
16945   return 1;
16946 }
16947
16948 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16949 /// node is a GlobalAddress + offset.
16950 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16951                                        const GlobalValue* &GA,
16952                                        int64_t &Offset) const {
16953   if (N->getOpcode() == X86ISD::Wrapper) {
16954     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16955       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16956       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16957       return true;
16958     }
16959   }
16960   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16961 }
16962
16963 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16964 /// same as extracting the high 128-bit part of 256-bit vector and then
16965 /// inserting the result into the low part of a new 256-bit vector
16966 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16967   EVT VT = SVOp->getValueType(0);
16968   unsigned NumElems = VT.getVectorNumElements();
16969
16970   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16971   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16972     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16973         SVOp->getMaskElt(j) >= 0)
16974       return false;
16975
16976   return true;
16977 }
16978
16979 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16980 /// same as extracting the low 128-bit part of 256-bit vector and then
16981 /// inserting the result into the high part of a new 256-bit vector
16982 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16983   EVT VT = SVOp->getValueType(0);
16984   unsigned NumElems = VT.getVectorNumElements();
16985
16986   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
16987   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
16988     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16989         SVOp->getMaskElt(j) >= 0)
16990       return false;
16991
16992   return true;
16993 }
16994
16995 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
16996 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
16997                                         TargetLowering::DAGCombinerInfo &DCI,
16998                                         const X86Subtarget* Subtarget) {
16999   SDLoc dl(N);
17000   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17001   SDValue V1 = SVOp->getOperand(0);
17002   SDValue V2 = SVOp->getOperand(1);
17003   EVT VT = SVOp->getValueType(0);
17004   unsigned NumElems = VT.getVectorNumElements();
17005
17006   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17007       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17008     //
17009     //                   0,0,0,...
17010     //                      |
17011     //    V      UNDEF    BUILD_VECTOR    UNDEF
17012     //     \      /           \           /
17013     //  CONCAT_VECTOR         CONCAT_VECTOR
17014     //         \                  /
17015     //          \                /
17016     //          RESULT: V + zero extended
17017     //
17018     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17019         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17020         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17021       return SDValue();
17022
17023     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17024       return SDValue();
17025
17026     // To match the shuffle mask, the first half of the mask should
17027     // be exactly the first vector, and all the rest a splat with the
17028     // first element of the second one.
17029     for (unsigned i = 0; i != NumElems/2; ++i)
17030       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17031           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17032         return SDValue();
17033
17034     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17035     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17036       if (Ld->hasNUsesOfValue(1, 0)) {
17037         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17038         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17039         SDValue ResNode =
17040           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17041                                   Ld->getMemoryVT(),
17042                                   Ld->getPointerInfo(),
17043                                   Ld->getAlignment(),
17044                                   false/*isVolatile*/, true/*ReadMem*/,
17045                                   false/*WriteMem*/);
17046
17047         // Make sure the newly-created LOAD is in the same position as Ld in
17048         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17049         // and update uses of Ld's output chain to use the TokenFactor.
17050         if (Ld->hasAnyUseOfValue(1)) {
17051           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17052                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17053           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17054           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17055                                  SDValue(ResNode.getNode(), 1));
17056         }
17057
17058         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17059       }
17060     }
17061
17062     // Emit a zeroed vector and insert the desired subvector on its
17063     // first half.
17064     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17065     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17066     return DCI.CombineTo(N, InsV);
17067   }
17068
17069   //===--------------------------------------------------------------------===//
17070   // Combine some shuffles into subvector extracts and inserts:
17071   //
17072
17073   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17074   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17075     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17076     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17077     return DCI.CombineTo(N, InsV);
17078   }
17079
17080   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17081   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17082     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17083     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17084     return DCI.CombineTo(N, InsV);
17085   }
17086
17087   return SDValue();
17088 }
17089
17090 /// PerformShuffleCombine - Performs several different shuffle combines.
17091 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17092                                      TargetLowering::DAGCombinerInfo &DCI,
17093                                      const X86Subtarget *Subtarget) {
17094   SDLoc dl(N);
17095   EVT VT = N->getValueType(0);
17096
17097   // Don't create instructions with illegal types after legalize types has run.
17098   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17099   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17100     return SDValue();
17101
17102   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17103   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17104       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17105     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17106
17107   // Only handle 128 wide vector from here on.
17108   if (!VT.is128BitVector())
17109     return SDValue();
17110
17111   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17112   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17113   // consecutive, non-overlapping, and in the right order.
17114   SmallVector<SDValue, 16> Elts;
17115   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17116     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17117
17118   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17119 }
17120
17121 /// PerformTruncateCombine - Converts truncate operation to
17122 /// a sequence of vector shuffle operations.
17123 /// It is possible when we truncate 256-bit vector to 128-bit vector
17124 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17125                                       TargetLowering::DAGCombinerInfo &DCI,
17126                                       const X86Subtarget *Subtarget)  {
17127   return SDValue();
17128 }
17129
17130 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17131 /// specific shuffle of a load can be folded into a single element load.
17132 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17133 /// shuffles have been customed lowered so we need to handle those here.
17134 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17135                                          TargetLowering::DAGCombinerInfo &DCI) {
17136   if (DCI.isBeforeLegalizeOps())
17137     return SDValue();
17138
17139   SDValue InVec = N->getOperand(0);
17140   SDValue EltNo = N->getOperand(1);
17141
17142   if (!isa<ConstantSDNode>(EltNo))
17143     return SDValue();
17144
17145   EVT VT = InVec.getValueType();
17146
17147   bool HasShuffleIntoBitcast = false;
17148   if (InVec.getOpcode() == ISD::BITCAST) {
17149     // Don't duplicate a load with other uses.
17150     if (!InVec.hasOneUse())
17151       return SDValue();
17152     EVT BCVT = InVec.getOperand(0).getValueType();
17153     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17154       return SDValue();
17155     InVec = InVec.getOperand(0);
17156     HasShuffleIntoBitcast = true;
17157   }
17158
17159   if (!isTargetShuffle(InVec.getOpcode()))
17160     return SDValue();
17161
17162   // Don't duplicate a load with other uses.
17163   if (!InVec.hasOneUse())
17164     return SDValue();
17165
17166   SmallVector<int, 16> ShuffleMask;
17167   bool UnaryShuffle;
17168   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17169                             UnaryShuffle))
17170     return SDValue();
17171
17172   // Select the input vector, guarding against out of range extract vector.
17173   unsigned NumElems = VT.getVectorNumElements();
17174   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17175   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17176   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17177                                          : InVec.getOperand(1);
17178
17179   // If inputs to shuffle are the same for both ops, then allow 2 uses
17180   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17181
17182   if (LdNode.getOpcode() == ISD::BITCAST) {
17183     // Don't duplicate a load with other uses.
17184     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17185       return SDValue();
17186
17187     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17188     LdNode = LdNode.getOperand(0);
17189   }
17190
17191   if (!ISD::isNormalLoad(LdNode.getNode()))
17192     return SDValue();
17193
17194   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17195
17196   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17197     return SDValue();
17198
17199   if (HasShuffleIntoBitcast) {
17200     // If there's a bitcast before the shuffle, check if the load type and
17201     // alignment is valid.
17202     unsigned Align = LN0->getAlignment();
17203     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17204     unsigned NewAlign = TLI.getDataLayout()->
17205       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17206
17207     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17208       return SDValue();
17209   }
17210
17211   // All checks match so transform back to vector_shuffle so that DAG combiner
17212   // can finish the job
17213   SDLoc dl(N);
17214
17215   // Create shuffle node taking into account the case that its a unary shuffle
17216   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17217   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17218                                  InVec.getOperand(0), Shuffle,
17219                                  &ShuffleMask[0]);
17220   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17221   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17222                      EltNo);
17223 }
17224
17225 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17226 /// generation and convert it from being a bunch of shuffles and extracts
17227 /// to a simple store and scalar loads to extract the elements.
17228 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17229                                          TargetLowering::DAGCombinerInfo &DCI) {
17230   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17231   if (NewOp.getNode())
17232     return NewOp;
17233
17234   SDValue InputVector = N->getOperand(0);
17235
17236   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17237   // from mmx to v2i32 has a single usage.
17238   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17239       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17240       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17241     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17242                        N->getValueType(0),
17243                        InputVector.getNode()->getOperand(0));
17244
17245   // Only operate on vectors of 4 elements, where the alternative shuffling
17246   // gets to be more expensive.
17247   if (InputVector.getValueType() != MVT::v4i32)
17248     return SDValue();
17249
17250   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17251   // single use which is a sign-extend or zero-extend, and all elements are
17252   // used.
17253   SmallVector<SDNode *, 4> Uses;
17254   unsigned ExtractedElements = 0;
17255   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17256        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17257     if (UI.getUse().getResNo() != InputVector.getResNo())
17258       return SDValue();
17259
17260     SDNode *Extract = *UI;
17261     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17262       return SDValue();
17263
17264     if (Extract->getValueType(0) != MVT::i32)
17265       return SDValue();
17266     if (!Extract->hasOneUse())
17267       return SDValue();
17268     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17269         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17270       return SDValue();
17271     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17272       return SDValue();
17273
17274     // Record which element was extracted.
17275     ExtractedElements |=
17276       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17277
17278     Uses.push_back(Extract);
17279   }
17280
17281   // If not all the elements were used, this may not be worthwhile.
17282   if (ExtractedElements != 15)
17283     return SDValue();
17284
17285   // Ok, we've now decided to do the transformation.
17286   SDLoc dl(InputVector);
17287
17288   // Store the value to a temporary stack slot.
17289   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17290   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17291                             MachinePointerInfo(), false, false, 0);
17292
17293   // Replace each use (extract) with a load of the appropriate element.
17294   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17295        UE = Uses.end(); UI != UE; ++UI) {
17296     SDNode *Extract = *UI;
17297
17298     // cOMpute the element's address.
17299     SDValue Idx = Extract->getOperand(1);
17300     unsigned EltSize =
17301         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17302     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17303     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17304     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17305
17306     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17307                                      StackPtr, OffsetVal);
17308
17309     // Load the scalar.
17310     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17311                                      ScalarAddr, MachinePointerInfo(),
17312                                      false, false, false, 0);
17313
17314     // Replace the exact with the load.
17315     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17316   }
17317
17318   // The replacement was made in place; don't return anything.
17319   return SDValue();
17320 }
17321
17322 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17323 static std::pair<unsigned, bool>
17324 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17325                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17326   if (!VT.isVector())
17327     return std::make_pair(0, false);
17328
17329   bool NeedSplit = false;
17330   switch (VT.getSimpleVT().SimpleTy) {
17331   default: return std::make_pair(0, false);
17332   case MVT::v32i8:
17333   case MVT::v16i16:
17334   case MVT::v8i32:
17335     if (!Subtarget->hasAVX2())
17336       NeedSplit = true;
17337     if (!Subtarget->hasAVX())
17338       return std::make_pair(0, false);
17339     break;
17340   case MVT::v16i8:
17341   case MVT::v8i16:
17342   case MVT::v4i32:
17343     if (!Subtarget->hasSSE2())
17344       return std::make_pair(0, false);
17345   }
17346
17347   // SSE2 has only a small subset of the operations.
17348   bool hasUnsigned = Subtarget->hasSSE41() ||
17349                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17350   bool hasSigned = Subtarget->hasSSE41() ||
17351                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17352
17353   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17354
17355   unsigned Opc = 0;
17356   // Check for x CC y ? x : y.
17357   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17358       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17359     switch (CC) {
17360     default: break;
17361     case ISD::SETULT:
17362     case ISD::SETULE:
17363       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17364     case ISD::SETUGT:
17365     case ISD::SETUGE:
17366       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17367     case ISD::SETLT:
17368     case ISD::SETLE:
17369       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17370     case ISD::SETGT:
17371     case ISD::SETGE:
17372       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17373     }
17374   // Check for x CC y ? y : x -- a min/max with reversed arms.
17375   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17376              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17377     switch (CC) {
17378     default: break;
17379     case ISD::SETULT:
17380     case ISD::SETULE:
17381       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17382     case ISD::SETUGT:
17383     case ISD::SETUGE:
17384       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17385     case ISD::SETLT:
17386     case ISD::SETLE:
17387       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17388     case ISD::SETGT:
17389     case ISD::SETGE:
17390       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17391     }
17392   }
17393
17394   return std::make_pair(Opc, NeedSplit);
17395 }
17396
17397 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17398 /// nodes.
17399 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17400                                     TargetLowering::DAGCombinerInfo &DCI,
17401                                     const X86Subtarget *Subtarget) {
17402   SDLoc DL(N);
17403   SDValue Cond = N->getOperand(0);
17404   // Get the LHS/RHS of the select.
17405   SDValue LHS = N->getOperand(1);
17406   SDValue RHS = N->getOperand(2);
17407   EVT VT = LHS.getValueType();
17408   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17409
17410   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17411   // instructions match the semantics of the common C idiom x<y?x:y but not
17412   // x<=y?x:y, because of how they handle negative zero (which can be
17413   // ignored in unsafe-math mode).
17414   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17415       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17416       (Subtarget->hasSSE2() ||
17417        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17418     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17419
17420     unsigned Opcode = 0;
17421     // Check for x CC y ? x : y.
17422     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17423         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17424       switch (CC) {
17425       default: break;
17426       case ISD::SETULT:
17427         // Converting this to a min would handle NaNs incorrectly, and swapping
17428         // the operands would cause it to handle comparisons between positive
17429         // and negative zero incorrectly.
17430         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17431           if (!DAG.getTarget().Options.UnsafeFPMath &&
17432               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17433             break;
17434           std::swap(LHS, RHS);
17435         }
17436         Opcode = X86ISD::FMIN;
17437         break;
17438       case ISD::SETOLE:
17439         // Converting this to a min would handle comparisons between positive
17440         // and negative zero incorrectly.
17441         if (!DAG.getTarget().Options.UnsafeFPMath &&
17442             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17443           break;
17444         Opcode = X86ISD::FMIN;
17445         break;
17446       case ISD::SETULE:
17447         // Converting this to a min would handle both negative zeros and NaNs
17448         // incorrectly, but we can swap the operands to fix both.
17449         std::swap(LHS, RHS);
17450       case ISD::SETOLT:
17451       case ISD::SETLT:
17452       case ISD::SETLE:
17453         Opcode = X86ISD::FMIN;
17454         break;
17455
17456       case ISD::SETOGE:
17457         // Converting this to a max would handle comparisons between positive
17458         // and negative zero incorrectly.
17459         if (!DAG.getTarget().Options.UnsafeFPMath &&
17460             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17461           break;
17462         Opcode = X86ISD::FMAX;
17463         break;
17464       case ISD::SETUGT:
17465         // Converting this to a max would handle NaNs incorrectly, and swapping
17466         // the operands would cause it to handle comparisons between positive
17467         // and negative zero incorrectly.
17468         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17469           if (!DAG.getTarget().Options.UnsafeFPMath &&
17470               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17471             break;
17472           std::swap(LHS, RHS);
17473         }
17474         Opcode = X86ISD::FMAX;
17475         break;
17476       case ISD::SETUGE:
17477         // Converting this to a max would handle both negative zeros and NaNs
17478         // incorrectly, but we can swap the operands to fix both.
17479         std::swap(LHS, RHS);
17480       case ISD::SETOGT:
17481       case ISD::SETGT:
17482       case ISD::SETGE:
17483         Opcode = X86ISD::FMAX;
17484         break;
17485       }
17486     // Check for x CC y ? y : x -- a min/max with reversed arms.
17487     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17488                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17489       switch (CC) {
17490       default: break;
17491       case ISD::SETOGE:
17492         // Converting this to a min would handle comparisons between positive
17493         // and negative zero incorrectly, and swapping the operands would
17494         // cause it to handle NaNs incorrectly.
17495         if (!DAG.getTarget().Options.UnsafeFPMath &&
17496             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17497           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17498             break;
17499           std::swap(LHS, RHS);
17500         }
17501         Opcode = X86ISD::FMIN;
17502         break;
17503       case ISD::SETUGT:
17504         // Converting this to a min would handle NaNs incorrectly.
17505         if (!DAG.getTarget().Options.UnsafeFPMath &&
17506             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17507           break;
17508         Opcode = X86ISD::FMIN;
17509         break;
17510       case ISD::SETUGE:
17511         // Converting this to a min would handle both negative zeros and NaNs
17512         // incorrectly, but we can swap the operands to fix both.
17513         std::swap(LHS, RHS);
17514       case ISD::SETOGT:
17515       case ISD::SETGT:
17516       case ISD::SETGE:
17517         Opcode = X86ISD::FMIN;
17518         break;
17519
17520       case ISD::SETULT:
17521         // Converting this to a max would handle NaNs incorrectly.
17522         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17523           break;
17524         Opcode = X86ISD::FMAX;
17525         break;
17526       case ISD::SETOLE:
17527         // Converting this to a max would handle comparisons between positive
17528         // and negative zero incorrectly, and swapping the operands would
17529         // cause it to handle NaNs incorrectly.
17530         if (!DAG.getTarget().Options.UnsafeFPMath &&
17531             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17532           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17533             break;
17534           std::swap(LHS, RHS);
17535         }
17536         Opcode = X86ISD::FMAX;
17537         break;
17538       case ISD::SETULE:
17539         // Converting this to a max would handle both negative zeros and NaNs
17540         // incorrectly, but we can swap the operands to fix both.
17541         std::swap(LHS, RHS);
17542       case ISD::SETOLT:
17543       case ISD::SETLT:
17544       case ISD::SETLE:
17545         Opcode = X86ISD::FMAX;
17546         break;
17547       }
17548     }
17549
17550     if (Opcode)
17551       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17552   }
17553
17554   EVT CondVT = Cond.getValueType();
17555   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17556       CondVT.getVectorElementType() == MVT::i1) {
17557     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17558     // lowering on AVX-512. In this case we convert it to
17559     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17560     // The same situation for all 128 and 256-bit vectors of i8 and i16
17561     EVT OpVT = LHS.getValueType();
17562     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17563         (OpVT.getVectorElementType() == MVT::i8 ||
17564          OpVT.getVectorElementType() == MVT::i16)) {
17565       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17566       DCI.AddToWorklist(Cond.getNode());
17567       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17568     }
17569   }
17570   // If this is a select between two integer constants, try to do some
17571   // optimizations.
17572   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17573     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17574       // Don't do this for crazy integer types.
17575       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17576         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17577         // so that TrueC (the true value) is larger than FalseC.
17578         bool NeedsCondInvert = false;
17579
17580         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17581             // Efficiently invertible.
17582             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17583              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17584               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17585           NeedsCondInvert = true;
17586           std::swap(TrueC, FalseC);
17587         }
17588
17589         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17590         if (FalseC->getAPIntValue() == 0 &&
17591             TrueC->getAPIntValue().isPowerOf2()) {
17592           if (NeedsCondInvert) // Invert the condition if needed.
17593             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17594                                DAG.getConstant(1, Cond.getValueType()));
17595
17596           // Zero extend the condition if needed.
17597           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17598
17599           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17600           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17601                              DAG.getConstant(ShAmt, MVT::i8));
17602         }
17603
17604         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17605         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17606           if (NeedsCondInvert) // Invert the condition if needed.
17607             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17608                                DAG.getConstant(1, Cond.getValueType()));
17609
17610           // Zero extend the condition if needed.
17611           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17612                              FalseC->getValueType(0), Cond);
17613           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17614                              SDValue(FalseC, 0));
17615         }
17616
17617         // Optimize cases that will turn into an LEA instruction.  This requires
17618         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17619         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17620           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17621           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17622
17623           bool isFastMultiplier = false;
17624           if (Diff < 10) {
17625             switch ((unsigned char)Diff) {
17626               default: break;
17627               case 1:  // result = add base, cond
17628               case 2:  // result = lea base(    , cond*2)
17629               case 3:  // result = lea base(cond, cond*2)
17630               case 4:  // result = lea base(    , cond*4)
17631               case 5:  // result = lea base(cond, cond*4)
17632               case 8:  // result = lea base(    , cond*8)
17633               case 9:  // result = lea base(cond, cond*8)
17634                 isFastMultiplier = true;
17635                 break;
17636             }
17637           }
17638
17639           if (isFastMultiplier) {
17640             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17641             if (NeedsCondInvert) // Invert the condition if needed.
17642               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17643                                  DAG.getConstant(1, Cond.getValueType()));
17644
17645             // Zero extend the condition if needed.
17646             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17647                                Cond);
17648             // Scale the condition by the difference.
17649             if (Diff != 1)
17650               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17651                                  DAG.getConstant(Diff, Cond.getValueType()));
17652
17653             // Add the base if non-zero.
17654             if (FalseC->getAPIntValue() != 0)
17655               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17656                                  SDValue(FalseC, 0));
17657             return Cond;
17658           }
17659         }
17660       }
17661   }
17662
17663   // Canonicalize max and min:
17664   // (x > y) ? x : y -> (x >= y) ? x : y
17665   // (x < y) ? x : y -> (x <= y) ? x : y
17666   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17667   // the need for an extra compare
17668   // against zero. e.g.
17669   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17670   // subl   %esi, %edi
17671   // testl  %edi, %edi
17672   // movl   $0, %eax
17673   // cmovgl %edi, %eax
17674   // =>
17675   // xorl   %eax, %eax
17676   // subl   %esi, $edi
17677   // cmovsl %eax, %edi
17678   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17679       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17680       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17681     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17682     switch (CC) {
17683     default: break;
17684     case ISD::SETLT:
17685     case ISD::SETGT: {
17686       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17687       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17688                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17689       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17690     }
17691     }
17692   }
17693
17694   // Early exit check
17695   if (!TLI.isTypeLegal(VT))
17696     return SDValue();
17697
17698   // Match VSELECTs into subs with unsigned saturation.
17699   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17700       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17701       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17702        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17703     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17704
17705     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17706     // left side invert the predicate to simplify logic below.
17707     SDValue Other;
17708     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17709       Other = RHS;
17710       CC = ISD::getSetCCInverse(CC, true);
17711     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17712       Other = LHS;
17713     }
17714
17715     if (Other.getNode() && Other->getNumOperands() == 2 &&
17716         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17717       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17718       SDValue CondRHS = Cond->getOperand(1);
17719
17720       // Look for a general sub with unsigned saturation first.
17721       // x >= y ? x-y : 0 --> subus x, y
17722       // x >  y ? x-y : 0 --> subus x, y
17723       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17724           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17725         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17726
17727       // If the RHS is a constant we have to reverse the const canonicalization.
17728       // x > C-1 ? x+-C : 0 --> subus x, C
17729       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17730           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17731         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17732         if (CondRHS.getConstantOperandVal(0) == -A-1)
17733           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17734                              DAG.getConstant(-A, VT));
17735       }
17736
17737       // Another special case: If C was a sign bit, the sub has been
17738       // canonicalized into a xor.
17739       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17740       //        it's safe to decanonicalize the xor?
17741       // x s< 0 ? x^C : 0 --> subus x, C
17742       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17743           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17744           isSplatVector(OpRHS.getNode())) {
17745         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17746         if (A.isSignBit())
17747           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17748       }
17749     }
17750   }
17751
17752   // Try to match a min/max vector operation.
17753   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17754     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17755     unsigned Opc = ret.first;
17756     bool NeedSplit = ret.second;
17757
17758     if (Opc && NeedSplit) {
17759       unsigned NumElems = VT.getVectorNumElements();
17760       // Extract the LHS vectors
17761       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17762       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17763
17764       // Extract the RHS vectors
17765       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17766       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17767
17768       // Create min/max for each subvector
17769       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17770       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17771
17772       // Merge the result
17773       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17774     } else if (Opc)
17775       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17776   }
17777
17778   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17779   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17780       // Check if SETCC has already been promoted
17781       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17782       // Check that condition value type matches vselect operand type
17783       CondVT == VT) { 
17784
17785     assert(Cond.getValueType().isVector() &&
17786            "vector select expects a vector selector!");
17787
17788     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17789     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17790
17791     if (!TValIsAllOnes && !FValIsAllZeros) {
17792       // Try invert the condition if true value is not all 1s and false value
17793       // is not all 0s.
17794       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17795       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17796
17797       if (TValIsAllZeros || FValIsAllOnes) {
17798         SDValue CC = Cond.getOperand(2);
17799         ISD::CondCode NewCC =
17800           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17801                                Cond.getOperand(0).getValueType().isInteger());
17802         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17803         std::swap(LHS, RHS);
17804         TValIsAllOnes = FValIsAllOnes;
17805         FValIsAllZeros = TValIsAllZeros;
17806       }
17807     }
17808
17809     if (TValIsAllOnes || FValIsAllZeros) {
17810       SDValue Ret;
17811
17812       if (TValIsAllOnes && FValIsAllZeros)
17813         Ret = Cond;
17814       else if (TValIsAllOnes)
17815         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17816                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17817       else if (FValIsAllZeros)
17818         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17819                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17820
17821       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17822     }
17823   }
17824
17825   // Try to fold this VSELECT into a MOVSS/MOVSD
17826   if (N->getOpcode() == ISD::VSELECT &&
17827       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17828     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17829         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17830       bool CanFold = false;
17831       unsigned NumElems = Cond.getNumOperands();
17832       SDValue A = LHS;
17833       SDValue B = RHS;
17834       
17835       if (isZero(Cond.getOperand(0))) {
17836         CanFold = true;
17837
17838         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17839         // fold (vselect <0,-1> -> (movsd A, B)
17840         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17841           CanFold = isAllOnes(Cond.getOperand(i));
17842       } else if (isAllOnes(Cond.getOperand(0))) {
17843         CanFold = true;
17844         std::swap(A, B);
17845
17846         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17847         // fold (vselect <-1,0> -> (movsd B, A)
17848         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17849           CanFold = isZero(Cond.getOperand(i));
17850       }
17851
17852       if (CanFold) {
17853         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17854           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17855         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17856       }
17857
17858       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17859         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17860         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17861         //                             (v2i64 (bitcast B)))))
17862         //
17863         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17864         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17865         //                             (v2f64 (bitcast B)))))
17866         //
17867         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17868         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17869         //                             (v2i64 (bitcast A)))))
17870         //
17871         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17872         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17873         //                             (v2f64 (bitcast A)))))
17874
17875         CanFold = (isZero(Cond.getOperand(0)) &&
17876                    isZero(Cond.getOperand(1)) &&
17877                    isAllOnes(Cond.getOperand(2)) &&
17878                    isAllOnes(Cond.getOperand(3)));
17879
17880         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17881             isAllOnes(Cond.getOperand(1)) &&
17882             isZero(Cond.getOperand(2)) &&
17883             isZero(Cond.getOperand(3))) {
17884           CanFold = true;
17885           std::swap(LHS, RHS);
17886         }
17887
17888         if (CanFold) {
17889           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17890           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17891           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17892           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17893                                                 NewB, DAG);
17894           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17895         }
17896       }
17897     }
17898   }
17899
17900   // If we know that this node is legal then we know that it is going to be
17901   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17902   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17903   // to simplify previous instructions.
17904   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17905       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17906     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17907
17908     // Don't optimize vector selects that map to mask-registers.
17909     if (BitWidth == 1)
17910       return SDValue();
17911
17912     // Check all uses of that condition operand to check whether it will be
17913     // consumed by non-BLEND instructions, which may depend on all bits are set
17914     // properly.
17915     for (SDNode::use_iterator I = Cond->use_begin(),
17916                               E = Cond->use_end(); I != E; ++I)
17917       if (I->getOpcode() != ISD::VSELECT)
17918         // TODO: Add other opcodes eventually lowered into BLEND.
17919         return SDValue();
17920
17921     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17922     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17923
17924     APInt KnownZero, KnownOne;
17925     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17926                                           DCI.isBeforeLegalizeOps());
17927     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17928         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17929       DCI.CommitTargetLoweringOpt(TLO);
17930   }
17931
17932   return SDValue();
17933 }
17934
17935 // Check whether a boolean test is testing a boolean value generated by
17936 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17937 // code.
17938 //
17939 // Simplify the following patterns:
17940 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17941 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17942 // to (Op EFLAGS Cond)
17943 //
17944 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17945 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17946 // to (Op EFLAGS !Cond)
17947 //
17948 // where Op could be BRCOND or CMOV.
17949 //
17950 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17951   // Quit if not CMP and SUB with its value result used.
17952   if (Cmp.getOpcode() != X86ISD::CMP &&
17953       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17954       return SDValue();
17955
17956   // Quit if not used as a boolean value.
17957   if (CC != X86::COND_E && CC != X86::COND_NE)
17958     return SDValue();
17959
17960   // Check CMP operands. One of them should be 0 or 1 and the other should be
17961   // an SetCC or extended from it.
17962   SDValue Op1 = Cmp.getOperand(0);
17963   SDValue Op2 = Cmp.getOperand(1);
17964
17965   SDValue SetCC;
17966   const ConstantSDNode* C = nullptr;
17967   bool needOppositeCond = (CC == X86::COND_E);
17968   bool checkAgainstTrue = false; // Is it a comparison against 1?
17969
17970   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17971     SetCC = Op2;
17972   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17973     SetCC = Op1;
17974   else // Quit if all operands are not constants.
17975     return SDValue();
17976
17977   if (C->getZExtValue() == 1) {
17978     needOppositeCond = !needOppositeCond;
17979     checkAgainstTrue = true;
17980   } else if (C->getZExtValue() != 0)
17981     // Quit if the constant is neither 0 or 1.
17982     return SDValue();
17983
17984   bool truncatedToBoolWithAnd = false;
17985   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
17986   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
17987          SetCC.getOpcode() == ISD::TRUNCATE ||
17988          SetCC.getOpcode() == ISD::AND) {
17989     if (SetCC.getOpcode() == ISD::AND) {
17990       int OpIdx = -1;
17991       ConstantSDNode *CS;
17992       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
17993           CS->getZExtValue() == 1)
17994         OpIdx = 1;
17995       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
17996           CS->getZExtValue() == 1)
17997         OpIdx = 0;
17998       if (OpIdx == -1)
17999         break;
18000       SetCC = SetCC.getOperand(OpIdx);
18001       truncatedToBoolWithAnd = true;
18002     } else
18003       SetCC = SetCC.getOperand(0);
18004   }
18005
18006   switch (SetCC.getOpcode()) {
18007   case X86ISD::SETCC_CARRY:
18008     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18009     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18010     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18011     // truncated to i1 using 'and'.
18012     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18013       break;
18014     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18015            "Invalid use of SETCC_CARRY!");
18016     // FALL THROUGH
18017   case X86ISD::SETCC:
18018     // Set the condition code or opposite one if necessary.
18019     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18020     if (needOppositeCond)
18021       CC = X86::GetOppositeBranchCondition(CC);
18022     return SetCC.getOperand(1);
18023   case X86ISD::CMOV: {
18024     // Check whether false/true value has canonical one, i.e. 0 or 1.
18025     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18026     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18027     // Quit if true value is not a constant.
18028     if (!TVal)
18029       return SDValue();
18030     // Quit if false value is not a constant.
18031     if (!FVal) {
18032       SDValue Op = SetCC.getOperand(0);
18033       // Skip 'zext' or 'trunc' node.
18034       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18035           Op.getOpcode() == ISD::TRUNCATE)
18036         Op = Op.getOperand(0);
18037       // A special case for rdrand/rdseed, where 0 is set if false cond is
18038       // found.
18039       if ((Op.getOpcode() != X86ISD::RDRAND &&
18040            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18041         return SDValue();
18042     }
18043     // Quit if false value is not the constant 0 or 1.
18044     bool FValIsFalse = true;
18045     if (FVal && FVal->getZExtValue() != 0) {
18046       if (FVal->getZExtValue() != 1)
18047         return SDValue();
18048       // If FVal is 1, opposite cond is needed.
18049       needOppositeCond = !needOppositeCond;
18050       FValIsFalse = false;
18051     }
18052     // Quit if TVal is not the constant opposite of FVal.
18053     if (FValIsFalse && TVal->getZExtValue() != 1)
18054       return SDValue();
18055     if (!FValIsFalse && TVal->getZExtValue() != 0)
18056       return SDValue();
18057     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18058     if (needOppositeCond)
18059       CC = X86::GetOppositeBranchCondition(CC);
18060     return SetCC.getOperand(3);
18061   }
18062   }
18063
18064   return SDValue();
18065 }
18066
18067 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18068 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18069                                   TargetLowering::DAGCombinerInfo &DCI,
18070                                   const X86Subtarget *Subtarget) {
18071   SDLoc DL(N);
18072
18073   // If the flag operand isn't dead, don't touch this CMOV.
18074   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18075     return SDValue();
18076
18077   SDValue FalseOp = N->getOperand(0);
18078   SDValue TrueOp = N->getOperand(1);
18079   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18080   SDValue Cond = N->getOperand(3);
18081
18082   if (CC == X86::COND_E || CC == X86::COND_NE) {
18083     switch (Cond.getOpcode()) {
18084     default: break;
18085     case X86ISD::BSR:
18086     case X86ISD::BSF:
18087       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18088       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18089         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18090     }
18091   }
18092
18093   SDValue Flags;
18094
18095   Flags = checkBoolTestSetCCCombine(Cond, CC);
18096   if (Flags.getNode() &&
18097       // Extra check as FCMOV only supports a subset of X86 cond.
18098       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18099     SDValue Ops[] = { FalseOp, TrueOp,
18100                       DAG.getConstant(CC, MVT::i8), Flags };
18101     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18102   }
18103
18104   // If this is a select between two integer constants, try to do some
18105   // optimizations.  Note that the operands are ordered the opposite of SELECT
18106   // operands.
18107   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18108     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18109       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18110       // larger than FalseC (the false value).
18111       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18112         CC = X86::GetOppositeBranchCondition(CC);
18113         std::swap(TrueC, FalseC);
18114         std::swap(TrueOp, FalseOp);
18115       }
18116
18117       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18118       // This is efficient for any integer data type (including i8/i16) and
18119       // shift amount.
18120       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18121         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18122                            DAG.getConstant(CC, MVT::i8), Cond);
18123
18124         // Zero extend the condition if needed.
18125         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18126
18127         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18128         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18129                            DAG.getConstant(ShAmt, MVT::i8));
18130         if (N->getNumValues() == 2)  // Dead flag value?
18131           return DCI.CombineTo(N, Cond, SDValue());
18132         return Cond;
18133       }
18134
18135       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18136       // for any integer data type, including i8/i16.
18137       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18138         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18139                            DAG.getConstant(CC, MVT::i8), Cond);
18140
18141         // Zero extend the condition if needed.
18142         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18143                            FalseC->getValueType(0), Cond);
18144         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18145                            SDValue(FalseC, 0));
18146
18147         if (N->getNumValues() == 2)  // Dead flag value?
18148           return DCI.CombineTo(N, Cond, SDValue());
18149         return Cond;
18150       }
18151
18152       // Optimize cases that will turn into an LEA instruction.  This requires
18153       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18154       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18155         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18156         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18157
18158         bool isFastMultiplier = false;
18159         if (Diff < 10) {
18160           switch ((unsigned char)Diff) {
18161           default: break;
18162           case 1:  // result = add base, cond
18163           case 2:  // result = lea base(    , cond*2)
18164           case 3:  // result = lea base(cond, cond*2)
18165           case 4:  // result = lea base(    , cond*4)
18166           case 5:  // result = lea base(cond, cond*4)
18167           case 8:  // result = lea base(    , cond*8)
18168           case 9:  // result = lea base(cond, cond*8)
18169             isFastMultiplier = true;
18170             break;
18171           }
18172         }
18173
18174         if (isFastMultiplier) {
18175           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18176           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18177                              DAG.getConstant(CC, MVT::i8), Cond);
18178           // Zero extend the condition if needed.
18179           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18180                              Cond);
18181           // Scale the condition by the difference.
18182           if (Diff != 1)
18183             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18184                                DAG.getConstant(Diff, Cond.getValueType()));
18185
18186           // Add the base if non-zero.
18187           if (FalseC->getAPIntValue() != 0)
18188             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18189                                SDValue(FalseC, 0));
18190           if (N->getNumValues() == 2)  // Dead flag value?
18191             return DCI.CombineTo(N, Cond, SDValue());
18192           return Cond;
18193         }
18194       }
18195     }
18196   }
18197
18198   // Handle these cases:
18199   //   (select (x != c), e, c) -> select (x != c), e, x),
18200   //   (select (x == c), c, e) -> select (x == c), x, e)
18201   // where the c is an integer constant, and the "select" is the combination
18202   // of CMOV and CMP.
18203   //
18204   // The rationale for this change is that the conditional-move from a constant
18205   // needs two instructions, however, conditional-move from a register needs
18206   // only one instruction.
18207   //
18208   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18209   //  some instruction-combining opportunities. This opt needs to be
18210   //  postponed as late as possible.
18211   //
18212   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18213     // the DCI.xxxx conditions are provided to postpone the optimization as
18214     // late as possible.
18215
18216     ConstantSDNode *CmpAgainst = nullptr;
18217     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18218         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18219         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18220
18221       if (CC == X86::COND_NE &&
18222           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18223         CC = X86::GetOppositeBranchCondition(CC);
18224         std::swap(TrueOp, FalseOp);
18225       }
18226
18227       if (CC == X86::COND_E &&
18228           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18229         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18230                           DAG.getConstant(CC, MVT::i8), Cond };
18231         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18232       }
18233     }
18234   }
18235
18236   return SDValue();
18237 }
18238
18239 /// PerformMulCombine - Optimize a single multiply with constant into two
18240 /// in order to implement it with two cheaper instructions, e.g.
18241 /// LEA + SHL, LEA + LEA.
18242 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18243                                  TargetLowering::DAGCombinerInfo &DCI) {
18244   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18245     return SDValue();
18246
18247   EVT VT = N->getValueType(0);
18248   if (VT != MVT::i64)
18249     return SDValue();
18250
18251   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18252   if (!C)
18253     return SDValue();
18254   uint64_t MulAmt = C->getZExtValue();
18255   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18256     return SDValue();
18257
18258   uint64_t MulAmt1 = 0;
18259   uint64_t MulAmt2 = 0;
18260   if ((MulAmt % 9) == 0) {
18261     MulAmt1 = 9;
18262     MulAmt2 = MulAmt / 9;
18263   } else if ((MulAmt % 5) == 0) {
18264     MulAmt1 = 5;
18265     MulAmt2 = MulAmt / 5;
18266   } else if ((MulAmt % 3) == 0) {
18267     MulAmt1 = 3;
18268     MulAmt2 = MulAmt / 3;
18269   }
18270   if (MulAmt2 &&
18271       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18272     SDLoc DL(N);
18273
18274     if (isPowerOf2_64(MulAmt2) &&
18275         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18276       // If second multiplifer is pow2, issue it first. We want the multiply by
18277       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18278       // is an add.
18279       std::swap(MulAmt1, MulAmt2);
18280
18281     SDValue NewMul;
18282     if (isPowerOf2_64(MulAmt1))
18283       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18284                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18285     else
18286       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18287                            DAG.getConstant(MulAmt1, VT));
18288
18289     if (isPowerOf2_64(MulAmt2))
18290       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18291                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18292     else
18293       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18294                            DAG.getConstant(MulAmt2, VT));
18295
18296     // Do not add new nodes to DAG combiner worklist.
18297     DCI.CombineTo(N, NewMul, false);
18298   }
18299   return SDValue();
18300 }
18301
18302 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18303   SDValue N0 = N->getOperand(0);
18304   SDValue N1 = N->getOperand(1);
18305   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18306   EVT VT = N0.getValueType();
18307
18308   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18309   // since the result of setcc_c is all zero's or all ones.
18310   if (VT.isInteger() && !VT.isVector() &&
18311       N1C && N0.getOpcode() == ISD::AND &&
18312       N0.getOperand(1).getOpcode() == ISD::Constant) {
18313     SDValue N00 = N0.getOperand(0);
18314     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18315         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18316           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18317          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18318       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18319       APInt ShAmt = N1C->getAPIntValue();
18320       Mask = Mask.shl(ShAmt);
18321       if (Mask != 0)
18322         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18323                            N00, DAG.getConstant(Mask, VT));
18324     }
18325   }
18326
18327   // Hardware support for vector shifts is sparse which makes us scalarize the
18328   // vector operations in many cases. Also, on sandybridge ADD is faster than
18329   // shl.
18330   // (shl V, 1) -> add V,V
18331   if (isSplatVector(N1.getNode())) {
18332     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18333     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18334     // We shift all of the values by one. In many cases we do not have
18335     // hardware support for this operation. This is better expressed as an ADD
18336     // of two values.
18337     if (N1C && (1 == N1C->getZExtValue())) {
18338       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18339     }
18340   }
18341
18342   return SDValue();
18343 }
18344
18345 /// \brief Returns a vector of 0s if the node in input is a vector logical
18346 /// shift by a constant amount which is known to be bigger than or equal
18347 /// to the vector element size in bits.
18348 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18349                                       const X86Subtarget *Subtarget) {
18350   EVT VT = N->getValueType(0);
18351
18352   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18353       (!Subtarget->hasInt256() ||
18354        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18355     return SDValue();
18356
18357   SDValue Amt = N->getOperand(1);
18358   SDLoc DL(N);
18359   if (isSplatVector(Amt.getNode())) {
18360     SDValue SclrAmt = Amt->getOperand(0);
18361     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18362       APInt ShiftAmt = C->getAPIntValue();
18363       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18364
18365       // SSE2/AVX2 logical shifts always return a vector of 0s
18366       // if the shift amount is bigger than or equal to
18367       // the element size. The constant shift amount will be
18368       // encoded as a 8-bit immediate.
18369       if (ShiftAmt.trunc(8).uge(MaxAmount))
18370         return getZeroVector(VT, Subtarget, DAG, DL);
18371     }
18372   }
18373
18374   return SDValue();
18375 }
18376
18377 /// PerformShiftCombine - Combine shifts.
18378 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18379                                    TargetLowering::DAGCombinerInfo &DCI,
18380                                    const X86Subtarget *Subtarget) {
18381   if (N->getOpcode() == ISD::SHL) {
18382     SDValue V = PerformSHLCombine(N, DAG);
18383     if (V.getNode()) return V;
18384   }
18385
18386   if (N->getOpcode() != ISD::SRA) {
18387     // Try to fold this logical shift into a zero vector.
18388     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18389     if (V.getNode()) return V;
18390   }
18391
18392   return SDValue();
18393 }
18394
18395 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18396 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18397 // and friends.  Likewise for OR -> CMPNEQSS.
18398 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18399                             TargetLowering::DAGCombinerInfo &DCI,
18400                             const X86Subtarget *Subtarget) {
18401   unsigned opcode;
18402
18403   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18404   // we're requiring SSE2 for both.
18405   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18406     SDValue N0 = N->getOperand(0);
18407     SDValue N1 = N->getOperand(1);
18408     SDValue CMP0 = N0->getOperand(1);
18409     SDValue CMP1 = N1->getOperand(1);
18410     SDLoc DL(N);
18411
18412     // The SETCCs should both refer to the same CMP.
18413     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18414       return SDValue();
18415
18416     SDValue CMP00 = CMP0->getOperand(0);
18417     SDValue CMP01 = CMP0->getOperand(1);
18418     EVT     VT    = CMP00.getValueType();
18419
18420     if (VT == MVT::f32 || VT == MVT::f64) {
18421       bool ExpectingFlags = false;
18422       // Check for any users that want flags:
18423       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18424            !ExpectingFlags && UI != UE; ++UI)
18425         switch (UI->getOpcode()) {
18426         default:
18427         case ISD::BR_CC:
18428         case ISD::BRCOND:
18429         case ISD::SELECT:
18430           ExpectingFlags = true;
18431           break;
18432         case ISD::CopyToReg:
18433         case ISD::SIGN_EXTEND:
18434         case ISD::ZERO_EXTEND:
18435         case ISD::ANY_EXTEND:
18436           break;
18437         }
18438
18439       if (!ExpectingFlags) {
18440         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18441         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18442
18443         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18444           X86::CondCode tmp = cc0;
18445           cc0 = cc1;
18446           cc1 = tmp;
18447         }
18448
18449         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18450             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18451           // FIXME: need symbolic constants for these magic numbers.
18452           // See X86ATTInstPrinter.cpp:printSSECC().
18453           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18454           if (Subtarget->hasAVX512()) {
18455             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18456                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18457             if (N->getValueType(0) != MVT::i1)
18458               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18459                                  FSetCC);
18460             return FSetCC;
18461           }
18462           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18463                                               CMP00.getValueType(), CMP00, CMP01,
18464                                               DAG.getConstant(x86cc, MVT::i8));
18465
18466           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18467           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18468
18469           if (is64BitFP && !Subtarget->is64Bit()) {
18470             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18471             // 64-bit integer, since that's not a legal type. Since
18472             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18473             // bits, but can do this little dance to extract the lowest 32 bits
18474             // and work with those going forward.
18475             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18476                                            OnesOrZeroesF);
18477             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18478                                            Vector64);
18479             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18480                                         Vector32, DAG.getIntPtrConstant(0));
18481             IntVT = MVT::i32;
18482           }
18483
18484           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18485           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18486                                       DAG.getConstant(1, IntVT));
18487           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18488           return OneBitOfTruth;
18489         }
18490       }
18491     }
18492   }
18493   return SDValue();
18494 }
18495
18496 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18497 /// so it can be folded inside ANDNP.
18498 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18499   EVT VT = N->getValueType(0);
18500
18501   // Match direct AllOnes for 128 and 256-bit vectors
18502   if (ISD::isBuildVectorAllOnes(N))
18503     return true;
18504
18505   // Look through a bit convert.
18506   if (N->getOpcode() == ISD::BITCAST)
18507     N = N->getOperand(0).getNode();
18508
18509   // Sometimes the operand may come from a insert_subvector building a 256-bit
18510   // allones vector
18511   if (VT.is256BitVector() &&
18512       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18513     SDValue V1 = N->getOperand(0);
18514     SDValue V2 = N->getOperand(1);
18515
18516     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18517         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18518         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18519         ISD::isBuildVectorAllOnes(V2.getNode()))
18520       return true;
18521   }
18522
18523   return false;
18524 }
18525
18526 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18527 // register. In most cases we actually compare or select YMM-sized registers
18528 // and mixing the two types creates horrible code. This method optimizes
18529 // some of the transition sequences.
18530 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18531                                  TargetLowering::DAGCombinerInfo &DCI,
18532                                  const X86Subtarget *Subtarget) {
18533   EVT VT = N->getValueType(0);
18534   if (!VT.is256BitVector())
18535     return SDValue();
18536
18537   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18538           N->getOpcode() == ISD::ZERO_EXTEND ||
18539           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18540
18541   SDValue Narrow = N->getOperand(0);
18542   EVT NarrowVT = Narrow->getValueType(0);
18543   if (!NarrowVT.is128BitVector())
18544     return SDValue();
18545
18546   if (Narrow->getOpcode() != ISD::XOR &&
18547       Narrow->getOpcode() != ISD::AND &&
18548       Narrow->getOpcode() != ISD::OR)
18549     return SDValue();
18550
18551   SDValue N0  = Narrow->getOperand(0);
18552   SDValue N1  = Narrow->getOperand(1);
18553   SDLoc DL(Narrow);
18554
18555   // The Left side has to be a trunc.
18556   if (N0.getOpcode() != ISD::TRUNCATE)
18557     return SDValue();
18558
18559   // The type of the truncated inputs.
18560   EVT WideVT = N0->getOperand(0)->getValueType(0);
18561   if (WideVT != VT)
18562     return SDValue();
18563
18564   // The right side has to be a 'trunc' or a constant vector.
18565   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18566   bool RHSConst = (isSplatVector(N1.getNode()) &&
18567                    isa<ConstantSDNode>(N1->getOperand(0)));
18568   if (!RHSTrunc && !RHSConst)
18569     return SDValue();
18570
18571   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18572
18573   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18574     return SDValue();
18575
18576   // Set N0 and N1 to hold the inputs to the new wide operation.
18577   N0 = N0->getOperand(0);
18578   if (RHSConst) {
18579     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18580                      N1->getOperand(0));
18581     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18582     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18583   } else if (RHSTrunc) {
18584     N1 = N1->getOperand(0);
18585   }
18586
18587   // Generate the wide operation.
18588   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18589   unsigned Opcode = N->getOpcode();
18590   switch (Opcode) {
18591   case ISD::ANY_EXTEND:
18592     return Op;
18593   case ISD::ZERO_EXTEND: {
18594     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18595     APInt Mask = APInt::getAllOnesValue(InBits);
18596     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18597     return DAG.getNode(ISD::AND, DL, VT,
18598                        Op, DAG.getConstant(Mask, VT));
18599   }
18600   case ISD::SIGN_EXTEND:
18601     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18602                        Op, DAG.getValueType(NarrowVT));
18603   default:
18604     llvm_unreachable("Unexpected opcode");
18605   }
18606 }
18607
18608 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18609                                  TargetLowering::DAGCombinerInfo &DCI,
18610                                  const X86Subtarget *Subtarget) {
18611   EVT VT = N->getValueType(0);
18612   if (DCI.isBeforeLegalizeOps())
18613     return SDValue();
18614
18615   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18616   if (R.getNode())
18617     return R;
18618
18619   // Create BEXTR instructions
18620   // BEXTR is ((X >> imm) & (2**size-1))
18621   if (VT == MVT::i32 || VT == MVT::i64) {
18622     SDValue N0 = N->getOperand(0);
18623     SDValue N1 = N->getOperand(1);
18624     SDLoc DL(N);
18625
18626     // Check for BEXTR.
18627     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18628         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18629       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18630       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18631       if (MaskNode && ShiftNode) {
18632         uint64_t Mask = MaskNode->getZExtValue();
18633         uint64_t Shift = ShiftNode->getZExtValue();
18634         if (isMask_64(Mask)) {
18635           uint64_t MaskSize = CountPopulation_64(Mask);
18636           if (Shift + MaskSize <= VT.getSizeInBits())
18637             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18638                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18639         }
18640       }
18641     } // BEXTR
18642
18643     return SDValue();
18644   }
18645
18646   // Want to form ANDNP nodes:
18647   // 1) In the hopes of then easily combining them with OR and AND nodes
18648   //    to form PBLEND/PSIGN.
18649   // 2) To match ANDN packed intrinsics
18650   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18651     return SDValue();
18652
18653   SDValue N0 = N->getOperand(0);
18654   SDValue N1 = N->getOperand(1);
18655   SDLoc DL(N);
18656
18657   // Check LHS for vnot
18658   if (N0.getOpcode() == ISD::XOR &&
18659       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18660       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18661     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18662
18663   // Check RHS for vnot
18664   if (N1.getOpcode() == ISD::XOR &&
18665       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18666       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18667     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18668
18669   return SDValue();
18670 }
18671
18672 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18673                                 TargetLowering::DAGCombinerInfo &DCI,
18674                                 const X86Subtarget *Subtarget) {
18675   if (DCI.isBeforeLegalizeOps())
18676     return SDValue();
18677
18678   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18679   if (R.getNode())
18680     return R;
18681
18682   SDValue N0 = N->getOperand(0);
18683   SDValue N1 = N->getOperand(1);
18684   EVT VT = N->getValueType(0);
18685
18686   // look for psign/blend
18687   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18688     if (!Subtarget->hasSSSE3() ||
18689         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18690       return SDValue();
18691
18692     // Canonicalize pandn to RHS
18693     if (N0.getOpcode() == X86ISD::ANDNP)
18694       std::swap(N0, N1);
18695     // or (and (m, y), (pandn m, x))
18696     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18697       SDValue Mask = N1.getOperand(0);
18698       SDValue X    = N1.getOperand(1);
18699       SDValue Y;
18700       if (N0.getOperand(0) == Mask)
18701         Y = N0.getOperand(1);
18702       if (N0.getOperand(1) == Mask)
18703         Y = N0.getOperand(0);
18704
18705       // Check to see if the mask appeared in both the AND and ANDNP and
18706       if (!Y.getNode())
18707         return SDValue();
18708
18709       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18710       // Look through mask bitcast.
18711       if (Mask.getOpcode() == ISD::BITCAST)
18712         Mask = Mask.getOperand(0);
18713       if (X.getOpcode() == ISD::BITCAST)
18714         X = X.getOperand(0);
18715       if (Y.getOpcode() == ISD::BITCAST)
18716         Y = Y.getOperand(0);
18717
18718       EVT MaskVT = Mask.getValueType();
18719
18720       // Validate that the Mask operand is a vector sra node.
18721       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18722       // there is no psrai.b
18723       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18724       unsigned SraAmt = ~0;
18725       if (Mask.getOpcode() == ISD::SRA) {
18726         SDValue Amt = Mask.getOperand(1);
18727         if (isSplatVector(Amt.getNode())) {
18728           SDValue SclrAmt = Amt->getOperand(0);
18729           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18730             SraAmt = C->getZExtValue();
18731         }
18732       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18733         SDValue SraC = Mask.getOperand(1);
18734         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18735       }
18736       if ((SraAmt + 1) != EltBits)
18737         return SDValue();
18738
18739       SDLoc DL(N);
18740
18741       // Now we know we at least have a plendvb with the mask val.  See if
18742       // we can form a psignb/w/d.
18743       // psign = x.type == y.type == mask.type && y = sub(0, x);
18744       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18745           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18746           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18747         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18748                "Unsupported VT for PSIGN");
18749         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18750         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18751       }
18752       // PBLENDVB only available on SSE 4.1
18753       if (!Subtarget->hasSSE41())
18754         return SDValue();
18755
18756       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18757
18758       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18759       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18760       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18761       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18762       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18763     }
18764   }
18765
18766   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18767     return SDValue();
18768
18769   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18770   MachineFunction &MF = DAG.getMachineFunction();
18771   bool OptForSize = MF.getFunction()->getAttributes().
18772     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18773
18774   // SHLD/SHRD instructions have lower register pressure, but on some
18775   // platforms they have higher latency than the equivalent
18776   // series of shifts/or that would otherwise be generated.
18777   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18778   // have higher latencies and we are not optimizing for size.
18779   if (!OptForSize && Subtarget->isSHLDSlow())
18780     return SDValue();
18781
18782   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18783     std::swap(N0, N1);
18784   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18785     return SDValue();
18786   if (!N0.hasOneUse() || !N1.hasOneUse())
18787     return SDValue();
18788
18789   SDValue ShAmt0 = N0.getOperand(1);
18790   if (ShAmt0.getValueType() != MVT::i8)
18791     return SDValue();
18792   SDValue ShAmt1 = N1.getOperand(1);
18793   if (ShAmt1.getValueType() != MVT::i8)
18794     return SDValue();
18795   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18796     ShAmt0 = ShAmt0.getOperand(0);
18797   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18798     ShAmt1 = ShAmt1.getOperand(0);
18799
18800   SDLoc DL(N);
18801   unsigned Opc = X86ISD::SHLD;
18802   SDValue Op0 = N0.getOperand(0);
18803   SDValue Op1 = N1.getOperand(0);
18804   if (ShAmt0.getOpcode() == ISD::SUB) {
18805     Opc = X86ISD::SHRD;
18806     std::swap(Op0, Op1);
18807     std::swap(ShAmt0, ShAmt1);
18808   }
18809
18810   unsigned Bits = VT.getSizeInBits();
18811   if (ShAmt1.getOpcode() == ISD::SUB) {
18812     SDValue Sum = ShAmt1.getOperand(0);
18813     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18814       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18815       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18816         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18817       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18818         return DAG.getNode(Opc, DL, VT,
18819                            Op0, Op1,
18820                            DAG.getNode(ISD::TRUNCATE, DL,
18821                                        MVT::i8, ShAmt0));
18822     }
18823   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18824     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18825     if (ShAmt0C &&
18826         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18827       return DAG.getNode(Opc, DL, VT,
18828                          N0.getOperand(0), N1.getOperand(0),
18829                          DAG.getNode(ISD::TRUNCATE, DL,
18830                                        MVT::i8, ShAmt0));
18831   }
18832
18833   return SDValue();
18834 }
18835
18836 // Generate NEG and CMOV for integer abs.
18837 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18838   EVT VT = N->getValueType(0);
18839
18840   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18841   // 8-bit integer abs to NEG and CMOV.
18842   if (VT.isInteger() && VT.getSizeInBits() == 8)
18843     return SDValue();
18844
18845   SDValue N0 = N->getOperand(0);
18846   SDValue N1 = N->getOperand(1);
18847   SDLoc DL(N);
18848
18849   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18850   // and change it to SUB and CMOV.
18851   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18852       N0.getOpcode() == ISD::ADD &&
18853       N0.getOperand(1) == N1 &&
18854       N1.getOpcode() == ISD::SRA &&
18855       N1.getOperand(0) == N0.getOperand(0))
18856     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18857       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18858         // Generate SUB & CMOV.
18859         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18860                                   DAG.getConstant(0, VT), N0.getOperand(0));
18861
18862         SDValue Ops[] = { N0.getOperand(0), Neg,
18863                           DAG.getConstant(X86::COND_GE, MVT::i8),
18864                           SDValue(Neg.getNode(), 1) };
18865         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
18866       }
18867   return SDValue();
18868 }
18869
18870 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18871 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18872                                  TargetLowering::DAGCombinerInfo &DCI,
18873                                  const X86Subtarget *Subtarget) {
18874   if (DCI.isBeforeLegalizeOps())
18875     return SDValue();
18876
18877   if (Subtarget->hasCMov()) {
18878     SDValue RV = performIntegerAbsCombine(N, DAG);
18879     if (RV.getNode())
18880       return RV;
18881   }
18882
18883   return SDValue();
18884 }
18885
18886 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18887 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18888                                   TargetLowering::DAGCombinerInfo &DCI,
18889                                   const X86Subtarget *Subtarget) {
18890   LoadSDNode *Ld = cast<LoadSDNode>(N);
18891   EVT RegVT = Ld->getValueType(0);
18892   EVT MemVT = Ld->getMemoryVT();
18893   SDLoc dl(Ld);
18894   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18895   unsigned RegSz = RegVT.getSizeInBits();
18896
18897   // On Sandybridge unaligned 256bit loads are inefficient.
18898   ISD::LoadExtType Ext = Ld->getExtensionType();
18899   unsigned Alignment = Ld->getAlignment();
18900   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18901   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18902       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18903     unsigned NumElems = RegVT.getVectorNumElements();
18904     if (NumElems < 2)
18905       return SDValue();
18906
18907     SDValue Ptr = Ld->getBasePtr();
18908     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18909
18910     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18911                                   NumElems/2);
18912     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18913                                 Ld->getPointerInfo(), Ld->isVolatile(),
18914                                 Ld->isNonTemporal(), Ld->isInvariant(),
18915                                 Alignment);
18916     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18917     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18918                                 Ld->getPointerInfo(), Ld->isVolatile(),
18919                                 Ld->isNonTemporal(), Ld->isInvariant(),
18920                                 std::min(16U, Alignment));
18921     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18922                              Load1.getValue(1),
18923                              Load2.getValue(1));
18924
18925     SDValue NewVec = DAG.getUNDEF(RegVT);
18926     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18927     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18928     return DCI.CombineTo(N, NewVec, TF, true);
18929   }
18930
18931   // If this is a vector EXT Load then attempt to optimize it using a
18932   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18933   // expansion is still better than scalar code.
18934   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18935   // emit a shuffle and a arithmetic shift.
18936   // TODO: It is possible to support ZExt by zeroing the undef values
18937   // during the shuffle phase or after the shuffle.
18938   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18939       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18940     assert(MemVT != RegVT && "Cannot extend to the same type");
18941     assert(MemVT.isVector() && "Must load a vector from memory");
18942
18943     unsigned NumElems = RegVT.getVectorNumElements();
18944     unsigned MemSz = MemVT.getSizeInBits();
18945     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18946
18947     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18948       return SDValue();
18949
18950     // All sizes must be a power of two.
18951     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18952       return SDValue();
18953
18954     // Attempt to load the original value using scalar loads.
18955     // Find the largest scalar type that divides the total loaded size.
18956     MVT SclrLoadTy = MVT::i8;
18957     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18958          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18959       MVT Tp = (MVT::SimpleValueType)tp;
18960       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18961         SclrLoadTy = Tp;
18962       }
18963     }
18964
18965     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18966     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18967         (64 <= MemSz))
18968       SclrLoadTy = MVT::f64;
18969
18970     // Calculate the number of scalar loads that we need to perform
18971     // in order to load our vector from memory.
18972     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18973     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18974       return SDValue();
18975
18976     unsigned loadRegZize = RegSz;
18977     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18978       loadRegZize /= 2;
18979
18980     // Represent our vector as a sequence of elements which are the
18981     // largest scalar that we can load.
18982     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18983       loadRegZize/SclrLoadTy.getSizeInBits());
18984
18985     // Represent the data using the same element type that is stored in
18986     // memory. In practice, we ''widen'' MemVT.
18987     EVT WideVecVT =
18988           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18989                        loadRegZize/MemVT.getScalarType().getSizeInBits());
18990
18991     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
18992       "Invalid vector type");
18993
18994     // We can't shuffle using an illegal type.
18995     if (!TLI.isTypeLegal(WideVecVT))
18996       return SDValue();
18997
18998     SmallVector<SDValue, 8> Chains;
18999     SDValue Ptr = Ld->getBasePtr();
19000     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19001                                         TLI.getPointerTy());
19002     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19003
19004     for (unsigned i = 0; i < NumLoads; ++i) {
19005       // Perform a single load.
19006       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19007                                        Ptr, Ld->getPointerInfo(),
19008                                        Ld->isVolatile(), Ld->isNonTemporal(),
19009                                        Ld->isInvariant(), Ld->getAlignment());
19010       Chains.push_back(ScalarLoad.getValue(1));
19011       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19012       // another round of DAGCombining.
19013       if (i == 0)
19014         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19015       else
19016         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19017                           ScalarLoad, DAG.getIntPtrConstant(i));
19018
19019       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19020     }
19021
19022     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19023
19024     // Bitcast the loaded value to a vector of the original element type, in
19025     // the size of the target vector type.
19026     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19027     unsigned SizeRatio = RegSz/MemSz;
19028
19029     if (Ext == ISD::SEXTLOAD) {
19030       // If we have SSE4.1 we can directly emit a VSEXT node.
19031       if (Subtarget->hasSSE41()) {
19032         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19033         return DCI.CombineTo(N, Sext, TF, true);
19034       }
19035
19036       // Otherwise we'll shuffle the small elements in the high bits of the
19037       // larger type and perform an arithmetic shift. If the shift is not legal
19038       // it's better to scalarize.
19039       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19040         return SDValue();
19041
19042       // Redistribute the loaded elements into the different locations.
19043       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19044       for (unsigned i = 0; i != NumElems; ++i)
19045         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19046
19047       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19048                                            DAG.getUNDEF(WideVecVT),
19049                                            &ShuffleVec[0]);
19050
19051       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19052
19053       // Build the arithmetic shift.
19054       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19055                      MemVT.getVectorElementType().getSizeInBits();
19056       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19057                           DAG.getConstant(Amt, RegVT));
19058
19059       return DCI.CombineTo(N, Shuff, TF, true);
19060     }
19061
19062     // Redistribute the loaded elements into the different locations.
19063     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19064     for (unsigned i = 0; i != NumElems; ++i)
19065       ShuffleVec[i*SizeRatio] = i;
19066
19067     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19068                                          DAG.getUNDEF(WideVecVT),
19069                                          &ShuffleVec[0]);
19070
19071     // Bitcast to the requested type.
19072     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19073     // Replace the original load with the new sequence
19074     // and return the new chain.
19075     return DCI.CombineTo(N, Shuff, TF, true);
19076   }
19077
19078   return SDValue();
19079 }
19080
19081 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19082 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19083                                    const X86Subtarget *Subtarget) {
19084   StoreSDNode *St = cast<StoreSDNode>(N);
19085   EVT VT = St->getValue().getValueType();
19086   EVT StVT = St->getMemoryVT();
19087   SDLoc dl(St);
19088   SDValue StoredVal = St->getOperand(1);
19089   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19090
19091   // If we are saving a concatenation of two XMM registers, perform two stores.
19092   // On Sandy Bridge, 256-bit memory operations are executed by two
19093   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19094   // memory  operation.
19095   unsigned Alignment = St->getAlignment();
19096   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19097   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19098       StVT == VT && !IsAligned) {
19099     unsigned NumElems = VT.getVectorNumElements();
19100     if (NumElems < 2)
19101       return SDValue();
19102
19103     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19104     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19105
19106     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19107     SDValue Ptr0 = St->getBasePtr();
19108     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19109
19110     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19111                                 St->getPointerInfo(), St->isVolatile(),
19112                                 St->isNonTemporal(), Alignment);
19113     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19114                                 St->getPointerInfo(), St->isVolatile(),
19115                                 St->isNonTemporal(),
19116                                 std::min(16U, Alignment));
19117     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19118   }
19119
19120   // Optimize trunc store (of multiple scalars) to shuffle and store.
19121   // First, pack all of the elements in one place. Next, store to memory
19122   // in fewer chunks.
19123   if (St->isTruncatingStore() && VT.isVector()) {
19124     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19125     unsigned NumElems = VT.getVectorNumElements();
19126     assert(StVT != VT && "Cannot truncate to the same type");
19127     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19128     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19129
19130     // From, To sizes and ElemCount must be pow of two
19131     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19132     // We are going to use the original vector elt for storing.
19133     // Accumulated smaller vector elements must be a multiple of the store size.
19134     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19135
19136     unsigned SizeRatio  = FromSz / ToSz;
19137
19138     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19139
19140     // Create a type on which we perform the shuffle
19141     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19142             StVT.getScalarType(), NumElems*SizeRatio);
19143
19144     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19145
19146     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19147     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19148     for (unsigned i = 0; i != NumElems; ++i)
19149       ShuffleVec[i] = i * SizeRatio;
19150
19151     // Can't shuffle using an illegal type.
19152     if (!TLI.isTypeLegal(WideVecVT))
19153       return SDValue();
19154
19155     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19156                                          DAG.getUNDEF(WideVecVT),
19157                                          &ShuffleVec[0]);
19158     // At this point all of the data is stored at the bottom of the
19159     // register. We now need to save it to mem.
19160
19161     // Find the largest store unit
19162     MVT StoreType = MVT::i8;
19163     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19164          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19165       MVT Tp = (MVT::SimpleValueType)tp;
19166       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19167         StoreType = Tp;
19168     }
19169
19170     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19171     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19172         (64 <= NumElems * ToSz))
19173       StoreType = MVT::f64;
19174
19175     // Bitcast the original vector into a vector of store-size units
19176     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19177             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19178     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19179     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19180     SmallVector<SDValue, 8> Chains;
19181     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19182                                         TLI.getPointerTy());
19183     SDValue Ptr = St->getBasePtr();
19184
19185     // Perform one or more big stores into memory.
19186     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19187       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19188                                    StoreType, ShuffWide,
19189                                    DAG.getIntPtrConstant(i));
19190       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19191                                 St->getPointerInfo(), St->isVolatile(),
19192                                 St->isNonTemporal(), St->getAlignment());
19193       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19194       Chains.push_back(Ch);
19195     }
19196
19197     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19198   }
19199
19200   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19201   // the FP state in cases where an emms may be missing.
19202   // A preferable solution to the general problem is to figure out the right
19203   // places to insert EMMS.  This qualifies as a quick hack.
19204
19205   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19206   if (VT.getSizeInBits() != 64)
19207     return SDValue();
19208
19209   const Function *F = DAG.getMachineFunction().getFunction();
19210   bool NoImplicitFloatOps = F->getAttributes().
19211     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19212   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19213                      && Subtarget->hasSSE2();
19214   if ((VT.isVector() ||
19215        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19216       isa<LoadSDNode>(St->getValue()) &&
19217       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19218       St->getChain().hasOneUse() && !St->isVolatile()) {
19219     SDNode* LdVal = St->getValue().getNode();
19220     LoadSDNode *Ld = nullptr;
19221     int TokenFactorIndex = -1;
19222     SmallVector<SDValue, 8> Ops;
19223     SDNode* ChainVal = St->getChain().getNode();
19224     // Must be a store of a load.  We currently handle two cases:  the load
19225     // is a direct child, and it's under an intervening TokenFactor.  It is
19226     // possible to dig deeper under nested TokenFactors.
19227     if (ChainVal == LdVal)
19228       Ld = cast<LoadSDNode>(St->getChain());
19229     else if (St->getValue().hasOneUse() &&
19230              ChainVal->getOpcode() == ISD::TokenFactor) {
19231       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19232         if (ChainVal->getOperand(i).getNode() == LdVal) {
19233           TokenFactorIndex = i;
19234           Ld = cast<LoadSDNode>(St->getValue());
19235         } else
19236           Ops.push_back(ChainVal->getOperand(i));
19237       }
19238     }
19239
19240     if (!Ld || !ISD::isNormalLoad(Ld))
19241       return SDValue();
19242
19243     // If this is not the MMX case, i.e. we are just turning i64 load/store
19244     // into f64 load/store, avoid the transformation if there are multiple
19245     // uses of the loaded value.
19246     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19247       return SDValue();
19248
19249     SDLoc LdDL(Ld);
19250     SDLoc StDL(N);
19251     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19252     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19253     // pair instead.
19254     if (Subtarget->is64Bit() || F64IsLegal) {
19255       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19256       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19257                                   Ld->getPointerInfo(), Ld->isVolatile(),
19258                                   Ld->isNonTemporal(), Ld->isInvariant(),
19259                                   Ld->getAlignment());
19260       SDValue NewChain = NewLd.getValue(1);
19261       if (TokenFactorIndex != -1) {
19262         Ops.push_back(NewChain);
19263         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19264       }
19265       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19266                           St->getPointerInfo(),
19267                           St->isVolatile(), St->isNonTemporal(),
19268                           St->getAlignment());
19269     }
19270
19271     // Otherwise, lower to two pairs of 32-bit loads / stores.
19272     SDValue LoAddr = Ld->getBasePtr();
19273     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19274                                  DAG.getConstant(4, MVT::i32));
19275
19276     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19277                                Ld->getPointerInfo(),
19278                                Ld->isVolatile(), Ld->isNonTemporal(),
19279                                Ld->isInvariant(), Ld->getAlignment());
19280     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19281                                Ld->getPointerInfo().getWithOffset(4),
19282                                Ld->isVolatile(), Ld->isNonTemporal(),
19283                                Ld->isInvariant(),
19284                                MinAlign(Ld->getAlignment(), 4));
19285
19286     SDValue NewChain = LoLd.getValue(1);
19287     if (TokenFactorIndex != -1) {
19288       Ops.push_back(LoLd);
19289       Ops.push_back(HiLd);
19290       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19291     }
19292
19293     LoAddr = St->getBasePtr();
19294     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19295                          DAG.getConstant(4, MVT::i32));
19296
19297     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19298                                 St->getPointerInfo(),
19299                                 St->isVolatile(), St->isNonTemporal(),
19300                                 St->getAlignment());
19301     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19302                                 St->getPointerInfo().getWithOffset(4),
19303                                 St->isVolatile(),
19304                                 St->isNonTemporal(),
19305                                 MinAlign(St->getAlignment(), 4));
19306     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19307   }
19308   return SDValue();
19309 }
19310
19311 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19312 /// and return the operands for the horizontal operation in LHS and RHS.  A
19313 /// horizontal operation performs the binary operation on successive elements
19314 /// of its first operand, then on successive elements of its second operand,
19315 /// returning the resulting values in a vector.  For example, if
19316 ///   A = < float a0, float a1, float a2, float a3 >
19317 /// and
19318 ///   B = < float b0, float b1, float b2, float b3 >
19319 /// then the result of doing a horizontal operation on A and B is
19320 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19321 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19322 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19323 /// set to A, RHS to B, and the routine returns 'true'.
19324 /// Note that the binary operation should have the property that if one of the
19325 /// operands is UNDEF then the result is UNDEF.
19326 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19327   // Look for the following pattern: if
19328   //   A = < float a0, float a1, float a2, float a3 >
19329   //   B = < float b0, float b1, float b2, float b3 >
19330   // and
19331   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19332   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19333   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19334   // which is A horizontal-op B.
19335
19336   // At least one of the operands should be a vector shuffle.
19337   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19338       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19339     return false;
19340
19341   MVT VT = LHS.getSimpleValueType();
19342
19343   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19344          "Unsupported vector type for horizontal add/sub");
19345
19346   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19347   // operate independently on 128-bit lanes.
19348   unsigned NumElts = VT.getVectorNumElements();
19349   unsigned NumLanes = VT.getSizeInBits()/128;
19350   unsigned NumLaneElts = NumElts / NumLanes;
19351   assert((NumLaneElts % 2 == 0) &&
19352          "Vector type should have an even number of elements in each lane");
19353   unsigned HalfLaneElts = NumLaneElts/2;
19354
19355   // View LHS in the form
19356   //   LHS = VECTOR_SHUFFLE A, B, LMask
19357   // If LHS is not a shuffle then pretend it is the shuffle
19358   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19359   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19360   // type VT.
19361   SDValue A, B;
19362   SmallVector<int, 16> LMask(NumElts);
19363   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19364     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19365       A = LHS.getOperand(0);
19366     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19367       B = LHS.getOperand(1);
19368     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19369     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19370   } else {
19371     if (LHS.getOpcode() != ISD::UNDEF)
19372       A = LHS;
19373     for (unsigned i = 0; i != NumElts; ++i)
19374       LMask[i] = i;
19375   }
19376
19377   // Likewise, view RHS in the form
19378   //   RHS = VECTOR_SHUFFLE C, D, RMask
19379   SDValue C, D;
19380   SmallVector<int, 16> RMask(NumElts);
19381   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19382     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19383       C = RHS.getOperand(0);
19384     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19385       D = RHS.getOperand(1);
19386     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19387     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19388   } else {
19389     if (RHS.getOpcode() != ISD::UNDEF)
19390       C = RHS;
19391     for (unsigned i = 0; i != NumElts; ++i)
19392       RMask[i] = i;
19393   }
19394
19395   // Check that the shuffles are both shuffling the same vectors.
19396   if (!(A == C && B == D) && !(A == D && B == C))
19397     return false;
19398
19399   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19400   if (!A.getNode() && !B.getNode())
19401     return false;
19402
19403   // If A and B occur in reverse order in RHS, then "swap" them (which means
19404   // rewriting the mask).
19405   if (A != C)
19406     CommuteVectorShuffleMask(RMask, NumElts);
19407
19408   // At this point LHS and RHS are equivalent to
19409   //   LHS = VECTOR_SHUFFLE A, B, LMask
19410   //   RHS = VECTOR_SHUFFLE A, B, RMask
19411   // Check that the masks correspond to performing a horizontal operation.
19412   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19413     for (unsigned i = 0; i != NumLaneElts; ++i) {
19414       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19415
19416       // Ignore any UNDEF components.
19417       if (LIdx < 0 || RIdx < 0 ||
19418           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19419           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19420         continue;
19421
19422       // Check that successive elements are being operated on.  If not, this is
19423       // not a horizontal operation.
19424       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19425       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19426       if (!(LIdx == Index && RIdx == Index + 1) &&
19427           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19428         return false;
19429     }
19430   }
19431
19432   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19433   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19434   return true;
19435 }
19436
19437 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19438 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
19439                                   const X86Subtarget *Subtarget) {
19440   EVT VT = N->getValueType(0);
19441   SDValue LHS = N->getOperand(0);
19442   SDValue RHS = N->getOperand(1);
19443
19444   // Try to synthesize horizontal adds from adds of shuffles.
19445   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19446        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19447       isHorizontalBinOp(LHS, RHS, true))
19448     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19449   return SDValue();
19450 }
19451
19452 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19453 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19454                                   const X86Subtarget *Subtarget) {
19455   EVT VT = N->getValueType(0);
19456   SDValue LHS = N->getOperand(0);
19457   SDValue RHS = N->getOperand(1);
19458
19459   // Try to synthesize horizontal subs from subs of shuffles.
19460   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19461        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19462       isHorizontalBinOp(LHS, RHS, false))
19463     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19464   return SDValue();
19465 }
19466
19467 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19468 /// X86ISD::FXOR nodes.
19469 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19470   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19471   // F[X]OR(0.0, x) -> x
19472   // F[X]OR(x, 0.0) -> x
19473   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19474     if (C->getValueAPF().isPosZero())
19475       return N->getOperand(1);
19476   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19477     if (C->getValueAPF().isPosZero())
19478       return N->getOperand(0);
19479   return SDValue();
19480 }
19481
19482 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19483 /// X86ISD::FMAX nodes.
19484 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19485   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19486
19487   // Only perform optimizations if UnsafeMath is used.
19488   if (!DAG.getTarget().Options.UnsafeFPMath)
19489     return SDValue();
19490
19491   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19492   // into FMINC and FMAXC, which are Commutative operations.
19493   unsigned NewOp = 0;
19494   switch (N->getOpcode()) {
19495     default: llvm_unreachable("unknown opcode");
19496     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19497     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19498   }
19499
19500   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19501                      N->getOperand(0), N->getOperand(1));
19502 }
19503
19504 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19505 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19506   // FAND(0.0, x) -> 0.0
19507   // FAND(x, 0.0) -> 0.0
19508   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19509     if (C->getValueAPF().isPosZero())
19510       return N->getOperand(0);
19511   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19512     if (C->getValueAPF().isPosZero())
19513       return N->getOperand(1);
19514   return SDValue();
19515 }
19516
19517 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19518 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19519   // FANDN(x, 0.0) -> 0.0
19520   // FANDN(0.0, x) -> x
19521   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19522     if (C->getValueAPF().isPosZero())
19523       return N->getOperand(1);
19524   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19525     if (C->getValueAPF().isPosZero())
19526       return N->getOperand(1);
19527   return SDValue();
19528 }
19529
19530 static SDValue PerformBTCombine(SDNode *N,
19531                                 SelectionDAG &DAG,
19532                                 TargetLowering::DAGCombinerInfo &DCI) {
19533   // BT ignores high bits in the bit index operand.
19534   SDValue Op1 = N->getOperand(1);
19535   if (Op1.hasOneUse()) {
19536     unsigned BitWidth = Op1.getValueSizeInBits();
19537     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19538     APInt KnownZero, KnownOne;
19539     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19540                                           !DCI.isBeforeLegalizeOps());
19541     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19542     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19543         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19544       DCI.CommitTargetLoweringOpt(TLO);
19545   }
19546   return SDValue();
19547 }
19548
19549 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19550   SDValue Op = N->getOperand(0);
19551   if (Op.getOpcode() == ISD::BITCAST)
19552     Op = Op.getOperand(0);
19553   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19554   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19555       VT.getVectorElementType().getSizeInBits() ==
19556       OpVT.getVectorElementType().getSizeInBits()) {
19557     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19558   }
19559   return SDValue();
19560 }
19561
19562 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19563                                                const X86Subtarget *Subtarget) {
19564   EVT VT = N->getValueType(0);
19565   if (!VT.isVector())
19566     return SDValue();
19567
19568   SDValue N0 = N->getOperand(0);
19569   SDValue N1 = N->getOperand(1);
19570   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19571   SDLoc dl(N);
19572
19573   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19574   // both SSE and AVX2 since there is no sign-extended shift right
19575   // operation on a vector with 64-bit elements.
19576   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19577   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19578   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19579       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19580     SDValue N00 = N0.getOperand(0);
19581
19582     // EXTLOAD has a better solution on AVX2,
19583     // it may be replaced with X86ISD::VSEXT node.
19584     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19585       if (!ISD::isNormalLoad(N00.getNode()))
19586         return SDValue();
19587
19588     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19589         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19590                                   N00, N1);
19591       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19592     }
19593   }
19594   return SDValue();
19595 }
19596
19597 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19598                                   TargetLowering::DAGCombinerInfo &DCI,
19599                                   const X86Subtarget *Subtarget) {
19600   if (!DCI.isBeforeLegalizeOps())
19601     return SDValue();
19602
19603   if (!Subtarget->hasFp256())
19604     return SDValue();
19605
19606   EVT VT = N->getValueType(0);
19607   if (VT.isVector() && VT.getSizeInBits() == 256) {
19608     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19609     if (R.getNode())
19610       return R;
19611   }
19612
19613   return SDValue();
19614 }
19615
19616 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19617                                  const X86Subtarget* Subtarget) {
19618   SDLoc dl(N);
19619   EVT VT = N->getValueType(0);
19620
19621   // Let legalize expand this if it isn't a legal type yet.
19622   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19623     return SDValue();
19624
19625   EVT ScalarVT = VT.getScalarType();
19626   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19627       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19628     return SDValue();
19629
19630   SDValue A = N->getOperand(0);
19631   SDValue B = N->getOperand(1);
19632   SDValue C = N->getOperand(2);
19633
19634   bool NegA = (A.getOpcode() == ISD::FNEG);
19635   bool NegB = (B.getOpcode() == ISD::FNEG);
19636   bool NegC = (C.getOpcode() == ISD::FNEG);
19637
19638   // Negative multiplication when NegA xor NegB
19639   bool NegMul = (NegA != NegB);
19640   if (NegA)
19641     A = A.getOperand(0);
19642   if (NegB)
19643     B = B.getOperand(0);
19644   if (NegC)
19645     C = C.getOperand(0);
19646
19647   unsigned Opcode;
19648   if (!NegMul)
19649     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19650   else
19651     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19652
19653   return DAG.getNode(Opcode, dl, VT, A, B, C);
19654 }
19655
19656 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19657                                   TargetLowering::DAGCombinerInfo &DCI,
19658                                   const X86Subtarget *Subtarget) {
19659   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19660   //           (and (i32 x86isd::setcc_carry), 1)
19661   // This eliminates the zext. This transformation is necessary because
19662   // ISD::SETCC is always legalized to i8.
19663   SDLoc dl(N);
19664   SDValue N0 = N->getOperand(0);
19665   EVT VT = N->getValueType(0);
19666
19667   if (N0.getOpcode() == ISD::AND &&
19668       N0.hasOneUse() &&
19669       N0.getOperand(0).hasOneUse()) {
19670     SDValue N00 = N0.getOperand(0);
19671     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19672       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19673       if (!C || C->getZExtValue() != 1)
19674         return SDValue();
19675       return DAG.getNode(ISD::AND, dl, VT,
19676                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19677                                      N00.getOperand(0), N00.getOperand(1)),
19678                          DAG.getConstant(1, VT));
19679     }
19680   }
19681
19682   if (N0.getOpcode() == ISD::TRUNCATE &&
19683       N0.hasOneUse() &&
19684       N0.getOperand(0).hasOneUse()) {
19685     SDValue N00 = N0.getOperand(0);
19686     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19687       return DAG.getNode(ISD::AND, dl, VT,
19688                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19689                                      N00.getOperand(0), N00.getOperand(1)),
19690                          DAG.getConstant(1, VT));
19691     }
19692   }
19693   if (VT.is256BitVector()) {
19694     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19695     if (R.getNode())
19696       return R;
19697   }
19698
19699   return SDValue();
19700 }
19701
19702 // Optimize x == -y --> x+y == 0
19703 //          x != -y --> x+y != 0
19704 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19705                                       const X86Subtarget* Subtarget) {
19706   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19707   SDValue LHS = N->getOperand(0);
19708   SDValue RHS = N->getOperand(1);
19709   EVT VT = N->getValueType(0);
19710   SDLoc DL(N);
19711
19712   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19713     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19714       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19715         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19716                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19717         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19718                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19719       }
19720   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19721     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19722       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19723         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19724                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19725         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19726                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19727       }
19728
19729   if (VT.getScalarType() == MVT::i1) {
19730     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19731       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19732     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19733     if (!IsSEXT0 && !IsVZero0)
19734       return SDValue();
19735     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19736       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19737     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19738
19739     if (!IsSEXT1 && !IsVZero1)
19740       return SDValue();
19741
19742     if (IsSEXT0 && IsVZero1) {
19743       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19744       if (CC == ISD::SETEQ)
19745         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19746       return LHS.getOperand(0);
19747     }
19748     if (IsSEXT1 && IsVZero0) {
19749       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19750       if (CC == ISD::SETEQ)
19751         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19752       return RHS.getOperand(0);
19753     }
19754   }
19755
19756   return SDValue();
19757 }
19758
19759 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19760 // as "sbb reg,reg", since it can be extended without zext and produces
19761 // an all-ones bit which is more useful than 0/1 in some cases.
19762 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19763                                MVT VT) {
19764   if (VT == MVT::i8)
19765     return DAG.getNode(ISD::AND, DL, VT,
19766                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19767                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19768                        DAG.getConstant(1, VT));
19769   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19770   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19771                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19772                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19773 }
19774
19775 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19776 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19777                                    TargetLowering::DAGCombinerInfo &DCI,
19778                                    const X86Subtarget *Subtarget) {
19779   SDLoc DL(N);
19780   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19781   SDValue EFLAGS = N->getOperand(1);
19782
19783   if (CC == X86::COND_A) {
19784     // Try to convert COND_A into COND_B in an attempt to facilitate
19785     // materializing "setb reg".
19786     //
19787     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19788     // cannot take an immediate as its first operand.
19789     //
19790     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19791         EFLAGS.getValueType().isInteger() &&
19792         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19793       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19794                                    EFLAGS.getNode()->getVTList(),
19795                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19796       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19797       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19798     }
19799   }
19800
19801   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19802   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19803   // cases.
19804   if (CC == X86::COND_B)
19805     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19806
19807   SDValue Flags;
19808
19809   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19810   if (Flags.getNode()) {
19811     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19812     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19813   }
19814
19815   return SDValue();
19816 }
19817
19818 // Optimize branch condition evaluation.
19819 //
19820 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19821                                     TargetLowering::DAGCombinerInfo &DCI,
19822                                     const X86Subtarget *Subtarget) {
19823   SDLoc DL(N);
19824   SDValue Chain = N->getOperand(0);
19825   SDValue Dest = N->getOperand(1);
19826   SDValue EFLAGS = N->getOperand(3);
19827   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19828
19829   SDValue Flags;
19830
19831   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19832   if (Flags.getNode()) {
19833     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19834     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19835                        Flags);
19836   }
19837
19838   return SDValue();
19839 }
19840
19841 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19842                                         const X86TargetLowering *XTLI) {
19843   SDValue Op0 = N->getOperand(0);
19844   EVT InVT = Op0->getValueType(0);
19845
19846   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19847   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19848     SDLoc dl(N);
19849     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19850     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19851     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19852   }
19853
19854   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19855   // a 32-bit target where SSE doesn't support i64->FP operations.
19856   if (Op0.getOpcode() == ISD::LOAD) {
19857     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19858     EVT VT = Ld->getValueType(0);
19859     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19860         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19861         !XTLI->getSubtarget()->is64Bit() &&
19862         VT == MVT::i64) {
19863       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19864                                           Ld->getChain(), Op0, DAG);
19865       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19866       return FILDChain;
19867     }
19868   }
19869   return SDValue();
19870 }
19871
19872 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19873 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19874                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19875   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19876   // the result is either zero or one (depending on the input carry bit).
19877   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19878   if (X86::isZeroNode(N->getOperand(0)) &&
19879       X86::isZeroNode(N->getOperand(1)) &&
19880       // We don't have a good way to replace an EFLAGS use, so only do this when
19881       // dead right now.
19882       SDValue(N, 1).use_empty()) {
19883     SDLoc DL(N);
19884     EVT VT = N->getValueType(0);
19885     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19886     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19887                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19888                                            DAG.getConstant(X86::COND_B,MVT::i8),
19889                                            N->getOperand(2)),
19890                                DAG.getConstant(1, VT));
19891     return DCI.CombineTo(N, Res1, CarryOut);
19892   }
19893
19894   return SDValue();
19895 }
19896
19897 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19898 //      (add Y, (setne X, 0)) -> sbb -1, Y
19899 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19900 //      (sub (setne X, 0), Y) -> adc -1, Y
19901 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19902   SDLoc DL(N);
19903
19904   // Look through ZExts.
19905   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19906   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19907     return SDValue();
19908
19909   SDValue SetCC = Ext.getOperand(0);
19910   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19911     return SDValue();
19912
19913   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19914   if (CC != X86::COND_E && CC != X86::COND_NE)
19915     return SDValue();
19916
19917   SDValue Cmp = SetCC.getOperand(1);
19918   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19919       !X86::isZeroNode(Cmp.getOperand(1)) ||
19920       !Cmp.getOperand(0).getValueType().isInteger())
19921     return SDValue();
19922
19923   SDValue CmpOp0 = Cmp.getOperand(0);
19924   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19925                                DAG.getConstant(1, CmpOp0.getValueType()));
19926
19927   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19928   if (CC == X86::COND_NE)
19929     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19930                        DL, OtherVal.getValueType(), OtherVal,
19931                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19932   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19933                      DL, OtherVal.getValueType(), OtherVal,
19934                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19935 }
19936
19937 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19938 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19939                                  const X86Subtarget *Subtarget) {
19940   EVT VT = N->getValueType(0);
19941   SDValue Op0 = N->getOperand(0);
19942   SDValue Op1 = N->getOperand(1);
19943
19944   // Try to synthesize horizontal adds from adds of shuffles.
19945   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19946        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19947       isHorizontalBinOp(Op0, Op1, true))
19948     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19949
19950   return OptimizeConditionalInDecrement(N, DAG);
19951 }
19952
19953 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19954                                  const X86Subtarget *Subtarget) {
19955   SDValue Op0 = N->getOperand(0);
19956   SDValue Op1 = N->getOperand(1);
19957
19958   // X86 can't encode an immediate LHS of a sub. See if we can push the
19959   // negation into a preceding instruction.
19960   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19961     // If the RHS of the sub is a XOR with one use and a constant, invert the
19962     // immediate. Then add one to the LHS of the sub so we can turn
19963     // X-Y -> X+~Y+1, saving one register.
19964     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19965         isa<ConstantSDNode>(Op1.getOperand(1))) {
19966       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19967       EVT VT = Op0.getValueType();
19968       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19969                                    Op1.getOperand(0),
19970                                    DAG.getConstant(~XorC, VT));
19971       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19972                          DAG.getConstant(C->getAPIntValue()+1, VT));
19973     }
19974   }
19975
19976   // Try to synthesize horizontal adds from adds of shuffles.
19977   EVT VT = N->getValueType(0);
19978   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19979        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19980       isHorizontalBinOp(Op0, Op1, true))
19981     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19982
19983   return OptimizeConditionalInDecrement(N, DAG);
19984 }
19985
19986 /// performVZEXTCombine - Performs build vector combines
19987 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
19988                                         TargetLowering::DAGCombinerInfo &DCI,
19989                                         const X86Subtarget *Subtarget) {
19990   // (vzext (bitcast (vzext (x)) -> (vzext x)
19991   SDValue In = N->getOperand(0);
19992   while (In.getOpcode() == ISD::BITCAST)
19993     In = In.getOperand(0);
19994
19995   if (In.getOpcode() != X86ISD::VZEXT)
19996     return SDValue();
19997
19998   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
19999                      In.getOperand(0));
20000 }
20001
20002 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20003                                              DAGCombinerInfo &DCI) const {
20004   SelectionDAG &DAG = DCI.DAG;
20005   switch (N->getOpcode()) {
20006   default: break;
20007   case ISD::EXTRACT_VECTOR_ELT:
20008     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20009   case ISD::VSELECT:
20010   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20011   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20012   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20013   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20014   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20015   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20016   case ISD::SHL:
20017   case ISD::SRA:
20018   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20019   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20020   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20021   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20022   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20023   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20024   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20025   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20026   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20027   case X86ISD::FXOR:
20028   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20029   case X86ISD::FMIN:
20030   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20031   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20032   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20033   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20034   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20035   case ISD::ANY_EXTEND:
20036   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20037   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20038   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20039   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20040   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20041   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20042   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20043   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20044   case X86ISD::SHUFP:       // Handle all target specific shuffles
20045   case X86ISD::PALIGNR:
20046   case X86ISD::UNPCKH:
20047   case X86ISD::UNPCKL:
20048   case X86ISD::MOVHLPS:
20049   case X86ISD::MOVLHPS:
20050   case X86ISD::PSHUFD:
20051   case X86ISD::PSHUFHW:
20052   case X86ISD::PSHUFLW:
20053   case X86ISD::MOVSS:
20054   case X86ISD::MOVSD:
20055   case X86ISD::VPERMILP:
20056   case X86ISD::VPERM2X128:
20057   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20058   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20059   }
20060
20061   return SDValue();
20062 }
20063
20064 /// isTypeDesirableForOp - Return true if the target has native support for
20065 /// the specified value type and it is 'desirable' to use the type for the
20066 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20067 /// instruction encodings are longer and some i16 instructions are slow.
20068 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20069   if (!isTypeLegal(VT))
20070     return false;
20071   if (VT != MVT::i16)
20072     return true;
20073
20074   switch (Opc) {
20075   default:
20076     return true;
20077   case ISD::LOAD:
20078   case ISD::SIGN_EXTEND:
20079   case ISD::ZERO_EXTEND:
20080   case ISD::ANY_EXTEND:
20081   case ISD::SHL:
20082   case ISD::SRL:
20083   case ISD::SUB:
20084   case ISD::ADD:
20085   case ISD::MUL:
20086   case ISD::AND:
20087   case ISD::OR:
20088   case ISD::XOR:
20089     return false;
20090   }
20091 }
20092
20093 /// IsDesirableToPromoteOp - This method query the target whether it is
20094 /// beneficial for dag combiner to promote the specified node. If true, it
20095 /// should return the desired promotion type by reference.
20096 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20097   EVT VT = Op.getValueType();
20098   if (VT != MVT::i16)
20099     return false;
20100
20101   bool Promote = false;
20102   bool Commute = false;
20103   switch (Op.getOpcode()) {
20104   default: break;
20105   case ISD::LOAD: {
20106     LoadSDNode *LD = cast<LoadSDNode>(Op);
20107     // If the non-extending load has a single use and it's not live out, then it
20108     // might be folded.
20109     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20110                                                      Op.hasOneUse()*/) {
20111       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20112              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20113         // The only case where we'd want to promote LOAD (rather then it being
20114         // promoted as an operand is when it's only use is liveout.
20115         if (UI->getOpcode() != ISD::CopyToReg)
20116           return false;
20117       }
20118     }
20119     Promote = true;
20120     break;
20121   }
20122   case ISD::SIGN_EXTEND:
20123   case ISD::ZERO_EXTEND:
20124   case ISD::ANY_EXTEND:
20125     Promote = true;
20126     break;
20127   case ISD::SHL:
20128   case ISD::SRL: {
20129     SDValue N0 = Op.getOperand(0);
20130     // Look out for (store (shl (load), x)).
20131     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20132       return false;
20133     Promote = true;
20134     break;
20135   }
20136   case ISD::ADD:
20137   case ISD::MUL:
20138   case ISD::AND:
20139   case ISD::OR:
20140   case ISD::XOR:
20141     Commute = true;
20142     // fallthrough
20143   case ISD::SUB: {
20144     SDValue N0 = Op.getOperand(0);
20145     SDValue N1 = Op.getOperand(1);
20146     if (!Commute && MayFoldLoad(N1))
20147       return false;
20148     // Avoid disabling potential load folding opportunities.
20149     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20150       return false;
20151     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20152       return false;
20153     Promote = true;
20154   }
20155   }
20156
20157   PVT = MVT::i32;
20158   return Promote;
20159 }
20160
20161 //===----------------------------------------------------------------------===//
20162 //                           X86 Inline Assembly Support
20163 //===----------------------------------------------------------------------===//
20164
20165 namespace {
20166   // Helper to match a string separated by whitespace.
20167   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20168     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20169
20170     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20171       StringRef piece(*args[i]);
20172       if (!s.startswith(piece)) // Check if the piece matches.
20173         return false;
20174
20175       s = s.substr(piece.size());
20176       StringRef::size_type pos = s.find_first_not_of(" \t");
20177       if (pos == 0) // We matched a prefix.
20178         return false;
20179
20180       s = s.substr(pos);
20181     }
20182
20183     return s.empty();
20184   }
20185   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20186 }
20187
20188 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20189
20190   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20191     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20192         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20193         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20194
20195       if (AsmPieces.size() == 3)
20196         return true;
20197       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20198         return true;
20199     }
20200   }
20201   return false;
20202 }
20203
20204 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20205   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20206
20207   std::string AsmStr = IA->getAsmString();
20208
20209   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20210   if (!Ty || Ty->getBitWidth() % 16 != 0)
20211     return false;
20212
20213   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20214   SmallVector<StringRef, 4> AsmPieces;
20215   SplitString(AsmStr, AsmPieces, ";\n");
20216
20217   switch (AsmPieces.size()) {
20218   default: return false;
20219   case 1:
20220     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20221     // we will turn this bswap into something that will be lowered to logical
20222     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20223     // lower so don't worry about this.
20224     // bswap $0
20225     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20226         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20227         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20228         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20229         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20230         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20231       // No need to check constraints, nothing other than the equivalent of
20232       // "=r,0" would be valid here.
20233       return IntrinsicLowering::LowerToByteSwap(CI);
20234     }
20235
20236     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20237     if (CI->getType()->isIntegerTy(16) &&
20238         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20239         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20240          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20241       AsmPieces.clear();
20242       const std::string &ConstraintsStr = IA->getConstraintString();
20243       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20244       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20245       if (clobbersFlagRegisters(AsmPieces))
20246         return IntrinsicLowering::LowerToByteSwap(CI);
20247     }
20248     break;
20249   case 3:
20250     if (CI->getType()->isIntegerTy(32) &&
20251         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20252         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20253         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20254         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20255       AsmPieces.clear();
20256       const std::string &ConstraintsStr = IA->getConstraintString();
20257       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20258       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20259       if (clobbersFlagRegisters(AsmPieces))
20260         return IntrinsicLowering::LowerToByteSwap(CI);
20261     }
20262
20263     if (CI->getType()->isIntegerTy(64)) {
20264       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20265       if (Constraints.size() >= 2 &&
20266           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20267           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20268         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20269         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20270             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20271             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20272           return IntrinsicLowering::LowerToByteSwap(CI);
20273       }
20274     }
20275     break;
20276   }
20277   return false;
20278 }
20279
20280 /// getConstraintType - Given a constraint letter, return the type of
20281 /// constraint it is for this target.
20282 X86TargetLowering::ConstraintType
20283 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20284   if (Constraint.size() == 1) {
20285     switch (Constraint[0]) {
20286     case 'R':
20287     case 'q':
20288     case 'Q':
20289     case 'f':
20290     case 't':
20291     case 'u':
20292     case 'y':
20293     case 'x':
20294     case 'Y':
20295     case 'l':
20296       return C_RegisterClass;
20297     case 'a':
20298     case 'b':
20299     case 'c':
20300     case 'd':
20301     case 'S':
20302     case 'D':
20303     case 'A':
20304       return C_Register;
20305     case 'I':
20306     case 'J':
20307     case 'K':
20308     case 'L':
20309     case 'M':
20310     case 'N':
20311     case 'G':
20312     case 'C':
20313     case 'e':
20314     case 'Z':
20315       return C_Other;
20316     default:
20317       break;
20318     }
20319   }
20320   return TargetLowering::getConstraintType(Constraint);
20321 }
20322
20323 /// Examine constraint type and operand type and determine a weight value.
20324 /// This object must already have been set up with the operand type
20325 /// and the current alternative constraint selected.
20326 TargetLowering::ConstraintWeight
20327   X86TargetLowering::getSingleConstraintMatchWeight(
20328     AsmOperandInfo &info, const char *constraint) const {
20329   ConstraintWeight weight = CW_Invalid;
20330   Value *CallOperandVal = info.CallOperandVal;
20331     // If we don't have a value, we can't do a match,
20332     // but allow it at the lowest weight.
20333   if (!CallOperandVal)
20334     return CW_Default;
20335   Type *type = CallOperandVal->getType();
20336   // Look at the constraint type.
20337   switch (*constraint) {
20338   default:
20339     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20340   case 'R':
20341   case 'q':
20342   case 'Q':
20343   case 'a':
20344   case 'b':
20345   case 'c':
20346   case 'd':
20347   case 'S':
20348   case 'D':
20349   case 'A':
20350     if (CallOperandVal->getType()->isIntegerTy())
20351       weight = CW_SpecificReg;
20352     break;
20353   case 'f':
20354   case 't':
20355   case 'u':
20356     if (type->isFloatingPointTy())
20357       weight = CW_SpecificReg;
20358     break;
20359   case 'y':
20360     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20361       weight = CW_SpecificReg;
20362     break;
20363   case 'x':
20364   case 'Y':
20365     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20366         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20367       weight = CW_Register;
20368     break;
20369   case 'I':
20370     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20371       if (C->getZExtValue() <= 31)
20372         weight = CW_Constant;
20373     }
20374     break;
20375   case 'J':
20376     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20377       if (C->getZExtValue() <= 63)
20378         weight = CW_Constant;
20379     }
20380     break;
20381   case 'K':
20382     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20383       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20384         weight = CW_Constant;
20385     }
20386     break;
20387   case 'L':
20388     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20389       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20390         weight = CW_Constant;
20391     }
20392     break;
20393   case 'M':
20394     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20395       if (C->getZExtValue() <= 3)
20396         weight = CW_Constant;
20397     }
20398     break;
20399   case 'N':
20400     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20401       if (C->getZExtValue() <= 0xff)
20402         weight = CW_Constant;
20403     }
20404     break;
20405   case 'G':
20406   case 'C':
20407     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20408       weight = CW_Constant;
20409     }
20410     break;
20411   case 'e':
20412     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20413       if ((C->getSExtValue() >= -0x80000000LL) &&
20414           (C->getSExtValue() <= 0x7fffffffLL))
20415         weight = CW_Constant;
20416     }
20417     break;
20418   case 'Z':
20419     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20420       if (C->getZExtValue() <= 0xffffffff)
20421         weight = CW_Constant;
20422     }
20423     break;
20424   }
20425   return weight;
20426 }
20427
20428 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20429 /// with another that has more specific requirements based on the type of the
20430 /// corresponding operand.
20431 const char *X86TargetLowering::
20432 LowerXConstraint(EVT ConstraintVT) const {
20433   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20434   // 'f' like normal targets.
20435   if (ConstraintVT.isFloatingPoint()) {
20436     if (Subtarget->hasSSE2())
20437       return "Y";
20438     if (Subtarget->hasSSE1())
20439       return "x";
20440   }
20441
20442   return TargetLowering::LowerXConstraint(ConstraintVT);
20443 }
20444
20445 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20446 /// vector.  If it is invalid, don't add anything to Ops.
20447 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20448                                                      std::string &Constraint,
20449                                                      std::vector<SDValue>&Ops,
20450                                                      SelectionDAG &DAG) const {
20451   SDValue Result;
20452
20453   // Only support length 1 constraints for now.
20454   if (Constraint.length() > 1) return;
20455
20456   char ConstraintLetter = Constraint[0];
20457   switch (ConstraintLetter) {
20458   default: break;
20459   case 'I':
20460     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20461       if (C->getZExtValue() <= 31) {
20462         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20463         break;
20464       }
20465     }
20466     return;
20467   case 'J':
20468     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20469       if (C->getZExtValue() <= 63) {
20470         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20471         break;
20472       }
20473     }
20474     return;
20475   case 'K':
20476     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20477       if (isInt<8>(C->getSExtValue())) {
20478         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20479         break;
20480       }
20481     }
20482     return;
20483   case 'N':
20484     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20485       if (C->getZExtValue() <= 255) {
20486         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20487         break;
20488       }
20489     }
20490     return;
20491   case 'e': {
20492     // 32-bit signed value
20493     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20494       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20495                                            C->getSExtValue())) {
20496         // Widen to 64 bits here to get it sign extended.
20497         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20498         break;
20499       }
20500     // FIXME gcc accepts some relocatable values here too, but only in certain
20501     // memory models; it's complicated.
20502     }
20503     return;
20504   }
20505   case 'Z': {
20506     // 32-bit unsigned value
20507     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20508       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20509                                            C->getZExtValue())) {
20510         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20511         break;
20512       }
20513     }
20514     // FIXME gcc accepts some relocatable values here too, but only in certain
20515     // memory models; it's complicated.
20516     return;
20517   }
20518   case 'i': {
20519     // Literal immediates are always ok.
20520     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20521       // Widen to 64 bits here to get it sign extended.
20522       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20523       break;
20524     }
20525
20526     // In any sort of PIC mode addresses need to be computed at runtime by
20527     // adding in a register or some sort of table lookup.  These can't
20528     // be used as immediates.
20529     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20530       return;
20531
20532     // If we are in non-pic codegen mode, we allow the address of a global (with
20533     // an optional displacement) to be used with 'i'.
20534     GlobalAddressSDNode *GA = nullptr;
20535     int64_t Offset = 0;
20536
20537     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20538     while (1) {
20539       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20540         Offset += GA->getOffset();
20541         break;
20542       } else if (Op.getOpcode() == ISD::ADD) {
20543         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20544           Offset += C->getZExtValue();
20545           Op = Op.getOperand(0);
20546           continue;
20547         }
20548       } else if (Op.getOpcode() == ISD::SUB) {
20549         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20550           Offset += -C->getZExtValue();
20551           Op = Op.getOperand(0);
20552           continue;
20553         }
20554       }
20555
20556       // Otherwise, this isn't something we can handle, reject it.
20557       return;
20558     }
20559
20560     const GlobalValue *GV = GA->getGlobal();
20561     // If we require an extra load to get this address, as in PIC mode, we
20562     // can't accept it.
20563     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20564                                                         getTargetMachine())))
20565       return;
20566
20567     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20568                                         GA->getValueType(0), Offset);
20569     break;
20570   }
20571   }
20572
20573   if (Result.getNode()) {
20574     Ops.push_back(Result);
20575     return;
20576   }
20577   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20578 }
20579
20580 std::pair<unsigned, const TargetRegisterClass*>
20581 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20582                                                 MVT VT) const {
20583   // First, see if this is a constraint that directly corresponds to an LLVM
20584   // register class.
20585   if (Constraint.size() == 1) {
20586     // GCC Constraint Letters
20587     switch (Constraint[0]) {
20588     default: break;
20589       // TODO: Slight differences here in allocation order and leaving
20590       // RIP in the class. Do they matter any more here than they do
20591       // in the normal allocation?
20592     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20593       if (Subtarget->is64Bit()) {
20594         if (VT == MVT::i32 || VT == MVT::f32)
20595           return std::make_pair(0U, &X86::GR32RegClass);
20596         if (VT == MVT::i16)
20597           return std::make_pair(0U, &X86::GR16RegClass);
20598         if (VT == MVT::i8 || VT == MVT::i1)
20599           return std::make_pair(0U, &X86::GR8RegClass);
20600         if (VT == MVT::i64 || VT == MVT::f64)
20601           return std::make_pair(0U, &X86::GR64RegClass);
20602         break;
20603       }
20604       // 32-bit fallthrough
20605     case 'Q':   // Q_REGS
20606       if (VT == MVT::i32 || VT == MVT::f32)
20607         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20608       if (VT == MVT::i16)
20609         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20610       if (VT == MVT::i8 || VT == MVT::i1)
20611         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20612       if (VT == MVT::i64)
20613         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20614       break;
20615     case 'r':   // GENERAL_REGS
20616     case 'l':   // INDEX_REGS
20617       if (VT == MVT::i8 || VT == MVT::i1)
20618         return std::make_pair(0U, &X86::GR8RegClass);
20619       if (VT == MVT::i16)
20620         return std::make_pair(0U, &X86::GR16RegClass);
20621       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20622         return std::make_pair(0U, &X86::GR32RegClass);
20623       return std::make_pair(0U, &X86::GR64RegClass);
20624     case 'R':   // LEGACY_REGS
20625       if (VT == MVT::i8 || VT == MVT::i1)
20626         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20627       if (VT == MVT::i16)
20628         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20629       if (VT == MVT::i32 || !Subtarget->is64Bit())
20630         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20631       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20632     case 'f':  // FP Stack registers.
20633       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20634       // value to the correct fpstack register class.
20635       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20636         return std::make_pair(0U, &X86::RFP32RegClass);
20637       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20638         return std::make_pair(0U, &X86::RFP64RegClass);
20639       return std::make_pair(0U, &X86::RFP80RegClass);
20640     case 'y':   // MMX_REGS if MMX allowed.
20641       if (!Subtarget->hasMMX()) break;
20642       return std::make_pair(0U, &X86::VR64RegClass);
20643     case 'Y':   // SSE_REGS if SSE2 allowed
20644       if (!Subtarget->hasSSE2()) break;
20645       // FALL THROUGH.
20646     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20647       if (!Subtarget->hasSSE1()) break;
20648
20649       switch (VT.SimpleTy) {
20650       default: break;
20651       // Scalar SSE types.
20652       case MVT::f32:
20653       case MVT::i32:
20654         return std::make_pair(0U, &X86::FR32RegClass);
20655       case MVT::f64:
20656       case MVT::i64:
20657         return std::make_pair(0U, &X86::FR64RegClass);
20658       // Vector types.
20659       case MVT::v16i8:
20660       case MVT::v8i16:
20661       case MVT::v4i32:
20662       case MVT::v2i64:
20663       case MVT::v4f32:
20664       case MVT::v2f64:
20665         return std::make_pair(0U, &X86::VR128RegClass);
20666       // AVX types.
20667       case MVT::v32i8:
20668       case MVT::v16i16:
20669       case MVT::v8i32:
20670       case MVT::v4i64:
20671       case MVT::v8f32:
20672       case MVT::v4f64:
20673         return std::make_pair(0U, &X86::VR256RegClass);
20674       case MVT::v8f64:
20675       case MVT::v16f32:
20676       case MVT::v16i32:
20677       case MVT::v8i64:
20678         return std::make_pair(0U, &X86::VR512RegClass);
20679       }
20680       break;
20681     }
20682   }
20683
20684   // Use the default implementation in TargetLowering to convert the register
20685   // constraint into a member of a register class.
20686   std::pair<unsigned, const TargetRegisterClass*> Res;
20687   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20688
20689   // Not found as a standard register?
20690   if (!Res.second) {
20691     // Map st(0) -> st(7) -> ST0
20692     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20693         tolower(Constraint[1]) == 's' &&
20694         tolower(Constraint[2]) == 't' &&
20695         Constraint[3] == '(' &&
20696         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20697         Constraint[5] == ')' &&
20698         Constraint[6] == '}') {
20699
20700       Res.first = X86::ST0+Constraint[4]-'0';
20701       Res.second = &X86::RFP80RegClass;
20702       return Res;
20703     }
20704
20705     // GCC allows "st(0)" to be called just plain "st".
20706     if (StringRef("{st}").equals_lower(Constraint)) {
20707       Res.first = X86::ST0;
20708       Res.second = &X86::RFP80RegClass;
20709       return Res;
20710     }
20711
20712     // flags -> EFLAGS
20713     if (StringRef("{flags}").equals_lower(Constraint)) {
20714       Res.first = X86::EFLAGS;
20715       Res.second = &X86::CCRRegClass;
20716       return Res;
20717     }
20718
20719     // 'A' means EAX + EDX.
20720     if (Constraint == "A") {
20721       Res.first = X86::EAX;
20722       Res.second = &X86::GR32_ADRegClass;
20723       return Res;
20724     }
20725     return Res;
20726   }
20727
20728   // Otherwise, check to see if this is a register class of the wrong value
20729   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20730   // turn into {ax},{dx}.
20731   if (Res.second->hasType(VT))
20732     return Res;   // Correct type already, nothing to do.
20733
20734   // All of the single-register GCC register classes map their values onto
20735   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20736   // really want an 8-bit or 32-bit register, map to the appropriate register
20737   // class and return the appropriate register.
20738   if (Res.second == &X86::GR16RegClass) {
20739     if (VT == MVT::i8 || VT == MVT::i1) {
20740       unsigned DestReg = 0;
20741       switch (Res.first) {
20742       default: break;
20743       case X86::AX: DestReg = X86::AL; break;
20744       case X86::DX: DestReg = X86::DL; break;
20745       case X86::CX: DestReg = X86::CL; break;
20746       case X86::BX: DestReg = X86::BL; break;
20747       }
20748       if (DestReg) {
20749         Res.first = DestReg;
20750         Res.second = &X86::GR8RegClass;
20751       }
20752     } else if (VT == MVT::i32 || VT == MVT::f32) {
20753       unsigned DestReg = 0;
20754       switch (Res.first) {
20755       default: break;
20756       case X86::AX: DestReg = X86::EAX; break;
20757       case X86::DX: DestReg = X86::EDX; break;
20758       case X86::CX: DestReg = X86::ECX; break;
20759       case X86::BX: DestReg = X86::EBX; break;
20760       case X86::SI: DestReg = X86::ESI; break;
20761       case X86::DI: DestReg = X86::EDI; break;
20762       case X86::BP: DestReg = X86::EBP; break;
20763       case X86::SP: DestReg = X86::ESP; break;
20764       }
20765       if (DestReg) {
20766         Res.first = DestReg;
20767         Res.second = &X86::GR32RegClass;
20768       }
20769     } else if (VT == MVT::i64 || VT == MVT::f64) {
20770       unsigned DestReg = 0;
20771       switch (Res.first) {
20772       default: break;
20773       case X86::AX: DestReg = X86::RAX; break;
20774       case X86::DX: DestReg = X86::RDX; break;
20775       case X86::CX: DestReg = X86::RCX; break;
20776       case X86::BX: DestReg = X86::RBX; break;
20777       case X86::SI: DestReg = X86::RSI; break;
20778       case X86::DI: DestReg = X86::RDI; break;
20779       case X86::BP: DestReg = X86::RBP; break;
20780       case X86::SP: DestReg = X86::RSP; break;
20781       }
20782       if (DestReg) {
20783         Res.first = DestReg;
20784         Res.second = &X86::GR64RegClass;
20785       }
20786     }
20787   } else if (Res.second == &X86::FR32RegClass ||
20788              Res.second == &X86::FR64RegClass ||
20789              Res.second == &X86::VR128RegClass ||
20790              Res.second == &X86::VR256RegClass ||
20791              Res.second == &X86::FR32XRegClass ||
20792              Res.second == &X86::FR64XRegClass ||
20793              Res.second == &X86::VR128XRegClass ||
20794              Res.second == &X86::VR256XRegClass ||
20795              Res.second == &X86::VR512RegClass) {
20796     // Handle references to XMM physical registers that got mapped into the
20797     // wrong class.  This can happen with constraints like {xmm0} where the
20798     // target independent register mapper will just pick the first match it can
20799     // find, ignoring the required type.
20800
20801     if (VT == MVT::f32 || VT == MVT::i32)
20802       Res.second = &X86::FR32RegClass;
20803     else if (VT == MVT::f64 || VT == MVT::i64)
20804       Res.second = &X86::FR64RegClass;
20805     else if (X86::VR128RegClass.hasType(VT))
20806       Res.second = &X86::VR128RegClass;
20807     else if (X86::VR256RegClass.hasType(VT))
20808       Res.second = &X86::VR256RegClass;
20809     else if (X86::VR512RegClass.hasType(VT))
20810       Res.second = &X86::VR512RegClass;
20811   }
20812
20813   return Res;
20814 }
20815
20816 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20817                                             Type *Ty) const {
20818   // Scaling factors are not free at all.
20819   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20820   // will take 2 allocations instead of 1 for plain addressing mode,
20821   // i.e. inst (reg1).
20822   if (isLegalAddressingMode(AM, Ty))
20823     // Scale represents reg2 * scale, thus account for 1
20824     // as soon as we use a second register.
20825     return AM.Scale != 0;
20826   return -1;
20827 }