Convert SelectionDAG::getMergeValues to use ArrayRef.
[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::SMUL_LOHI,          MVT::v4i32, Custom);
945     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
946     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
947     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
948     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
949     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
950     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
951     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
952     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
954     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
955     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
956     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
957     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
958     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
959
960     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
961     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
962     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
963     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
964
965     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
966     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
968     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
969     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
970
971     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
972     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
973       MVT VT = (MVT::SimpleValueType)i;
974       // Do not attempt to custom lower non-power-of-2 vectors
975       if (!isPowerOf2_32(VT.getVectorNumElements()))
976         continue;
977       // Do not attempt to custom lower non-128-bit vectors
978       if (!VT.is128BitVector())
979         continue;
980       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
981       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
982       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
983     }
984
985     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
986     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
987     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
988     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
989     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
990     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
991
992     if (Subtarget->is64Bit()) {
993       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
994       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
995     }
996
997     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
998     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
999       MVT VT = (MVT::SimpleValueType)i;
1000
1001       // Do not attempt to promote non-128-bit vectors
1002       if (!VT.is128BitVector())
1003         continue;
1004
1005       setOperationAction(ISD::AND,    VT, Promote);
1006       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1007       setOperationAction(ISD::OR,     VT, Promote);
1008       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1009       setOperationAction(ISD::XOR,    VT, Promote);
1010       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1011       setOperationAction(ISD::LOAD,   VT, Promote);
1012       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1013       setOperationAction(ISD::SELECT, VT, Promote);
1014       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1015     }
1016
1017     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1018
1019     // Custom lower v2i64 and v2f64 selects.
1020     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1021     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1022     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1023     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1024
1025     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1026     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1027
1028     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1029     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1030     // As there is no 64-bit GPR available, we need build a special custom
1031     // sequence to convert from v2i32 to v2f32.
1032     if (!Subtarget->is64Bit())
1033       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1034
1035     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1036     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1037
1038     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1039   }
1040
1041   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1042     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1043     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1044     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1045     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1046     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1047     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1048     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1049     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1050     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1051     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1052
1053     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1054     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1055     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1056     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1057     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1058     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1059     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1060     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1061     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1062     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1063
1064     // FIXME: Do we need to handle scalar-to-vector here?
1065     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
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, 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, 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, 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, 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, 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, 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, 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, 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, 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   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13170   unsigned Opcode =
13171       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13172   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13173                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13174   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13175                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13176
13177   // Shuffle it back into the right order.
13178   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13179   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13180   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13181   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13182
13183   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13184   // unsigned multiply.
13185   if (IsSigned && !Subtarget->hasSSE41()) {
13186     SDValue ShAmt =
13187         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13188     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13189                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13190     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13191                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13192
13193     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13194     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13195   }
13196
13197   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13198 }
13199
13200 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13201                                          const X86Subtarget *Subtarget) {
13202   MVT VT = Op.getSimpleValueType();
13203   SDLoc dl(Op);
13204   SDValue R = Op.getOperand(0);
13205   SDValue Amt = Op.getOperand(1);
13206
13207   // Optimize shl/srl/sra with constant shift amount.
13208   if (isSplatVector(Amt.getNode())) {
13209     SDValue SclrAmt = Amt->getOperand(0);
13210     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13211       uint64_t ShiftAmt = C->getZExtValue();
13212
13213       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13214           (Subtarget->hasInt256() &&
13215            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13216           (Subtarget->hasAVX512() &&
13217            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13218         if (Op.getOpcode() == ISD::SHL)
13219           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13220                                             DAG);
13221         if (Op.getOpcode() == ISD::SRL)
13222           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13223                                             DAG);
13224         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13225           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13226                                             DAG);
13227       }
13228
13229       if (VT == MVT::v16i8) {
13230         if (Op.getOpcode() == ISD::SHL) {
13231           // Make a large shift.
13232           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13233                                                    MVT::v8i16, R, ShiftAmt,
13234                                                    DAG);
13235           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13236           // Zero out the rightmost bits.
13237           SmallVector<SDValue, 16> V(16,
13238                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13239                                                      MVT::i8));
13240           return DAG.getNode(ISD::AND, dl, VT, SHL,
13241                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13242         }
13243         if (Op.getOpcode() == ISD::SRL) {
13244           // Make a large shift.
13245           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13246                                                    MVT::v8i16, R, ShiftAmt,
13247                                                    DAG);
13248           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13249           // Zero out the leftmost bits.
13250           SmallVector<SDValue, 16> V(16,
13251                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13252                                                      MVT::i8));
13253           return DAG.getNode(ISD::AND, dl, VT, SRL,
13254                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13255         }
13256         if (Op.getOpcode() == ISD::SRA) {
13257           if (ShiftAmt == 7) {
13258             // R s>> 7  ===  R s< 0
13259             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13260             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13261           }
13262
13263           // R s>> a === ((R u>> a) ^ m) - m
13264           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13265           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13266                                                          MVT::i8));
13267           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13268           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13269           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13270           return Res;
13271         }
13272         llvm_unreachable("Unknown shift opcode.");
13273       }
13274
13275       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13276         if (Op.getOpcode() == ISD::SHL) {
13277           // Make a large shift.
13278           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13279                                                    MVT::v16i16, R, ShiftAmt,
13280                                                    DAG);
13281           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13282           // Zero out the rightmost bits.
13283           SmallVector<SDValue, 32> V(32,
13284                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13285                                                      MVT::i8));
13286           return DAG.getNode(ISD::AND, dl, VT, SHL,
13287                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13288         }
13289         if (Op.getOpcode() == ISD::SRL) {
13290           // Make a large shift.
13291           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13292                                                    MVT::v16i16, R, ShiftAmt,
13293                                                    DAG);
13294           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13295           // Zero out the leftmost bits.
13296           SmallVector<SDValue, 32> V(32,
13297                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13298                                                      MVT::i8));
13299           return DAG.getNode(ISD::AND, dl, VT, SRL,
13300                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13301         }
13302         if (Op.getOpcode() == ISD::SRA) {
13303           if (ShiftAmt == 7) {
13304             // R s>> 7  ===  R s< 0
13305             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13306             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13307           }
13308
13309           // R s>> a === ((R u>> a) ^ m) - m
13310           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13311           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13312                                                          MVT::i8));
13313           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13314           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13315           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13316           return Res;
13317         }
13318         llvm_unreachable("Unknown shift opcode.");
13319       }
13320     }
13321   }
13322
13323   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13324   if (!Subtarget->is64Bit() &&
13325       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13326       Amt.getOpcode() == ISD::BITCAST &&
13327       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13328     Amt = Amt.getOperand(0);
13329     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13330                      VT.getVectorNumElements();
13331     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13332     uint64_t ShiftAmt = 0;
13333     for (unsigned i = 0; i != Ratio; ++i) {
13334       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13335       if (!C)
13336         return SDValue();
13337       // 6 == Log2(64)
13338       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13339     }
13340     // Check remaining shift amounts.
13341     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13342       uint64_t ShAmt = 0;
13343       for (unsigned j = 0; j != Ratio; ++j) {
13344         ConstantSDNode *C =
13345           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13346         if (!C)
13347           return SDValue();
13348         // 6 == Log2(64)
13349         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13350       }
13351       if (ShAmt != ShiftAmt)
13352         return SDValue();
13353     }
13354     switch (Op.getOpcode()) {
13355     default:
13356       llvm_unreachable("Unknown shift opcode!");
13357     case ISD::SHL:
13358       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13359                                         DAG);
13360     case ISD::SRL:
13361       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13362                                         DAG);
13363     case ISD::SRA:
13364       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13365                                         DAG);
13366     }
13367   }
13368
13369   return SDValue();
13370 }
13371
13372 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13373                                         const X86Subtarget* Subtarget) {
13374   MVT VT = Op.getSimpleValueType();
13375   SDLoc dl(Op);
13376   SDValue R = Op.getOperand(0);
13377   SDValue Amt = Op.getOperand(1);
13378
13379   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13380       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13381       (Subtarget->hasInt256() &&
13382        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13383         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13384        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13385     SDValue BaseShAmt;
13386     EVT EltVT = VT.getVectorElementType();
13387
13388     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13389       unsigned NumElts = VT.getVectorNumElements();
13390       unsigned i, j;
13391       for (i = 0; i != NumElts; ++i) {
13392         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13393           continue;
13394         break;
13395       }
13396       for (j = i; j != NumElts; ++j) {
13397         SDValue Arg = Amt.getOperand(j);
13398         if (Arg.getOpcode() == ISD::UNDEF) continue;
13399         if (Arg != Amt.getOperand(i))
13400           break;
13401       }
13402       if (i != NumElts && j == NumElts)
13403         BaseShAmt = Amt.getOperand(i);
13404     } else {
13405       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13406         Amt = Amt.getOperand(0);
13407       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13408                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13409         SDValue InVec = Amt.getOperand(0);
13410         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13411           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13412           unsigned i = 0;
13413           for (; i != NumElts; ++i) {
13414             SDValue Arg = InVec.getOperand(i);
13415             if (Arg.getOpcode() == ISD::UNDEF) continue;
13416             BaseShAmt = Arg;
13417             break;
13418           }
13419         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13420            if (ConstantSDNode *C =
13421                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13422              unsigned SplatIdx =
13423                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13424              if (C->getZExtValue() == SplatIdx)
13425                BaseShAmt = InVec.getOperand(1);
13426            }
13427         }
13428         if (!BaseShAmt.getNode())
13429           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13430                                   DAG.getIntPtrConstant(0));
13431       }
13432     }
13433
13434     if (BaseShAmt.getNode()) {
13435       if (EltVT.bitsGT(MVT::i32))
13436         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13437       else if (EltVT.bitsLT(MVT::i32))
13438         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13439
13440       switch (Op.getOpcode()) {
13441       default:
13442         llvm_unreachable("Unknown shift opcode!");
13443       case ISD::SHL:
13444         switch (VT.SimpleTy) {
13445         default: return SDValue();
13446         case MVT::v2i64:
13447         case MVT::v4i32:
13448         case MVT::v8i16:
13449         case MVT::v4i64:
13450         case MVT::v8i32:
13451         case MVT::v16i16:
13452         case MVT::v16i32:
13453         case MVT::v8i64:
13454           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13455         }
13456       case ISD::SRA:
13457         switch (VT.SimpleTy) {
13458         default: return SDValue();
13459         case MVT::v4i32:
13460         case MVT::v8i16:
13461         case MVT::v8i32:
13462         case MVT::v16i16:
13463         case MVT::v16i32:
13464         case MVT::v8i64:
13465           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13466         }
13467       case ISD::SRL:
13468         switch (VT.SimpleTy) {
13469         default: return SDValue();
13470         case MVT::v2i64:
13471         case MVT::v4i32:
13472         case MVT::v8i16:
13473         case MVT::v4i64:
13474         case MVT::v8i32:
13475         case MVT::v16i16:
13476         case MVT::v16i32:
13477         case MVT::v8i64:
13478           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13479         }
13480       }
13481     }
13482   }
13483
13484   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13485   if (!Subtarget->is64Bit() &&
13486       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13487       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13488       Amt.getOpcode() == ISD::BITCAST &&
13489       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13490     Amt = Amt.getOperand(0);
13491     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13492                      VT.getVectorNumElements();
13493     std::vector<SDValue> Vals(Ratio);
13494     for (unsigned i = 0; i != Ratio; ++i)
13495       Vals[i] = Amt.getOperand(i);
13496     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13497       for (unsigned j = 0; j != Ratio; ++j)
13498         if (Vals[j] != Amt.getOperand(i + j))
13499           return SDValue();
13500     }
13501     switch (Op.getOpcode()) {
13502     default:
13503       llvm_unreachable("Unknown shift opcode!");
13504     case ISD::SHL:
13505       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13506     case ISD::SRL:
13507       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13508     case ISD::SRA:
13509       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13510     }
13511   }
13512
13513   return SDValue();
13514 }
13515
13516 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13517                           SelectionDAG &DAG) {
13518
13519   MVT VT = Op.getSimpleValueType();
13520   SDLoc dl(Op);
13521   SDValue R = Op.getOperand(0);
13522   SDValue Amt = Op.getOperand(1);
13523   SDValue V;
13524
13525   if (!Subtarget->hasSSE2())
13526     return SDValue();
13527
13528   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13529   if (V.getNode())
13530     return V;
13531
13532   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13533   if (V.getNode())
13534       return V;
13535
13536   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13537     return Op;
13538   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13539   if (Subtarget->hasInt256()) {
13540     if (Op.getOpcode() == ISD::SRL &&
13541         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13542          VT == MVT::v4i64 || VT == MVT::v8i32))
13543       return Op;
13544     if (Op.getOpcode() == ISD::SHL &&
13545         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13546          VT == MVT::v4i64 || VT == MVT::v8i32))
13547       return Op;
13548     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13549       return Op;
13550   }
13551
13552   // If possible, lower this packed shift into a vector multiply instead of
13553   // expanding it into a sequence of scalar shifts.
13554   // Do this only if the vector shift count is a constant build_vector.
13555   if (Op.getOpcode() == ISD::SHL && 
13556       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13557        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13558       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13559     SmallVector<SDValue, 8> Elts;
13560     EVT SVT = VT.getScalarType();
13561     unsigned SVTBits = SVT.getSizeInBits();
13562     const APInt &One = APInt(SVTBits, 1);
13563     unsigned NumElems = VT.getVectorNumElements();
13564
13565     for (unsigned i=0; i !=NumElems; ++i) {
13566       SDValue Op = Amt->getOperand(i);
13567       if (Op->getOpcode() == ISD::UNDEF) {
13568         Elts.push_back(Op);
13569         continue;
13570       }
13571
13572       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13573       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13574       uint64_t ShAmt = C.getZExtValue();
13575       if (ShAmt >= SVTBits) {
13576         Elts.push_back(DAG.getUNDEF(SVT));
13577         continue;
13578       }
13579       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13580     }
13581     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13582     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13583   }
13584
13585   // Lower SHL with variable shift amount.
13586   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13587     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13588
13589     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13590     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13591     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13592     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13593   }
13594
13595   // If possible, lower this shift as a sequence of two shifts by
13596   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13597   // Example:
13598   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13599   //
13600   // Could be rewritten as:
13601   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13602   //
13603   // The advantage is that the two shifts from the example would be
13604   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13605   // the vector shift into four scalar shifts plus four pairs of vector
13606   // insert/extract.
13607   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13608       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13609     unsigned TargetOpcode = X86ISD::MOVSS;
13610     bool CanBeSimplified;
13611     // The splat value for the first packed shift (the 'X' from the example).
13612     SDValue Amt1 = Amt->getOperand(0);
13613     // The splat value for the second packed shift (the 'Y' from the example).
13614     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13615                                         Amt->getOperand(2);
13616
13617     // See if it is possible to replace this node with a sequence of
13618     // two shifts followed by a MOVSS/MOVSD
13619     if (VT == MVT::v4i32) {
13620       // Check if it is legal to use a MOVSS.
13621       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13622                         Amt2 == Amt->getOperand(3);
13623       if (!CanBeSimplified) {
13624         // Otherwise, check if we can still simplify this node using a MOVSD.
13625         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13626                           Amt->getOperand(2) == Amt->getOperand(3);
13627         TargetOpcode = X86ISD::MOVSD;
13628         Amt2 = Amt->getOperand(2);
13629       }
13630     } else {
13631       // Do similar checks for the case where the machine value type
13632       // is MVT::v8i16.
13633       CanBeSimplified = Amt1 == Amt->getOperand(1);
13634       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13635         CanBeSimplified = Amt2 == Amt->getOperand(i);
13636
13637       if (!CanBeSimplified) {
13638         TargetOpcode = X86ISD::MOVSD;
13639         CanBeSimplified = true;
13640         Amt2 = Amt->getOperand(4);
13641         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13642           CanBeSimplified = Amt1 == Amt->getOperand(i);
13643         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13644           CanBeSimplified = Amt2 == Amt->getOperand(j);
13645       }
13646     }
13647     
13648     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13649         isa<ConstantSDNode>(Amt2)) {
13650       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13651       EVT CastVT = MVT::v4i32;
13652       SDValue Splat1 = 
13653         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13654       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13655       SDValue Splat2 = 
13656         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13657       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13658       if (TargetOpcode == X86ISD::MOVSD)
13659         CastVT = MVT::v2i64;
13660       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13661       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13662       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13663                                             BitCast1, DAG);
13664       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13665     }
13666   }
13667
13668   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13669     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13670
13671     // a = a << 5;
13672     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13673     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13674
13675     // Turn 'a' into a mask suitable for VSELECT
13676     SDValue VSelM = DAG.getConstant(0x80, VT);
13677     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13678     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13679
13680     SDValue CM1 = DAG.getConstant(0x0f, VT);
13681     SDValue CM2 = DAG.getConstant(0x3f, VT);
13682
13683     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13684     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13685     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13686     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13687     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13688
13689     // a += a
13690     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13691     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13692     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13693
13694     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13695     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13696     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13697     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13698     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13699
13700     // a += a
13701     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13702     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13703     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13704
13705     // return VSELECT(r, r+r, a);
13706     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
13707                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
13708     return R;
13709   }
13710
13711   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
13712   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
13713   // solution better.
13714   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
13715     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
13716     unsigned ExtOpc =
13717         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
13718     R = DAG.getNode(ExtOpc, dl, NewVT, R);
13719     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
13720     return DAG.getNode(ISD::TRUNCATE, dl, VT,
13721                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
13722     }
13723
13724   // Decompose 256-bit shifts into smaller 128-bit shifts.
13725   if (VT.is256BitVector()) {
13726     unsigned NumElems = VT.getVectorNumElements();
13727     MVT EltVT = VT.getVectorElementType();
13728     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13729
13730     // Extract the two vectors
13731     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
13732     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
13733
13734     // Recreate the shift amount vectors
13735     SDValue Amt1, Amt2;
13736     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13737       // Constant shift amount
13738       SmallVector<SDValue, 4> Amt1Csts;
13739       SmallVector<SDValue, 4> Amt2Csts;
13740       for (unsigned i = 0; i != NumElems/2; ++i)
13741         Amt1Csts.push_back(Amt->getOperand(i));
13742       for (unsigned i = NumElems/2; i != NumElems; ++i)
13743         Amt2Csts.push_back(Amt->getOperand(i));
13744
13745       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
13746       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
13747     } else {
13748       // Variable shift amount
13749       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
13750       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
13751     }
13752
13753     // Issue new vector shifts for the smaller types
13754     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
13755     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
13756
13757     // Concatenate the result back
13758     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
13759   }
13760
13761   return SDValue();
13762 }
13763
13764 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
13765   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
13766   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
13767   // looks for this combo and may remove the "setcc" instruction if the "setcc"
13768   // has only one use.
13769   SDNode *N = Op.getNode();
13770   SDValue LHS = N->getOperand(0);
13771   SDValue RHS = N->getOperand(1);
13772   unsigned BaseOp = 0;
13773   unsigned Cond = 0;
13774   SDLoc DL(Op);
13775   switch (Op.getOpcode()) {
13776   default: llvm_unreachable("Unknown ovf instruction!");
13777   case ISD::SADDO:
13778     // A subtract of one will be selected as a INC. Note that INC doesn't
13779     // set CF, so we can't do this for UADDO.
13780     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13781       if (C->isOne()) {
13782         BaseOp = X86ISD::INC;
13783         Cond = X86::COND_O;
13784         break;
13785       }
13786     BaseOp = X86ISD::ADD;
13787     Cond = X86::COND_O;
13788     break;
13789   case ISD::UADDO:
13790     BaseOp = X86ISD::ADD;
13791     Cond = X86::COND_B;
13792     break;
13793   case ISD::SSUBO:
13794     // A subtract of one will be selected as a DEC. Note that DEC doesn't
13795     // set CF, so we can't do this for USUBO.
13796     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13797       if (C->isOne()) {
13798         BaseOp = X86ISD::DEC;
13799         Cond = X86::COND_O;
13800         break;
13801       }
13802     BaseOp = X86ISD::SUB;
13803     Cond = X86::COND_O;
13804     break;
13805   case ISD::USUBO:
13806     BaseOp = X86ISD::SUB;
13807     Cond = X86::COND_B;
13808     break;
13809   case ISD::SMULO:
13810     BaseOp = X86ISD::SMUL;
13811     Cond = X86::COND_O;
13812     break;
13813   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
13814     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
13815                                  MVT::i32);
13816     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
13817
13818     SDValue SetCC =
13819       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13820                   DAG.getConstant(X86::COND_O, MVT::i32),
13821                   SDValue(Sum.getNode(), 2));
13822
13823     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13824   }
13825   }
13826
13827   // Also sets EFLAGS.
13828   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
13829   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
13830
13831   SDValue SetCC =
13832     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
13833                 DAG.getConstant(Cond, MVT::i32),
13834                 SDValue(Sum.getNode(), 1));
13835
13836   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
13837 }
13838
13839 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
13840                                                   SelectionDAG &DAG) const {
13841   SDLoc dl(Op);
13842   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
13843   MVT VT = Op.getSimpleValueType();
13844
13845   if (!Subtarget->hasSSE2() || !VT.isVector())
13846     return SDValue();
13847
13848   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
13849                       ExtraVT.getScalarType().getSizeInBits();
13850
13851   switch (VT.SimpleTy) {
13852     default: return SDValue();
13853     case MVT::v8i32:
13854     case MVT::v16i16:
13855       if (!Subtarget->hasFp256())
13856         return SDValue();
13857       if (!Subtarget->hasInt256()) {
13858         // needs to be split
13859         unsigned NumElems = VT.getVectorNumElements();
13860
13861         // Extract the LHS vectors
13862         SDValue LHS = Op.getOperand(0);
13863         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13864         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13865
13866         MVT EltVT = VT.getVectorElementType();
13867         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13868
13869         EVT ExtraEltVT = ExtraVT.getVectorElementType();
13870         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
13871         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
13872                                    ExtraNumElems/2);
13873         SDValue Extra = DAG.getValueType(ExtraVT);
13874
13875         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
13876         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
13877
13878         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
13879       }
13880       // fall through
13881     case MVT::v4i32:
13882     case MVT::v8i16: {
13883       SDValue Op0 = Op.getOperand(0);
13884       SDValue Op00 = Op0.getOperand(0);
13885       SDValue Tmp1;
13886       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
13887       if (Op0.getOpcode() == ISD::BITCAST &&
13888           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
13889         // (sext (vzext x)) -> (vsext x)
13890         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
13891         if (Tmp1.getNode()) {
13892           EVT ExtraEltVT = ExtraVT.getVectorElementType();
13893           // This folding is only valid when the in-reg type is a vector of i8,
13894           // i16, or i32.
13895           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
13896               ExtraEltVT == MVT::i32) {
13897             SDValue Tmp1Op0 = Tmp1.getOperand(0);
13898             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
13899                    "This optimization is invalid without a VZEXT.");
13900             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
13901           }
13902           Op0 = Tmp1;
13903         }
13904       }
13905
13906       // If the above didn't work, then just use Shift-Left + Shift-Right.
13907       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
13908                                         DAG);
13909       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
13910                                         DAG);
13911     }
13912   }
13913 }
13914
13915 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
13916                                  SelectionDAG &DAG) {
13917   SDLoc dl(Op);
13918   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
13919     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
13920   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
13921     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
13922
13923   // The only fence that needs an instruction is a sequentially-consistent
13924   // cross-thread fence.
13925   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
13926     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
13927     // no-sse2). There isn't any reason to disable it if the target processor
13928     // supports it.
13929     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
13930       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
13931
13932     SDValue Chain = Op.getOperand(0);
13933     SDValue Zero = DAG.getConstant(0, MVT::i32);
13934     SDValue Ops[] = {
13935       DAG.getRegister(X86::ESP, MVT::i32), // Base
13936       DAG.getTargetConstant(1, MVT::i8),   // Scale
13937       DAG.getRegister(0, MVT::i32),        // Index
13938       DAG.getTargetConstant(0, MVT::i32),  // Disp
13939       DAG.getRegister(0, MVT::i32),        // Segment.
13940       Zero,
13941       Chain
13942     };
13943     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
13944     return SDValue(Res, 0);
13945   }
13946
13947   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
13948   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
13949 }
13950
13951 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
13952                              SelectionDAG &DAG) {
13953   MVT T = Op.getSimpleValueType();
13954   SDLoc DL(Op);
13955   unsigned Reg = 0;
13956   unsigned size = 0;
13957   switch(T.SimpleTy) {
13958   default: llvm_unreachable("Invalid value type!");
13959   case MVT::i8:  Reg = X86::AL;  size = 1; break;
13960   case MVT::i16: Reg = X86::AX;  size = 2; break;
13961   case MVT::i32: Reg = X86::EAX; size = 4; break;
13962   case MVT::i64:
13963     assert(Subtarget->is64Bit() && "Node not type legal!");
13964     Reg = X86::RAX; size = 8;
13965     break;
13966   }
13967   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
13968                                     Op.getOperand(2), SDValue());
13969   SDValue Ops[] = { cpIn.getValue(0),
13970                     Op.getOperand(1),
13971                     Op.getOperand(3),
13972                     DAG.getTargetConstant(size, MVT::i8),
13973                     cpIn.getValue(1) };
13974   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13975   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
13976   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
13977                                            Ops, T, MMO);
13978   SDValue cpOut =
13979     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
13980   return cpOut;
13981 }
13982
13983 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
13984                             SelectionDAG &DAG) {
13985   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
13986   MVT DstVT = Op.getSimpleValueType();
13987   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
13988          Subtarget->hasMMX() && "Unexpected custom BITCAST");
13989   assert((DstVT == MVT::i64 ||
13990           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
13991          "Unexpected custom BITCAST");
13992   // i64 <=> MMX conversions are Legal.
13993   if (SrcVT==MVT::i64 && DstVT.isVector())
13994     return Op;
13995   if (DstVT==MVT::i64 && SrcVT.isVector())
13996     return Op;
13997   // MMX <=> MMX conversions are Legal.
13998   if (SrcVT.isVector() && DstVT.isVector())
13999     return Op;
14000   // All other conversions need to be expanded.
14001   return SDValue();
14002 }
14003
14004 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14005   SDNode *Node = Op.getNode();
14006   SDLoc dl(Node);
14007   EVT T = Node->getValueType(0);
14008   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14009                               DAG.getConstant(0, T), Node->getOperand(2));
14010   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14011                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14012                        Node->getOperand(0),
14013                        Node->getOperand(1), negOp,
14014                        cast<AtomicSDNode>(Node)->getMemOperand(),
14015                        cast<AtomicSDNode>(Node)->getOrdering(),
14016                        cast<AtomicSDNode>(Node)->getSynchScope());
14017 }
14018
14019 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14020   SDNode *Node = Op.getNode();
14021   SDLoc dl(Node);
14022   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14023
14024   // Convert seq_cst store -> xchg
14025   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14026   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14027   //        (The only way to get a 16-byte store is cmpxchg16b)
14028   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14029   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14030       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14031     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14032                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14033                                  Node->getOperand(0),
14034                                  Node->getOperand(1), Node->getOperand(2),
14035                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14036                                  cast<AtomicSDNode>(Node)->getOrdering(),
14037                                  cast<AtomicSDNode>(Node)->getSynchScope());
14038     return Swap.getValue(1);
14039   }
14040   // Other atomic stores have a simple pattern.
14041   return Op;
14042 }
14043
14044 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14045   EVT VT = Op.getNode()->getSimpleValueType(0);
14046
14047   // Let legalize expand this if it isn't a legal type yet.
14048   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14049     return SDValue();
14050
14051   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14052
14053   unsigned Opc;
14054   bool ExtraOp = false;
14055   switch (Op.getOpcode()) {
14056   default: llvm_unreachable("Invalid code");
14057   case ISD::ADDC: Opc = X86ISD::ADD; break;
14058   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14059   case ISD::SUBC: Opc = X86ISD::SUB; break;
14060   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14061   }
14062
14063   if (!ExtraOp)
14064     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14065                        Op.getOperand(1));
14066   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14067                      Op.getOperand(1), Op.getOperand(2));
14068 }
14069
14070 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14071                             SelectionDAG &DAG) {
14072   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14073
14074   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14075   // which returns the values as { float, float } (in XMM0) or
14076   // { double, double } (which is returned in XMM0, XMM1).
14077   SDLoc dl(Op);
14078   SDValue Arg = Op.getOperand(0);
14079   EVT ArgVT = Arg.getValueType();
14080   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14081
14082   TargetLowering::ArgListTy Args;
14083   TargetLowering::ArgListEntry Entry;
14084
14085   Entry.Node = Arg;
14086   Entry.Ty = ArgTy;
14087   Entry.isSExt = false;
14088   Entry.isZExt = false;
14089   Args.push_back(Entry);
14090
14091   bool isF64 = ArgVT == MVT::f64;
14092   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14093   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14094   // the results are returned via SRet in memory.
14095   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14096   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14097   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14098
14099   Type *RetTy = isF64
14100     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14101     : (Type*)VectorType::get(ArgTy, 4);
14102   TargetLowering::
14103     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
14104                          false, false, false, false, 0,
14105                          CallingConv::C, /*isTaillCall=*/false,
14106                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
14107                          Callee, Args, DAG, dl);
14108   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14109
14110   if (isF64)
14111     // Returned in xmm0 and xmm1.
14112     return CallResult.first;
14113
14114   // Returned in bits 0:31 and 32:64 xmm0.
14115   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14116                                CallResult.first, DAG.getIntPtrConstant(0));
14117   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14118                                CallResult.first, DAG.getIntPtrConstant(1));
14119   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14120   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14121 }
14122
14123 /// LowerOperation - Provide custom lowering hooks for some operations.
14124 ///
14125 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14126   switch (Op.getOpcode()) {
14127   default: llvm_unreachable("Should not custom lower this!");
14128   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14129   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14130   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14131   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14132   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14133   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14134   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14135   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14136   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14137   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14138   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14139   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14140   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14141   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14142   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14143   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14144   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14145   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14146   case ISD::SHL_PARTS:
14147   case ISD::SRA_PARTS:
14148   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14149   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14150   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14151   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14152   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14153   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14154   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14155   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14156   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14157   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14158   case ISD::FABS:               return LowerFABS(Op, DAG);
14159   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14160   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14161   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14162   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14163   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14164   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14165   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14166   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14167   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14168   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14169   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14170   case ISD::INTRINSIC_VOID:
14171   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14172   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14173   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14174   case ISD::FRAME_TO_ARGS_OFFSET:
14175                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14176   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14177   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14178   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14179   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14180   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14181   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14182   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14183   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14184   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14185   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14186   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14187   case ISD::UMUL_LOHI:
14188   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14189   case ISD::SRA:
14190   case ISD::SRL:
14191   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14192   case ISD::SADDO:
14193   case ISD::UADDO:
14194   case ISD::SSUBO:
14195   case ISD::USUBO:
14196   case ISD::SMULO:
14197   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14198   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14199   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14200   case ISD::ADDC:
14201   case ISD::ADDE:
14202   case ISD::SUBC:
14203   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14204   case ISD::ADD:                return LowerADD(Op, DAG);
14205   case ISD::SUB:                return LowerSUB(Op, DAG);
14206   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14207   }
14208 }
14209
14210 static void ReplaceATOMIC_LOAD(SDNode *Node,
14211                                   SmallVectorImpl<SDValue> &Results,
14212                                   SelectionDAG &DAG) {
14213   SDLoc dl(Node);
14214   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14215
14216   // Convert wide load -> cmpxchg8b/cmpxchg16b
14217   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14218   //        (The only way to get a 16-byte load is cmpxchg16b)
14219   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14220   SDValue Zero = DAG.getConstant(0, VT);
14221   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14222                                Node->getOperand(0),
14223                                Node->getOperand(1), Zero, Zero,
14224                                cast<AtomicSDNode>(Node)->getMemOperand(),
14225                                cast<AtomicSDNode>(Node)->getOrdering(),
14226                                cast<AtomicSDNode>(Node)->getOrdering(),
14227                                cast<AtomicSDNode>(Node)->getSynchScope());
14228   Results.push_back(Swap.getValue(0));
14229   Results.push_back(Swap.getValue(1));
14230 }
14231
14232 static void
14233 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14234                         SelectionDAG &DAG, unsigned NewOp) {
14235   SDLoc dl(Node);
14236   assert (Node->getValueType(0) == MVT::i64 &&
14237           "Only know how to expand i64 atomics");
14238
14239   SDValue Chain = Node->getOperand(0);
14240   SDValue In1 = Node->getOperand(1);
14241   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14242                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14243   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14244                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14245   SDValue Ops[] = { Chain, In1, In2L, In2H };
14246   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14247   SDValue Result =
14248     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14249                             cast<MemSDNode>(Node)->getMemOperand());
14250   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14251   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14252   Results.push_back(Result.getValue(2));
14253 }
14254
14255 /// ReplaceNodeResults - Replace a node with an illegal result type
14256 /// with a new node built out of custom code.
14257 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14258                                            SmallVectorImpl<SDValue>&Results,
14259                                            SelectionDAG &DAG) const {
14260   SDLoc dl(N);
14261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14262   switch (N->getOpcode()) {
14263   default:
14264     llvm_unreachable("Do not know how to custom type legalize this operation!");
14265   case ISD::SIGN_EXTEND_INREG:
14266   case ISD::ADDC:
14267   case ISD::ADDE:
14268   case ISD::SUBC:
14269   case ISD::SUBE:
14270     // We don't want to expand or promote these.
14271     return;
14272   case ISD::FP_TO_SINT:
14273   case ISD::FP_TO_UINT: {
14274     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14275
14276     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14277       return;
14278
14279     std::pair<SDValue,SDValue> Vals =
14280         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14281     SDValue FIST = Vals.first, StackSlot = Vals.second;
14282     if (FIST.getNode()) {
14283       EVT VT = N->getValueType(0);
14284       // Return a load from the stack slot.
14285       if (StackSlot.getNode())
14286         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14287                                       MachinePointerInfo(),
14288                                       false, false, false, 0));
14289       else
14290         Results.push_back(FIST);
14291     }
14292     return;
14293   }
14294   case ISD::UINT_TO_FP: {
14295     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14296     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14297         N->getValueType(0) != MVT::v2f32)
14298       return;
14299     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14300                                  N->getOperand(0));
14301     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14302                                      MVT::f64);
14303     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14304     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14305                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14306     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14307     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14308     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14309     return;
14310   }
14311   case ISD::FP_ROUND: {
14312     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14313         return;
14314     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14315     Results.push_back(V);
14316     return;
14317   }
14318   case ISD::INTRINSIC_W_CHAIN: {
14319     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14320     switch (IntNo) {
14321     default : llvm_unreachable("Do not know how to custom type "
14322                                "legalize this intrinsic operation!");
14323     case Intrinsic::x86_rdtsc:
14324       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14325                                      Results);
14326     case Intrinsic::x86_rdtscp:
14327       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14328                                      Results);
14329     }
14330   }
14331   case ISD::READCYCLECOUNTER: {
14332     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14333                                    Results);
14334   }
14335   case ISD::ATOMIC_CMP_SWAP: {
14336     EVT T = N->getValueType(0);
14337     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14338     bool Regs64bit = T == MVT::i128;
14339     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14340     SDValue cpInL, cpInH;
14341     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14342                         DAG.getConstant(0, HalfT));
14343     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14344                         DAG.getConstant(1, HalfT));
14345     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14346                              Regs64bit ? X86::RAX : X86::EAX,
14347                              cpInL, SDValue());
14348     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14349                              Regs64bit ? X86::RDX : X86::EDX,
14350                              cpInH, cpInL.getValue(1));
14351     SDValue swapInL, swapInH;
14352     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14353                           DAG.getConstant(0, HalfT));
14354     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14355                           DAG.getConstant(1, HalfT));
14356     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14357                                Regs64bit ? X86::RBX : X86::EBX,
14358                                swapInL, cpInH.getValue(1));
14359     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14360                                Regs64bit ? X86::RCX : X86::ECX,
14361                                swapInH, swapInL.getValue(1));
14362     SDValue Ops[] = { swapInH.getValue(0),
14363                       N->getOperand(1),
14364                       swapInH.getValue(1) };
14365     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14366     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14367     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14368                                   X86ISD::LCMPXCHG8_DAG;
14369     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14370     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14371                                         Regs64bit ? X86::RAX : X86::EAX,
14372                                         HalfT, Result.getValue(1));
14373     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14374                                         Regs64bit ? X86::RDX : X86::EDX,
14375                                         HalfT, cpOutL.getValue(2));
14376     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14377     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14378     Results.push_back(cpOutH.getValue(1));
14379     return;
14380   }
14381   case ISD::ATOMIC_LOAD_ADD:
14382   case ISD::ATOMIC_LOAD_AND:
14383   case ISD::ATOMIC_LOAD_NAND:
14384   case ISD::ATOMIC_LOAD_OR:
14385   case ISD::ATOMIC_LOAD_SUB:
14386   case ISD::ATOMIC_LOAD_XOR:
14387   case ISD::ATOMIC_LOAD_MAX:
14388   case ISD::ATOMIC_LOAD_MIN:
14389   case ISD::ATOMIC_LOAD_UMAX:
14390   case ISD::ATOMIC_LOAD_UMIN:
14391   case ISD::ATOMIC_SWAP: {
14392     unsigned Opc;
14393     switch (N->getOpcode()) {
14394     default: llvm_unreachable("Unexpected opcode");
14395     case ISD::ATOMIC_LOAD_ADD:
14396       Opc = X86ISD::ATOMADD64_DAG;
14397       break;
14398     case ISD::ATOMIC_LOAD_AND:
14399       Opc = X86ISD::ATOMAND64_DAG;
14400       break;
14401     case ISD::ATOMIC_LOAD_NAND:
14402       Opc = X86ISD::ATOMNAND64_DAG;
14403       break;
14404     case ISD::ATOMIC_LOAD_OR:
14405       Opc = X86ISD::ATOMOR64_DAG;
14406       break;
14407     case ISD::ATOMIC_LOAD_SUB:
14408       Opc = X86ISD::ATOMSUB64_DAG;
14409       break;
14410     case ISD::ATOMIC_LOAD_XOR:
14411       Opc = X86ISD::ATOMXOR64_DAG;
14412       break;
14413     case ISD::ATOMIC_LOAD_MAX:
14414       Opc = X86ISD::ATOMMAX64_DAG;
14415       break;
14416     case ISD::ATOMIC_LOAD_MIN:
14417       Opc = X86ISD::ATOMMIN64_DAG;
14418       break;
14419     case ISD::ATOMIC_LOAD_UMAX:
14420       Opc = X86ISD::ATOMUMAX64_DAG;
14421       break;
14422     case ISD::ATOMIC_LOAD_UMIN:
14423       Opc = X86ISD::ATOMUMIN64_DAG;
14424       break;
14425     case ISD::ATOMIC_SWAP:
14426       Opc = X86ISD::ATOMSWAP64_DAG;
14427       break;
14428     }
14429     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14430     return;
14431   }
14432   case ISD::ATOMIC_LOAD:
14433     ReplaceATOMIC_LOAD(N, Results, DAG);
14434   }
14435 }
14436
14437 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14438   switch (Opcode) {
14439   default: return nullptr;
14440   case X86ISD::BSF:                return "X86ISD::BSF";
14441   case X86ISD::BSR:                return "X86ISD::BSR";
14442   case X86ISD::SHLD:               return "X86ISD::SHLD";
14443   case X86ISD::SHRD:               return "X86ISD::SHRD";
14444   case X86ISD::FAND:               return "X86ISD::FAND";
14445   case X86ISD::FANDN:              return "X86ISD::FANDN";
14446   case X86ISD::FOR:                return "X86ISD::FOR";
14447   case X86ISD::FXOR:               return "X86ISD::FXOR";
14448   case X86ISD::FSRL:               return "X86ISD::FSRL";
14449   case X86ISD::FILD:               return "X86ISD::FILD";
14450   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14451   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14452   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14453   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14454   case X86ISD::FLD:                return "X86ISD::FLD";
14455   case X86ISD::FST:                return "X86ISD::FST";
14456   case X86ISD::CALL:               return "X86ISD::CALL";
14457   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14458   case X86ISD::BT:                 return "X86ISD::BT";
14459   case X86ISD::CMP:                return "X86ISD::CMP";
14460   case X86ISD::COMI:               return "X86ISD::COMI";
14461   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14462   case X86ISD::CMPM:               return "X86ISD::CMPM";
14463   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14464   case X86ISD::SETCC:              return "X86ISD::SETCC";
14465   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14466   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14467   case X86ISD::CMOV:               return "X86ISD::CMOV";
14468   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14469   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14470   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14471   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14472   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14473   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14474   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14475   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14476   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14477   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14478   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14479   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14480   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14481   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14482   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14483   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14484   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14485   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14486   case X86ISD::HADD:               return "X86ISD::HADD";
14487   case X86ISD::HSUB:               return "X86ISD::HSUB";
14488   case X86ISD::FHADD:              return "X86ISD::FHADD";
14489   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14490   case X86ISD::UMAX:               return "X86ISD::UMAX";
14491   case X86ISD::UMIN:               return "X86ISD::UMIN";
14492   case X86ISD::SMAX:               return "X86ISD::SMAX";
14493   case X86ISD::SMIN:               return "X86ISD::SMIN";
14494   case X86ISD::FMAX:               return "X86ISD::FMAX";
14495   case X86ISD::FMIN:               return "X86ISD::FMIN";
14496   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14497   case X86ISD::FMINC:              return "X86ISD::FMINC";
14498   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14499   case X86ISD::FRCP:               return "X86ISD::FRCP";
14500   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14501   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14502   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14503   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14504   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14505   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14506   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14507   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14508   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14509   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14510   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14511   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14512   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14513   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14514   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14515   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14516   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14517   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14518   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14519   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14520   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14521   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14522   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14523   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14524   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14525   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14526   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14527   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14528   case X86ISD::VSHL:               return "X86ISD::VSHL";
14529   case X86ISD::VSRL:               return "X86ISD::VSRL";
14530   case X86ISD::VSRA:               return "X86ISD::VSRA";
14531   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14532   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14533   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14534   case X86ISD::CMPP:               return "X86ISD::CMPP";
14535   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14536   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14537   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14538   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14539   case X86ISD::ADD:                return "X86ISD::ADD";
14540   case X86ISD::SUB:                return "X86ISD::SUB";
14541   case X86ISD::ADC:                return "X86ISD::ADC";
14542   case X86ISD::SBB:                return "X86ISD::SBB";
14543   case X86ISD::SMUL:               return "X86ISD::SMUL";
14544   case X86ISD::UMUL:               return "X86ISD::UMUL";
14545   case X86ISD::INC:                return "X86ISD::INC";
14546   case X86ISD::DEC:                return "X86ISD::DEC";
14547   case X86ISD::OR:                 return "X86ISD::OR";
14548   case X86ISD::XOR:                return "X86ISD::XOR";
14549   case X86ISD::AND:                return "X86ISD::AND";
14550   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14551   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14552   case X86ISD::PTEST:              return "X86ISD::PTEST";
14553   case X86ISD::TESTP:              return "X86ISD::TESTP";
14554   case X86ISD::TESTM:              return "X86ISD::TESTM";
14555   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14556   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14557   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14558   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14559   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14560   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14561   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14562   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14563   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14564   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14565   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14566   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14567   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14568   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14569   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14570   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14571   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14572   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14573   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14574   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14575   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14576   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14577   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14578   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14579   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14580   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14581   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14582   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14583   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14584   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
14585   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14586   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14587   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14588   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14589   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14590   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14591   case X86ISD::SAHF:               return "X86ISD::SAHF";
14592   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14593   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14594   case X86ISD::FMADD:              return "X86ISD::FMADD";
14595   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14596   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14597   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14598   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14599   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14600   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14601   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14602   case X86ISD::XTEST:              return "X86ISD::XTEST";
14603   }
14604 }
14605
14606 // isLegalAddressingMode - Return true if the addressing mode represented
14607 // by AM is legal for this target, for a load/store of the specified type.
14608 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14609                                               Type *Ty) const {
14610   // X86 supports extremely general addressing modes.
14611   CodeModel::Model M = getTargetMachine().getCodeModel();
14612   Reloc::Model R = getTargetMachine().getRelocationModel();
14613
14614   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14615   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14616     return false;
14617
14618   if (AM.BaseGV) {
14619     unsigned GVFlags =
14620       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14621
14622     // If a reference to this global requires an extra load, we can't fold it.
14623     if (isGlobalStubReference(GVFlags))
14624       return false;
14625
14626     // If BaseGV requires a register for the PIC base, we cannot also have a
14627     // BaseReg specified.
14628     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14629       return false;
14630
14631     // If lower 4G is not available, then we must use rip-relative addressing.
14632     if ((M != CodeModel::Small || R != Reloc::Static) &&
14633         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
14634       return false;
14635   }
14636
14637   switch (AM.Scale) {
14638   case 0:
14639   case 1:
14640   case 2:
14641   case 4:
14642   case 8:
14643     // These scales always work.
14644     break;
14645   case 3:
14646   case 5:
14647   case 9:
14648     // These scales are formed with basereg+scalereg.  Only accept if there is
14649     // no basereg yet.
14650     if (AM.HasBaseReg)
14651       return false;
14652     break;
14653   default:  // Other stuff never works.
14654     return false;
14655   }
14656
14657   return true;
14658 }
14659
14660 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
14661   unsigned Bits = Ty->getScalarSizeInBits();
14662
14663   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
14664   // particularly cheaper than those without.
14665   if (Bits == 8)
14666     return false;
14667
14668   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
14669   // variable shifts just as cheap as scalar ones.
14670   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
14671     return false;
14672
14673   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
14674   // fully general vector.
14675   return true;
14676 }
14677
14678 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
14679   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14680     return false;
14681   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
14682   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
14683   return NumBits1 > NumBits2;
14684 }
14685
14686 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14687   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14688     return false;
14689
14690   if (!isTypeLegal(EVT::getEVT(Ty1)))
14691     return false;
14692
14693   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14694
14695   // Assuming the caller doesn't have a zeroext or signext return parameter,
14696   // truncation all the way down to i1 is valid.
14697   return true;
14698 }
14699
14700 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
14701   return isInt<32>(Imm);
14702 }
14703
14704 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
14705   // Can also use sub to handle negated immediates.
14706   return isInt<32>(Imm);
14707 }
14708
14709 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
14710   if (!VT1.isInteger() || !VT2.isInteger())
14711     return false;
14712   unsigned NumBits1 = VT1.getSizeInBits();
14713   unsigned NumBits2 = VT2.getSizeInBits();
14714   return NumBits1 > NumBits2;
14715 }
14716
14717 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
14718   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14719   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
14720 }
14721
14722 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
14723   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
14724   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
14725 }
14726
14727 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14728   EVT VT1 = Val.getValueType();
14729   if (isZExtFree(VT1, VT2))
14730     return true;
14731
14732   if (Val.getOpcode() != ISD::LOAD)
14733     return false;
14734
14735   if (!VT1.isSimple() || !VT1.isInteger() ||
14736       !VT2.isSimple() || !VT2.isInteger())
14737     return false;
14738
14739   switch (VT1.getSimpleVT().SimpleTy) {
14740   default: break;
14741   case MVT::i8:
14742   case MVT::i16:
14743   case MVT::i32:
14744     // X86 has 8, 16, and 32-bit zero-extending loads.
14745     return true;
14746   }
14747
14748   return false;
14749 }
14750
14751 bool
14752 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
14753   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
14754     return false;
14755
14756   VT = VT.getScalarType();
14757
14758   if (!VT.isSimple())
14759     return false;
14760
14761   switch (VT.getSimpleVT().SimpleTy) {
14762   case MVT::f32:
14763   case MVT::f64:
14764     return true;
14765   default:
14766     break;
14767   }
14768
14769   return false;
14770 }
14771
14772 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
14773   // i16 instructions are longer (0x66 prefix) and potentially slower.
14774   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
14775 }
14776
14777 /// isShuffleMaskLegal - Targets can use this to indicate that they only
14778 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
14779 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
14780 /// are assumed to be legal.
14781 bool
14782 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
14783                                       EVT VT) const {
14784   if (!VT.isSimple())
14785     return false;
14786
14787   MVT SVT = VT.getSimpleVT();
14788
14789   // Very little shuffling can be done for 64-bit vectors right now.
14790   if (VT.getSizeInBits() == 64)
14791     return false;
14792
14793   // FIXME: pshufb, blends, shifts.
14794   return (SVT.getVectorNumElements() == 2 ||
14795           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
14796           isMOVLMask(M, SVT) ||
14797           isSHUFPMask(M, SVT) ||
14798           isPSHUFDMask(M, SVT) ||
14799           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
14800           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
14801           isPALIGNRMask(M, SVT, Subtarget) ||
14802           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
14803           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
14804           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
14805           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()));
14806 }
14807
14808 bool
14809 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
14810                                           EVT VT) const {
14811   if (!VT.isSimple())
14812     return false;
14813
14814   MVT SVT = VT.getSimpleVT();
14815   unsigned NumElts = SVT.getVectorNumElements();
14816   // FIXME: This collection of masks seems suspect.
14817   if (NumElts == 2)
14818     return true;
14819   if (NumElts == 4 && SVT.is128BitVector()) {
14820     return (isMOVLMask(Mask, SVT)  ||
14821             isCommutedMOVLMask(Mask, SVT, true) ||
14822             isSHUFPMask(Mask, SVT) ||
14823             isSHUFPMask(Mask, SVT, /* Commuted */ true));
14824   }
14825   return false;
14826 }
14827
14828 //===----------------------------------------------------------------------===//
14829 //                           X86 Scheduler Hooks
14830 //===----------------------------------------------------------------------===//
14831
14832 /// Utility function to emit xbegin specifying the start of an RTM region.
14833 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
14834                                      const TargetInstrInfo *TII) {
14835   DebugLoc DL = MI->getDebugLoc();
14836
14837   const BasicBlock *BB = MBB->getBasicBlock();
14838   MachineFunction::iterator I = MBB;
14839   ++I;
14840
14841   // For the v = xbegin(), we generate
14842   //
14843   // thisMBB:
14844   //  xbegin sinkMBB
14845   //
14846   // mainMBB:
14847   //  eax = -1
14848   //
14849   // sinkMBB:
14850   //  v = eax
14851
14852   MachineBasicBlock *thisMBB = MBB;
14853   MachineFunction *MF = MBB->getParent();
14854   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14855   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14856   MF->insert(I, mainMBB);
14857   MF->insert(I, sinkMBB);
14858
14859   // Transfer the remainder of BB and its successor edges to sinkMBB.
14860   sinkMBB->splice(sinkMBB->begin(), MBB,
14861                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14862   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14863
14864   // thisMBB:
14865   //  xbegin sinkMBB
14866   //  # fallthrough to mainMBB
14867   //  # abortion to sinkMBB
14868   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
14869   thisMBB->addSuccessor(mainMBB);
14870   thisMBB->addSuccessor(sinkMBB);
14871
14872   // mainMBB:
14873   //  EAX = -1
14874   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
14875   mainMBB->addSuccessor(sinkMBB);
14876
14877   // sinkMBB:
14878   // EAX is live into the sinkMBB
14879   sinkMBB->addLiveIn(X86::EAX);
14880   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14881           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
14882     .addReg(X86::EAX);
14883
14884   MI->eraseFromParent();
14885   return sinkMBB;
14886 }
14887
14888 // Get CMPXCHG opcode for the specified data type.
14889 static unsigned getCmpXChgOpcode(EVT VT) {
14890   switch (VT.getSimpleVT().SimpleTy) {
14891   case MVT::i8:  return X86::LCMPXCHG8;
14892   case MVT::i16: return X86::LCMPXCHG16;
14893   case MVT::i32: return X86::LCMPXCHG32;
14894   case MVT::i64: return X86::LCMPXCHG64;
14895   default:
14896     break;
14897   }
14898   llvm_unreachable("Invalid operand size!");
14899 }
14900
14901 // Get LOAD opcode for the specified data type.
14902 static unsigned getLoadOpcode(EVT VT) {
14903   switch (VT.getSimpleVT().SimpleTy) {
14904   case MVT::i8:  return X86::MOV8rm;
14905   case MVT::i16: return X86::MOV16rm;
14906   case MVT::i32: return X86::MOV32rm;
14907   case MVT::i64: return X86::MOV64rm;
14908   default:
14909     break;
14910   }
14911   llvm_unreachable("Invalid operand size!");
14912 }
14913
14914 // Get opcode of the non-atomic one from the specified atomic instruction.
14915 static unsigned getNonAtomicOpcode(unsigned Opc) {
14916   switch (Opc) {
14917   case X86::ATOMAND8:  return X86::AND8rr;
14918   case X86::ATOMAND16: return X86::AND16rr;
14919   case X86::ATOMAND32: return X86::AND32rr;
14920   case X86::ATOMAND64: return X86::AND64rr;
14921   case X86::ATOMOR8:   return X86::OR8rr;
14922   case X86::ATOMOR16:  return X86::OR16rr;
14923   case X86::ATOMOR32:  return X86::OR32rr;
14924   case X86::ATOMOR64:  return X86::OR64rr;
14925   case X86::ATOMXOR8:  return X86::XOR8rr;
14926   case X86::ATOMXOR16: return X86::XOR16rr;
14927   case X86::ATOMXOR32: return X86::XOR32rr;
14928   case X86::ATOMXOR64: return X86::XOR64rr;
14929   }
14930   llvm_unreachable("Unhandled atomic-load-op opcode!");
14931 }
14932
14933 // Get opcode of the non-atomic one from the specified atomic instruction with
14934 // extra opcode.
14935 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
14936                                                unsigned &ExtraOpc) {
14937   switch (Opc) {
14938   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
14939   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
14940   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
14941   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
14942   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
14943   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
14944   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
14945   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
14946   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
14947   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
14948   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
14949   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
14950   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
14951   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
14952   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
14953   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
14954   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
14955   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
14956   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
14957   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
14958   }
14959   llvm_unreachable("Unhandled atomic-load-op opcode!");
14960 }
14961
14962 // Get opcode of the non-atomic one from the specified atomic instruction for
14963 // 64-bit data type on 32-bit target.
14964 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
14965   switch (Opc) {
14966   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
14967   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
14968   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
14969   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
14970   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
14971   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
14972   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
14973   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
14974   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
14975   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
14976   }
14977   llvm_unreachable("Unhandled atomic-load-op opcode!");
14978 }
14979
14980 // Get opcode of the non-atomic one from the specified atomic instruction for
14981 // 64-bit data type on 32-bit target with extra opcode.
14982 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
14983                                                    unsigned &HiOpc,
14984                                                    unsigned &ExtraOpc) {
14985   switch (Opc) {
14986   case X86::ATOMNAND6432:
14987     ExtraOpc = X86::NOT32r;
14988     HiOpc = X86::AND32rr;
14989     return X86::AND32rr;
14990   }
14991   llvm_unreachable("Unhandled atomic-load-op opcode!");
14992 }
14993
14994 // Get pseudo CMOV opcode from the specified data type.
14995 static unsigned getPseudoCMOVOpc(EVT VT) {
14996   switch (VT.getSimpleVT().SimpleTy) {
14997   case MVT::i8:  return X86::CMOV_GR8;
14998   case MVT::i16: return X86::CMOV_GR16;
14999   case MVT::i32: return X86::CMOV_GR32;
15000   default:
15001     break;
15002   }
15003   llvm_unreachable("Unknown CMOV opcode!");
15004 }
15005
15006 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15007 // They will be translated into a spin-loop or compare-exchange loop from
15008 //
15009 //    ...
15010 //    dst = atomic-fetch-op MI.addr, MI.val
15011 //    ...
15012 //
15013 // to
15014 //
15015 //    ...
15016 //    t1 = LOAD MI.addr
15017 // loop:
15018 //    t4 = phi(t1, t3 / loop)
15019 //    t2 = OP MI.val, t4
15020 //    EAX = t4
15021 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15022 //    t3 = EAX
15023 //    JNE loop
15024 // sink:
15025 //    dst = t3
15026 //    ...
15027 MachineBasicBlock *
15028 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15029                                        MachineBasicBlock *MBB) const {
15030   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15031   DebugLoc DL = MI->getDebugLoc();
15032
15033   MachineFunction *MF = MBB->getParent();
15034   MachineRegisterInfo &MRI = MF->getRegInfo();
15035
15036   const BasicBlock *BB = MBB->getBasicBlock();
15037   MachineFunction::iterator I = MBB;
15038   ++I;
15039
15040   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15041          "Unexpected number of operands");
15042
15043   assert(MI->hasOneMemOperand() &&
15044          "Expected atomic-load-op to have one memoperand");
15045
15046   // Memory Reference
15047   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15048   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15049
15050   unsigned DstReg, SrcReg;
15051   unsigned MemOpndSlot;
15052
15053   unsigned CurOp = 0;
15054
15055   DstReg = MI->getOperand(CurOp++).getReg();
15056   MemOpndSlot = CurOp;
15057   CurOp += X86::AddrNumOperands;
15058   SrcReg = MI->getOperand(CurOp++).getReg();
15059
15060   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15061   MVT::SimpleValueType VT = *RC->vt_begin();
15062   unsigned t1 = MRI.createVirtualRegister(RC);
15063   unsigned t2 = MRI.createVirtualRegister(RC);
15064   unsigned t3 = MRI.createVirtualRegister(RC);
15065   unsigned t4 = MRI.createVirtualRegister(RC);
15066   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15067
15068   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15069   unsigned LOADOpc = getLoadOpcode(VT);
15070
15071   // For the atomic load-arith operator, we generate
15072   //
15073   //  thisMBB:
15074   //    t1 = LOAD [MI.addr]
15075   //  mainMBB:
15076   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15077   //    t1 = OP MI.val, EAX
15078   //    EAX = t4
15079   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15080   //    t3 = EAX
15081   //    JNE mainMBB
15082   //  sinkMBB:
15083   //    dst = t3
15084
15085   MachineBasicBlock *thisMBB = MBB;
15086   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15087   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15088   MF->insert(I, mainMBB);
15089   MF->insert(I, sinkMBB);
15090
15091   MachineInstrBuilder MIB;
15092
15093   // Transfer the remainder of BB and its successor edges to sinkMBB.
15094   sinkMBB->splice(sinkMBB->begin(), MBB,
15095                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15096   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15097
15098   // thisMBB:
15099   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15100   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15101     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15102     if (NewMO.isReg())
15103       NewMO.setIsKill(false);
15104     MIB.addOperand(NewMO);
15105   }
15106   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15107     unsigned flags = (*MMOI)->getFlags();
15108     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15109     MachineMemOperand *MMO =
15110       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15111                                (*MMOI)->getSize(),
15112                                (*MMOI)->getBaseAlignment(),
15113                                (*MMOI)->getTBAAInfo(),
15114                                (*MMOI)->getRanges());
15115     MIB.addMemOperand(MMO);
15116   }
15117
15118   thisMBB->addSuccessor(mainMBB);
15119
15120   // mainMBB:
15121   MachineBasicBlock *origMainMBB = mainMBB;
15122
15123   // Add a PHI.
15124   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15125                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15126
15127   unsigned Opc = MI->getOpcode();
15128   switch (Opc) {
15129   default:
15130     llvm_unreachable("Unhandled atomic-load-op opcode!");
15131   case X86::ATOMAND8:
15132   case X86::ATOMAND16:
15133   case X86::ATOMAND32:
15134   case X86::ATOMAND64:
15135   case X86::ATOMOR8:
15136   case X86::ATOMOR16:
15137   case X86::ATOMOR32:
15138   case X86::ATOMOR64:
15139   case X86::ATOMXOR8:
15140   case X86::ATOMXOR16:
15141   case X86::ATOMXOR32:
15142   case X86::ATOMXOR64: {
15143     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15144     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15145       .addReg(t4);
15146     break;
15147   }
15148   case X86::ATOMNAND8:
15149   case X86::ATOMNAND16:
15150   case X86::ATOMNAND32:
15151   case X86::ATOMNAND64: {
15152     unsigned Tmp = MRI.createVirtualRegister(RC);
15153     unsigned NOTOpc;
15154     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15155     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15156       .addReg(t4);
15157     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15158     break;
15159   }
15160   case X86::ATOMMAX8:
15161   case X86::ATOMMAX16:
15162   case X86::ATOMMAX32:
15163   case X86::ATOMMAX64:
15164   case X86::ATOMMIN8:
15165   case X86::ATOMMIN16:
15166   case X86::ATOMMIN32:
15167   case X86::ATOMMIN64:
15168   case X86::ATOMUMAX8:
15169   case X86::ATOMUMAX16:
15170   case X86::ATOMUMAX32:
15171   case X86::ATOMUMAX64:
15172   case X86::ATOMUMIN8:
15173   case X86::ATOMUMIN16:
15174   case X86::ATOMUMIN32:
15175   case X86::ATOMUMIN64: {
15176     unsigned CMPOpc;
15177     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15178
15179     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15180       .addReg(SrcReg)
15181       .addReg(t4);
15182
15183     if (Subtarget->hasCMov()) {
15184       if (VT != MVT::i8) {
15185         // Native support
15186         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15187           .addReg(SrcReg)
15188           .addReg(t4);
15189       } else {
15190         // Promote i8 to i32 to use CMOV32
15191         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15192         const TargetRegisterClass *RC32 =
15193           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15194         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15195         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15196         unsigned Tmp = MRI.createVirtualRegister(RC32);
15197
15198         unsigned Undef = MRI.createVirtualRegister(RC32);
15199         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15200
15201         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15202           .addReg(Undef)
15203           .addReg(SrcReg)
15204           .addImm(X86::sub_8bit);
15205         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15206           .addReg(Undef)
15207           .addReg(t4)
15208           .addImm(X86::sub_8bit);
15209
15210         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15211           .addReg(SrcReg32)
15212           .addReg(AccReg32);
15213
15214         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15215           .addReg(Tmp, 0, X86::sub_8bit);
15216       }
15217     } else {
15218       // Use pseudo select and lower them.
15219       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15220              "Invalid atomic-load-op transformation!");
15221       unsigned SelOpc = getPseudoCMOVOpc(VT);
15222       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15223       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15224       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15225               .addReg(SrcReg).addReg(t4)
15226               .addImm(CC);
15227       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15228       // Replace the original PHI node as mainMBB is changed after CMOV
15229       // lowering.
15230       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15231         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15232       Phi->eraseFromParent();
15233     }
15234     break;
15235   }
15236   }
15237
15238   // Copy PhyReg back from virtual register.
15239   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15240     .addReg(t4);
15241
15242   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15243   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15244     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15245     if (NewMO.isReg())
15246       NewMO.setIsKill(false);
15247     MIB.addOperand(NewMO);
15248   }
15249   MIB.addReg(t2);
15250   MIB.setMemRefs(MMOBegin, MMOEnd);
15251
15252   // Copy PhyReg back to virtual register.
15253   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15254     .addReg(PhyReg);
15255
15256   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15257
15258   mainMBB->addSuccessor(origMainMBB);
15259   mainMBB->addSuccessor(sinkMBB);
15260
15261   // sinkMBB:
15262   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15263           TII->get(TargetOpcode::COPY), DstReg)
15264     .addReg(t3);
15265
15266   MI->eraseFromParent();
15267   return sinkMBB;
15268 }
15269
15270 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15271 // instructions. They will be translated into a spin-loop or compare-exchange
15272 // loop from
15273 //
15274 //    ...
15275 //    dst = atomic-fetch-op MI.addr, MI.val
15276 //    ...
15277 //
15278 // to
15279 //
15280 //    ...
15281 //    t1L = LOAD [MI.addr + 0]
15282 //    t1H = LOAD [MI.addr + 4]
15283 // loop:
15284 //    t4L = phi(t1L, t3L / loop)
15285 //    t4H = phi(t1H, t3H / loop)
15286 //    t2L = OP MI.val.lo, t4L
15287 //    t2H = OP MI.val.hi, t4H
15288 //    EAX = t4L
15289 //    EDX = t4H
15290 //    EBX = t2L
15291 //    ECX = t2H
15292 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15293 //    t3L = EAX
15294 //    t3H = EDX
15295 //    JNE loop
15296 // sink:
15297 //    dstL = t3L
15298 //    dstH = t3H
15299 //    ...
15300 MachineBasicBlock *
15301 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15302                                            MachineBasicBlock *MBB) const {
15303   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15304   DebugLoc DL = MI->getDebugLoc();
15305
15306   MachineFunction *MF = MBB->getParent();
15307   MachineRegisterInfo &MRI = MF->getRegInfo();
15308
15309   const BasicBlock *BB = MBB->getBasicBlock();
15310   MachineFunction::iterator I = MBB;
15311   ++I;
15312
15313   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15314          "Unexpected number of operands");
15315
15316   assert(MI->hasOneMemOperand() &&
15317          "Expected atomic-load-op32 to have one memoperand");
15318
15319   // Memory Reference
15320   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15321   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15322
15323   unsigned DstLoReg, DstHiReg;
15324   unsigned SrcLoReg, SrcHiReg;
15325   unsigned MemOpndSlot;
15326
15327   unsigned CurOp = 0;
15328
15329   DstLoReg = MI->getOperand(CurOp++).getReg();
15330   DstHiReg = MI->getOperand(CurOp++).getReg();
15331   MemOpndSlot = CurOp;
15332   CurOp += X86::AddrNumOperands;
15333   SrcLoReg = MI->getOperand(CurOp++).getReg();
15334   SrcHiReg = MI->getOperand(CurOp++).getReg();
15335
15336   const TargetRegisterClass *RC = &X86::GR32RegClass;
15337   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15338
15339   unsigned t1L = MRI.createVirtualRegister(RC);
15340   unsigned t1H = MRI.createVirtualRegister(RC);
15341   unsigned t2L = MRI.createVirtualRegister(RC);
15342   unsigned t2H = MRI.createVirtualRegister(RC);
15343   unsigned t3L = MRI.createVirtualRegister(RC);
15344   unsigned t3H = MRI.createVirtualRegister(RC);
15345   unsigned t4L = MRI.createVirtualRegister(RC);
15346   unsigned t4H = MRI.createVirtualRegister(RC);
15347
15348   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15349   unsigned LOADOpc = X86::MOV32rm;
15350
15351   // For the atomic load-arith operator, we generate
15352   //
15353   //  thisMBB:
15354   //    t1L = LOAD [MI.addr + 0]
15355   //    t1H = LOAD [MI.addr + 4]
15356   //  mainMBB:
15357   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15358   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15359   //    t2L = OP MI.val.lo, t4L
15360   //    t2H = OP MI.val.hi, t4H
15361   //    EBX = t2L
15362   //    ECX = t2H
15363   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15364   //    t3L = EAX
15365   //    t3H = EDX
15366   //    JNE loop
15367   //  sinkMBB:
15368   //    dstL = t3L
15369   //    dstH = t3H
15370
15371   MachineBasicBlock *thisMBB = MBB;
15372   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15373   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15374   MF->insert(I, mainMBB);
15375   MF->insert(I, sinkMBB);
15376
15377   MachineInstrBuilder MIB;
15378
15379   // Transfer the remainder of BB and its successor edges to sinkMBB.
15380   sinkMBB->splice(sinkMBB->begin(), MBB,
15381                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15382   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15383
15384   // thisMBB:
15385   // Lo
15386   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15387   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15388     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15389     if (NewMO.isReg())
15390       NewMO.setIsKill(false);
15391     MIB.addOperand(NewMO);
15392   }
15393   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15394     unsigned flags = (*MMOI)->getFlags();
15395     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15396     MachineMemOperand *MMO =
15397       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15398                                (*MMOI)->getSize(),
15399                                (*MMOI)->getBaseAlignment(),
15400                                (*MMOI)->getTBAAInfo(),
15401                                (*MMOI)->getRanges());
15402     MIB.addMemOperand(MMO);
15403   };
15404   MachineInstr *LowMI = MIB;
15405
15406   // Hi
15407   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15408   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15409     if (i == X86::AddrDisp) {
15410       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15411     } else {
15412       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15413       if (NewMO.isReg())
15414         NewMO.setIsKill(false);
15415       MIB.addOperand(NewMO);
15416     }
15417   }
15418   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15419
15420   thisMBB->addSuccessor(mainMBB);
15421
15422   // mainMBB:
15423   MachineBasicBlock *origMainMBB = mainMBB;
15424
15425   // Add PHIs.
15426   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15427                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15428   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15429                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15430
15431   unsigned Opc = MI->getOpcode();
15432   switch (Opc) {
15433   default:
15434     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15435   case X86::ATOMAND6432:
15436   case X86::ATOMOR6432:
15437   case X86::ATOMXOR6432:
15438   case X86::ATOMADD6432:
15439   case X86::ATOMSUB6432: {
15440     unsigned HiOpc;
15441     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15442     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15443       .addReg(SrcLoReg);
15444     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15445       .addReg(SrcHiReg);
15446     break;
15447   }
15448   case X86::ATOMNAND6432: {
15449     unsigned HiOpc, NOTOpc;
15450     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15451     unsigned TmpL = MRI.createVirtualRegister(RC);
15452     unsigned TmpH = MRI.createVirtualRegister(RC);
15453     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15454       .addReg(t4L);
15455     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15456       .addReg(t4H);
15457     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15458     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15459     break;
15460   }
15461   case X86::ATOMMAX6432:
15462   case X86::ATOMMIN6432:
15463   case X86::ATOMUMAX6432:
15464   case X86::ATOMUMIN6432: {
15465     unsigned HiOpc;
15466     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15467     unsigned cL = MRI.createVirtualRegister(RC8);
15468     unsigned cH = MRI.createVirtualRegister(RC8);
15469     unsigned cL32 = MRI.createVirtualRegister(RC);
15470     unsigned cH32 = MRI.createVirtualRegister(RC);
15471     unsigned cc = MRI.createVirtualRegister(RC);
15472     // cl := cmp src_lo, lo
15473     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15474       .addReg(SrcLoReg).addReg(t4L);
15475     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15476     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15477     // ch := cmp src_hi, hi
15478     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15479       .addReg(SrcHiReg).addReg(t4H);
15480     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15481     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15482     // cc := if (src_hi == hi) ? cl : ch;
15483     if (Subtarget->hasCMov()) {
15484       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15485         .addReg(cH32).addReg(cL32);
15486     } else {
15487       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15488               .addReg(cH32).addReg(cL32)
15489               .addImm(X86::COND_E);
15490       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15491     }
15492     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15493     if (Subtarget->hasCMov()) {
15494       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15495         .addReg(SrcLoReg).addReg(t4L);
15496       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15497         .addReg(SrcHiReg).addReg(t4H);
15498     } else {
15499       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15500               .addReg(SrcLoReg).addReg(t4L)
15501               .addImm(X86::COND_NE);
15502       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15503       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15504       // 2nd CMOV lowering.
15505       mainMBB->addLiveIn(X86::EFLAGS);
15506       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15507               .addReg(SrcHiReg).addReg(t4H)
15508               .addImm(X86::COND_NE);
15509       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15510       // Replace the original PHI node as mainMBB is changed after CMOV
15511       // lowering.
15512       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15513         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15514       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15515         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15516       PhiL->eraseFromParent();
15517       PhiH->eraseFromParent();
15518     }
15519     break;
15520   }
15521   case X86::ATOMSWAP6432: {
15522     unsigned HiOpc;
15523     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15524     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15525     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15526     break;
15527   }
15528   }
15529
15530   // Copy EDX:EAX back from HiReg:LoReg
15531   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15532   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15533   // Copy ECX:EBX from t1H:t1L
15534   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15535   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15536
15537   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15538   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15539     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15540     if (NewMO.isReg())
15541       NewMO.setIsKill(false);
15542     MIB.addOperand(NewMO);
15543   }
15544   MIB.setMemRefs(MMOBegin, MMOEnd);
15545
15546   // Copy EDX:EAX back to t3H:t3L
15547   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15548   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15549
15550   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15551
15552   mainMBB->addSuccessor(origMainMBB);
15553   mainMBB->addSuccessor(sinkMBB);
15554
15555   // sinkMBB:
15556   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15557           TII->get(TargetOpcode::COPY), DstLoReg)
15558     .addReg(t3L);
15559   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15560           TII->get(TargetOpcode::COPY), DstHiReg)
15561     .addReg(t3H);
15562
15563   MI->eraseFromParent();
15564   return sinkMBB;
15565 }
15566
15567 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15568 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15569 // in the .td file.
15570 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15571                                        const TargetInstrInfo *TII) {
15572   unsigned Opc;
15573   switch (MI->getOpcode()) {
15574   default: llvm_unreachable("illegal opcode!");
15575   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15576   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15577   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15578   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15579   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15580   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15581   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15582   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15583   }
15584
15585   DebugLoc dl = MI->getDebugLoc();
15586   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15587
15588   unsigned NumArgs = MI->getNumOperands();
15589   for (unsigned i = 1; i < NumArgs; ++i) {
15590     MachineOperand &Op = MI->getOperand(i);
15591     if (!(Op.isReg() && Op.isImplicit()))
15592       MIB.addOperand(Op);
15593   }
15594   if (MI->hasOneMemOperand())
15595     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15596
15597   BuildMI(*BB, MI, dl,
15598     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15599     .addReg(X86::XMM0);
15600
15601   MI->eraseFromParent();
15602   return BB;
15603 }
15604
15605 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15606 // defs in an instruction pattern
15607 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15608                                        const TargetInstrInfo *TII) {
15609   unsigned Opc;
15610   switch (MI->getOpcode()) {
15611   default: llvm_unreachable("illegal opcode!");
15612   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15613   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15614   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
15615   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
15616   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
15617   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
15618   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
15619   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
15620   }
15621
15622   DebugLoc dl = MI->getDebugLoc();
15623   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15624
15625   unsigned NumArgs = MI->getNumOperands(); // remove the results
15626   for (unsigned i = 1; i < NumArgs; ++i) {
15627     MachineOperand &Op = MI->getOperand(i);
15628     if (!(Op.isReg() && Op.isImplicit()))
15629       MIB.addOperand(Op);
15630   }
15631   if (MI->hasOneMemOperand())
15632     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15633
15634   BuildMI(*BB, MI, dl,
15635     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15636     .addReg(X86::ECX);
15637
15638   MI->eraseFromParent();
15639   return BB;
15640 }
15641
15642 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
15643                                        const TargetInstrInfo *TII,
15644                                        const X86Subtarget* Subtarget) {
15645   DebugLoc dl = MI->getDebugLoc();
15646
15647   // Address into RAX/EAX, other two args into ECX, EDX.
15648   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
15649   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
15650   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
15651   for (int i = 0; i < X86::AddrNumOperands; ++i)
15652     MIB.addOperand(MI->getOperand(i));
15653
15654   unsigned ValOps = X86::AddrNumOperands;
15655   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
15656     .addReg(MI->getOperand(ValOps).getReg());
15657   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
15658     .addReg(MI->getOperand(ValOps+1).getReg());
15659
15660   // The instruction doesn't actually take any operands though.
15661   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
15662
15663   MI->eraseFromParent(); // The pseudo is gone now.
15664   return BB;
15665 }
15666
15667 MachineBasicBlock *
15668 X86TargetLowering::EmitVAARG64WithCustomInserter(
15669                    MachineInstr *MI,
15670                    MachineBasicBlock *MBB) const {
15671   // Emit va_arg instruction on X86-64.
15672
15673   // Operands to this pseudo-instruction:
15674   // 0  ) Output        : destination address (reg)
15675   // 1-5) Input         : va_list address (addr, i64mem)
15676   // 6  ) ArgSize       : Size (in bytes) of vararg type
15677   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
15678   // 8  ) Align         : Alignment of type
15679   // 9  ) EFLAGS (implicit-def)
15680
15681   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
15682   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
15683
15684   unsigned DestReg = MI->getOperand(0).getReg();
15685   MachineOperand &Base = MI->getOperand(1);
15686   MachineOperand &Scale = MI->getOperand(2);
15687   MachineOperand &Index = MI->getOperand(3);
15688   MachineOperand &Disp = MI->getOperand(4);
15689   MachineOperand &Segment = MI->getOperand(5);
15690   unsigned ArgSize = MI->getOperand(6).getImm();
15691   unsigned ArgMode = MI->getOperand(7).getImm();
15692   unsigned Align = MI->getOperand(8).getImm();
15693
15694   // Memory Reference
15695   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
15696   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15697   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15698
15699   // Machine Information
15700   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15701   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
15702   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
15703   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
15704   DebugLoc DL = MI->getDebugLoc();
15705
15706   // struct va_list {
15707   //   i32   gp_offset
15708   //   i32   fp_offset
15709   //   i64   overflow_area (address)
15710   //   i64   reg_save_area (address)
15711   // }
15712   // sizeof(va_list) = 24
15713   // alignment(va_list) = 8
15714
15715   unsigned TotalNumIntRegs = 6;
15716   unsigned TotalNumXMMRegs = 8;
15717   bool UseGPOffset = (ArgMode == 1);
15718   bool UseFPOffset = (ArgMode == 2);
15719   unsigned MaxOffset = TotalNumIntRegs * 8 +
15720                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
15721
15722   /* Align ArgSize to a multiple of 8 */
15723   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
15724   bool NeedsAlign = (Align > 8);
15725
15726   MachineBasicBlock *thisMBB = MBB;
15727   MachineBasicBlock *overflowMBB;
15728   MachineBasicBlock *offsetMBB;
15729   MachineBasicBlock *endMBB;
15730
15731   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
15732   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
15733   unsigned OffsetReg = 0;
15734
15735   if (!UseGPOffset && !UseFPOffset) {
15736     // If we only pull from the overflow region, we don't create a branch.
15737     // We don't need to alter control flow.
15738     OffsetDestReg = 0; // unused
15739     OverflowDestReg = DestReg;
15740
15741     offsetMBB = nullptr;
15742     overflowMBB = thisMBB;
15743     endMBB = thisMBB;
15744   } else {
15745     // First emit code to check if gp_offset (or fp_offset) is below the bound.
15746     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
15747     // If not, pull from overflow_area. (branch to overflowMBB)
15748     //
15749     //       thisMBB
15750     //         |     .
15751     //         |        .
15752     //     offsetMBB   overflowMBB
15753     //         |        .
15754     //         |     .
15755     //        endMBB
15756
15757     // Registers for the PHI in endMBB
15758     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
15759     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
15760
15761     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15762     MachineFunction *MF = MBB->getParent();
15763     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15764     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15765     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
15766
15767     MachineFunction::iterator MBBIter = MBB;
15768     ++MBBIter;
15769
15770     // Insert the new basic blocks
15771     MF->insert(MBBIter, offsetMBB);
15772     MF->insert(MBBIter, overflowMBB);
15773     MF->insert(MBBIter, endMBB);
15774
15775     // Transfer the remainder of MBB and its successor edges to endMBB.
15776     endMBB->splice(endMBB->begin(), thisMBB,
15777                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
15778     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
15779
15780     // Make offsetMBB and overflowMBB successors of thisMBB
15781     thisMBB->addSuccessor(offsetMBB);
15782     thisMBB->addSuccessor(overflowMBB);
15783
15784     // endMBB is a successor of both offsetMBB and overflowMBB
15785     offsetMBB->addSuccessor(endMBB);
15786     overflowMBB->addSuccessor(endMBB);
15787
15788     // Load the offset value into a register
15789     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15790     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
15791       .addOperand(Base)
15792       .addOperand(Scale)
15793       .addOperand(Index)
15794       .addDisp(Disp, UseFPOffset ? 4 : 0)
15795       .addOperand(Segment)
15796       .setMemRefs(MMOBegin, MMOEnd);
15797
15798     // Check if there is enough room left to pull this argument.
15799     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
15800       .addReg(OffsetReg)
15801       .addImm(MaxOffset + 8 - ArgSizeA8);
15802
15803     // Branch to "overflowMBB" if offset >= max
15804     // Fall through to "offsetMBB" otherwise
15805     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
15806       .addMBB(overflowMBB);
15807   }
15808
15809   // In offsetMBB, emit code to use the reg_save_area.
15810   if (offsetMBB) {
15811     assert(OffsetReg != 0);
15812
15813     // Read the reg_save_area address.
15814     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
15815     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
15816       .addOperand(Base)
15817       .addOperand(Scale)
15818       .addOperand(Index)
15819       .addDisp(Disp, 16)
15820       .addOperand(Segment)
15821       .setMemRefs(MMOBegin, MMOEnd);
15822
15823     // Zero-extend the offset
15824     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
15825       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
15826         .addImm(0)
15827         .addReg(OffsetReg)
15828         .addImm(X86::sub_32bit);
15829
15830     // Add the offset to the reg_save_area to get the final address.
15831     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
15832       .addReg(OffsetReg64)
15833       .addReg(RegSaveReg);
15834
15835     // Compute the offset for the next argument
15836     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
15837     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
15838       .addReg(OffsetReg)
15839       .addImm(UseFPOffset ? 16 : 8);
15840
15841     // Store it back into the va_list.
15842     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
15843       .addOperand(Base)
15844       .addOperand(Scale)
15845       .addOperand(Index)
15846       .addDisp(Disp, UseFPOffset ? 4 : 0)
15847       .addOperand(Segment)
15848       .addReg(NextOffsetReg)
15849       .setMemRefs(MMOBegin, MMOEnd);
15850
15851     // Jump to endMBB
15852     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
15853       .addMBB(endMBB);
15854   }
15855
15856   //
15857   // Emit code to use overflow area
15858   //
15859
15860   // Load the overflow_area address into a register.
15861   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
15862   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
15863     .addOperand(Base)
15864     .addOperand(Scale)
15865     .addOperand(Index)
15866     .addDisp(Disp, 8)
15867     .addOperand(Segment)
15868     .setMemRefs(MMOBegin, MMOEnd);
15869
15870   // If we need to align it, do so. Otherwise, just copy the address
15871   // to OverflowDestReg.
15872   if (NeedsAlign) {
15873     // Align the overflow address
15874     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
15875     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
15876
15877     // aligned_addr = (addr + (align-1)) & ~(align-1)
15878     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
15879       .addReg(OverflowAddrReg)
15880       .addImm(Align-1);
15881
15882     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
15883       .addReg(TmpReg)
15884       .addImm(~(uint64_t)(Align-1));
15885   } else {
15886     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
15887       .addReg(OverflowAddrReg);
15888   }
15889
15890   // Compute the next overflow address after this argument.
15891   // (the overflow address should be kept 8-byte aligned)
15892   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
15893   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
15894     .addReg(OverflowDestReg)
15895     .addImm(ArgSizeA8);
15896
15897   // Store the new overflow address.
15898   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
15899     .addOperand(Base)
15900     .addOperand(Scale)
15901     .addOperand(Index)
15902     .addDisp(Disp, 8)
15903     .addOperand(Segment)
15904     .addReg(NextAddrReg)
15905     .setMemRefs(MMOBegin, MMOEnd);
15906
15907   // If we branched, emit the PHI to the front of endMBB.
15908   if (offsetMBB) {
15909     BuildMI(*endMBB, endMBB->begin(), DL,
15910             TII->get(X86::PHI), DestReg)
15911       .addReg(OffsetDestReg).addMBB(offsetMBB)
15912       .addReg(OverflowDestReg).addMBB(overflowMBB);
15913   }
15914
15915   // Erase the pseudo instruction
15916   MI->eraseFromParent();
15917
15918   return endMBB;
15919 }
15920
15921 MachineBasicBlock *
15922 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
15923                                                  MachineInstr *MI,
15924                                                  MachineBasicBlock *MBB) const {
15925   // Emit code to save XMM registers to the stack. The ABI says that the
15926   // number of registers to save is given in %al, so it's theoretically
15927   // possible to do an indirect jump trick to avoid saving all of them,
15928   // however this code takes a simpler approach and just executes all
15929   // of the stores if %al is non-zero. It's less code, and it's probably
15930   // easier on the hardware branch predictor, and stores aren't all that
15931   // expensive anyway.
15932
15933   // Create the new basic blocks. One block contains all the XMM stores,
15934   // and one block is the final destination regardless of whether any
15935   // stores were performed.
15936   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
15937   MachineFunction *F = MBB->getParent();
15938   MachineFunction::iterator MBBIter = MBB;
15939   ++MBBIter;
15940   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
15941   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
15942   F->insert(MBBIter, XMMSaveMBB);
15943   F->insert(MBBIter, EndMBB);
15944
15945   // Transfer the remainder of MBB and its successor edges to EndMBB.
15946   EndMBB->splice(EndMBB->begin(), MBB,
15947                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15948   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
15949
15950   // The original block will now fall through to the XMM save block.
15951   MBB->addSuccessor(XMMSaveMBB);
15952   // The XMMSaveMBB will fall through to the end block.
15953   XMMSaveMBB->addSuccessor(EndMBB);
15954
15955   // Now add the instructions.
15956   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15957   DebugLoc DL = MI->getDebugLoc();
15958
15959   unsigned CountReg = MI->getOperand(0).getReg();
15960   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
15961   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
15962
15963   if (!Subtarget->isTargetWin64()) {
15964     // If %al is 0, branch around the XMM save block.
15965     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
15966     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
15967     MBB->addSuccessor(EndMBB);
15968   }
15969
15970   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
15971   // that was just emitted, but clearly shouldn't be "saved".
15972   assert((MI->getNumOperands() <= 3 ||
15973           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
15974           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
15975          && "Expected last argument to be EFLAGS");
15976   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
15977   // In the XMM save block, save all the XMM argument registers.
15978   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
15979     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
15980     MachineMemOperand *MMO =
15981       F->getMachineMemOperand(
15982           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
15983         MachineMemOperand::MOStore,
15984         /*Size=*/16, /*Align=*/16);
15985     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
15986       .addFrameIndex(RegSaveFrameIndex)
15987       .addImm(/*Scale=*/1)
15988       .addReg(/*IndexReg=*/0)
15989       .addImm(/*Disp=*/Offset)
15990       .addReg(/*Segment=*/0)
15991       .addReg(MI->getOperand(i).getReg())
15992       .addMemOperand(MMO);
15993   }
15994
15995   MI->eraseFromParent();   // The pseudo instruction is gone now.
15996
15997   return EndMBB;
15998 }
15999
16000 // The EFLAGS operand of SelectItr might be missing a kill marker
16001 // because there were multiple uses of EFLAGS, and ISel didn't know
16002 // which to mark. Figure out whether SelectItr should have had a
16003 // kill marker, and set it if it should. Returns the correct kill
16004 // marker value.
16005 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16006                                      MachineBasicBlock* BB,
16007                                      const TargetRegisterInfo* TRI) {
16008   // Scan forward through BB for a use/def of EFLAGS.
16009   MachineBasicBlock::iterator miI(std::next(SelectItr));
16010   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16011     const MachineInstr& mi = *miI;
16012     if (mi.readsRegister(X86::EFLAGS))
16013       return false;
16014     if (mi.definesRegister(X86::EFLAGS))
16015       break; // Should have kill-flag - update below.
16016   }
16017
16018   // If we hit the end of the block, check whether EFLAGS is live into a
16019   // successor.
16020   if (miI == BB->end()) {
16021     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16022                                           sEnd = BB->succ_end();
16023          sItr != sEnd; ++sItr) {
16024       MachineBasicBlock* succ = *sItr;
16025       if (succ->isLiveIn(X86::EFLAGS))
16026         return false;
16027     }
16028   }
16029
16030   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16031   // out. SelectMI should have a kill flag on EFLAGS.
16032   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16033   return true;
16034 }
16035
16036 MachineBasicBlock *
16037 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16038                                      MachineBasicBlock *BB) const {
16039   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16040   DebugLoc DL = MI->getDebugLoc();
16041
16042   // To "insert" a SELECT_CC instruction, we actually have to insert the
16043   // diamond control-flow pattern.  The incoming instruction knows the
16044   // destination vreg to set, the condition code register to branch on, the
16045   // true/false values to select between, and a branch opcode to use.
16046   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16047   MachineFunction::iterator It = BB;
16048   ++It;
16049
16050   //  thisMBB:
16051   //  ...
16052   //   TrueVal = ...
16053   //   cmpTY ccX, r1, r2
16054   //   bCC copy1MBB
16055   //   fallthrough --> copy0MBB
16056   MachineBasicBlock *thisMBB = BB;
16057   MachineFunction *F = BB->getParent();
16058   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16059   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16060   F->insert(It, copy0MBB);
16061   F->insert(It, sinkMBB);
16062
16063   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16064   // live into the sink and copy blocks.
16065   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16066   if (!MI->killsRegister(X86::EFLAGS) &&
16067       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16068     copy0MBB->addLiveIn(X86::EFLAGS);
16069     sinkMBB->addLiveIn(X86::EFLAGS);
16070   }
16071
16072   // Transfer the remainder of BB and its successor edges to sinkMBB.
16073   sinkMBB->splice(sinkMBB->begin(), BB,
16074                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16075   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16076
16077   // Add the true and fallthrough blocks as its successors.
16078   BB->addSuccessor(copy0MBB);
16079   BB->addSuccessor(sinkMBB);
16080
16081   // Create the conditional branch instruction.
16082   unsigned Opc =
16083     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16084   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16085
16086   //  copy0MBB:
16087   //   %FalseValue = ...
16088   //   # fallthrough to sinkMBB
16089   copy0MBB->addSuccessor(sinkMBB);
16090
16091   //  sinkMBB:
16092   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16093   //  ...
16094   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16095           TII->get(X86::PHI), MI->getOperand(0).getReg())
16096     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16097     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16098
16099   MI->eraseFromParent();   // The pseudo instruction is gone now.
16100   return sinkMBB;
16101 }
16102
16103 MachineBasicBlock *
16104 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16105                                         bool Is64Bit) const {
16106   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16107   DebugLoc DL = MI->getDebugLoc();
16108   MachineFunction *MF = BB->getParent();
16109   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16110
16111   assert(MF->shouldSplitStack());
16112
16113   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16114   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16115
16116   // BB:
16117   //  ... [Till the alloca]
16118   // If stacklet is not large enough, jump to mallocMBB
16119   //
16120   // bumpMBB:
16121   //  Allocate by subtracting from RSP
16122   //  Jump to continueMBB
16123   //
16124   // mallocMBB:
16125   //  Allocate by call to runtime
16126   //
16127   // continueMBB:
16128   //  ...
16129   //  [rest of original BB]
16130   //
16131
16132   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16133   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16134   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16135
16136   MachineRegisterInfo &MRI = MF->getRegInfo();
16137   const TargetRegisterClass *AddrRegClass =
16138     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16139
16140   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16141     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16142     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16143     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16144     sizeVReg = MI->getOperand(1).getReg(),
16145     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16146
16147   MachineFunction::iterator MBBIter = BB;
16148   ++MBBIter;
16149
16150   MF->insert(MBBIter, bumpMBB);
16151   MF->insert(MBBIter, mallocMBB);
16152   MF->insert(MBBIter, continueMBB);
16153
16154   continueMBB->splice(continueMBB->begin(), BB,
16155                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16156   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16157
16158   // Add code to the main basic block to check if the stack limit has been hit,
16159   // and if so, jump to mallocMBB otherwise to bumpMBB.
16160   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16161   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16162     .addReg(tmpSPVReg).addReg(sizeVReg);
16163   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16164     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16165     .addReg(SPLimitVReg);
16166   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16167
16168   // bumpMBB simply decreases the stack pointer, since we know the current
16169   // stacklet has enough space.
16170   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16171     .addReg(SPLimitVReg);
16172   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16173     .addReg(SPLimitVReg);
16174   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16175
16176   // Calls into a routine in libgcc to allocate more space from the heap.
16177   const uint32_t *RegMask =
16178     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16179   if (Is64Bit) {
16180     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16181       .addReg(sizeVReg);
16182     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16183       .addExternalSymbol("__morestack_allocate_stack_space")
16184       .addRegMask(RegMask)
16185       .addReg(X86::RDI, RegState::Implicit)
16186       .addReg(X86::RAX, RegState::ImplicitDefine);
16187   } else {
16188     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16189       .addImm(12);
16190     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16191     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16192       .addExternalSymbol("__morestack_allocate_stack_space")
16193       .addRegMask(RegMask)
16194       .addReg(X86::EAX, RegState::ImplicitDefine);
16195   }
16196
16197   if (!Is64Bit)
16198     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16199       .addImm(16);
16200
16201   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16202     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16203   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16204
16205   // Set up the CFG correctly.
16206   BB->addSuccessor(bumpMBB);
16207   BB->addSuccessor(mallocMBB);
16208   mallocMBB->addSuccessor(continueMBB);
16209   bumpMBB->addSuccessor(continueMBB);
16210
16211   // Take care of the PHI nodes.
16212   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16213           MI->getOperand(0).getReg())
16214     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16215     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16216
16217   // Delete the original pseudo instruction.
16218   MI->eraseFromParent();
16219
16220   // And we're done.
16221   return continueMBB;
16222 }
16223
16224 MachineBasicBlock *
16225 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16226                                           MachineBasicBlock *BB) const {
16227   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16228   DebugLoc DL = MI->getDebugLoc();
16229
16230   assert(!Subtarget->isTargetMacho());
16231
16232   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16233   // non-trivial part is impdef of ESP.
16234
16235   if (Subtarget->isTargetWin64()) {
16236     if (Subtarget->isTargetCygMing()) {
16237       // ___chkstk(Mingw64):
16238       // Clobbers R10, R11, RAX and EFLAGS.
16239       // Updates RSP.
16240       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16241         .addExternalSymbol("___chkstk")
16242         .addReg(X86::RAX, RegState::Implicit)
16243         .addReg(X86::RSP, RegState::Implicit)
16244         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16245         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16246         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16247     } else {
16248       // __chkstk(MSVCRT): does not update stack pointer.
16249       // Clobbers R10, R11 and EFLAGS.
16250       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16251         .addExternalSymbol("__chkstk")
16252         .addReg(X86::RAX, RegState::Implicit)
16253         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16254       // RAX has the offset to be subtracted from RSP.
16255       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16256         .addReg(X86::RSP)
16257         .addReg(X86::RAX);
16258     }
16259   } else {
16260     const char *StackProbeSymbol =
16261       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16262
16263     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16264       .addExternalSymbol(StackProbeSymbol)
16265       .addReg(X86::EAX, RegState::Implicit)
16266       .addReg(X86::ESP, RegState::Implicit)
16267       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16268       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16269       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16270   }
16271
16272   MI->eraseFromParent();   // The pseudo instruction is gone now.
16273   return BB;
16274 }
16275
16276 MachineBasicBlock *
16277 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16278                                       MachineBasicBlock *BB) const {
16279   // This is pretty easy.  We're taking the value that we received from
16280   // our load from the relocation, sticking it in either RDI (x86-64)
16281   // or EAX and doing an indirect call.  The return value will then
16282   // be in the normal return register.
16283   const X86InstrInfo *TII
16284     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16285   DebugLoc DL = MI->getDebugLoc();
16286   MachineFunction *F = BB->getParent();
16287
16288   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16289   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16290
16291   // Get a register mask for the lowered call.
16292   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16293   // proper register mask.
16294   const uint32_t *RegMask =
16295     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16296   if (Subtarget->is64Bit()) {
16297     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16298                                       TII->get(X86::MOV64rm), X86::RDI)
16299     .addReg(X86::RIP)
16300     .addImm(0).addReg(0)
16301     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16302                       MI->getOperand(3).getTargetFlags())
16303     .addReg(0);
16304     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16305     addDirectMem(MIB, X86::RDI);
16306     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16307   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16308     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16309                                       TII->get(X86::MOV32rm), X86::EAX)
16310     .addReg(0)
16311     .addImm(0).addReg(0)
16312     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16313                       MI->getOperand(3).getTargetFlags())
16314     .addReg(0);
16315     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16316     addDirectMem(MIB, X86::EAX);
16317     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16318   } else {
16319     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16320                                       TII->get(X86::MOV32rm), X86::EAX)
16321     .addReg(TII->getGlobalBaseReg(F))
16322     .addImm(0).addReg(0)
16323     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16324                       MI->getOperand(3).getTargetFlags())
16325     .addReg(0);
16326     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16327     addDirectMem(MIB, X86::EAX);
16328     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16329   }
16330
16331   MI->eraseFromParent(); // The pseudo instruction is gone now.
16332   return BB;
16333 }
16334
16335 MachineBasicBlock *
16336 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16337                                     MachineBasicBlock *MBB) const {
16338   DebugLoc DL = MI->getDebugLoc();
16339   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16340
16341   MachineFunction *MF = MBB->getParent();
16342   MachineRegisterInfo &MRI = MF->getRegInfo();
16343
16344   const BasicBlock *BB = MBB->getBasicBlock();
16345   MachineFunction::iterator I = MBB;
16346   ++I;
16347
16348   // Memory Reference
16349   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16350   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16351
16352   unsigned DstReg;
16353   unsigned MemOpndSlot = 0;
16354
16355   unsigned CurOp = 0;
16356
16357   DstReg = MI->getOperand(CurOp++).getReg();
16358   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16359   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16360   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16361   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16362
16363   MemOpndSlot = CurOp;
16364
16365   MVT PVT = getPointerTy();
16366   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16367          "Invalid Pointer Size!");
16368
16369   // For v = setjmp(buf), we generate
16370   //
16371   // thisMBB:
16372   //  buf[LabelOffset] = restoreMBB
16373   //  SjLjSetup restoreMBB
16374   //
16375   // mainMBB:
16376   //  v_main = 0
16377   //
16378   // sinkMBB:
16379   //  v = phi(main, restore)
16380   //
16381   // restoreMBB:
16382   //  v_restore = 1
16383
16384   MachineBasicBlock *thisMBB = MBB;
16385   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16386   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16387   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16388   MF->insert(I, mainMBB);
16389   MF->insert(I, sinkMBB);
16390   MF->push_back(restoreMBB);
16391
16392   MachineInstrBuilder MIB;
16393
16394   // Transfer the remainder of BB and its successor edges to sinkMBB.
16395   sinkMBB->splice(sinkMBB->begin(), MBB,
16396                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16397   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16398
16399   // thisMBB:
16400   unsigned PtrStoreOpc = 0;
16401   unsigned LabelReg = 0;
16402   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16403   Reloc::Model RM = getTargetMachine().getRelocationModel();
16404   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16405                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16406
16407   // Prepare IP either in reg or imm.
16408   if (!UseImmLabel) {
16409     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16410     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16411     LabelReg = MRI.createVirtualRegister(PtrRC);
16412     if (Subtarget->is64Bit()) {
16413       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16414               .addReg(X86::RIP)
16415               .addImm(0)
16416               .addReg(0)
16417               .addMBB(restoreMBB)
16418               .addReg(0);
16419     } else {
16420       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16421       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16422               .addReg(XII->getGlobalBaseReg(MF))
16423               .addImm(0)
16424               .addReg(0)
16425               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16426               .addReg(0);
16427     }
16428   } else
16429     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16430   // Store IP
16431   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16432   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16433     if (i == X86::AddrDisp)
16434       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16435     else
16436       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16437   }
16438   if (!UseImmLabel)
16439     MIB.addReg(LabelReg);
16440   else
16441     MIB.addMBB(restoreMBB);
16442   MIB.setMemRefs(MMOBegin, MMOEnd);
16443   // Setup
16444   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16445           .addMBB(restoreMBB);
16446
16447   const X86RegisterInfo *RegInfo =
16448     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16449   MIB.addRegMask(RegInfo->getNoPreservedMask());
16450   thisMBB->addSuccessor(mainMBB);
16451   thisMBB->addSuccessor(restoreMBB);
16452
16453   // mainMBB:
16454   //  EAX = 0
16455   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16456   mainMBB->addSuccessor(sinkMBB);
16457
16458   // sinkMBB:
16459   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16460           TII->get(X86::PHI), DstReg)
16461     .addReg(mainDstReg).addMBB(mainMBB)
16462     .addReg(restoreDstReg).addMBB(restoreMBB);
16463
16464   // restoreMBB:
16465   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16466   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16467   restoreMBB->addSuccessor(sinkMBB);
16468
16469   MI->eraseFromParent();
16470   return sinkMBB;
16471 }
16472
16473 MachineBasicBlock *
16474 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16475                                      MachineBasicBlock *MBB) const {
16476   DebugLoc DL = MI->getDebugLoc();
16477   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16478
16479   MachineFunction *MF = MBB->getParent();
16480   MachineRegisterInfo &MRI = MF->getRegInfo();
16481
16482   // Memory Reference
16483   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16484   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16485
16486   MVT PVT = getPointerTy();
16487   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16488          "Invalid Pointer Size!");
16489
16490   const TargetRegisterClass *RC =
16491     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16492   unsigned Tmp = MRI.createVirtualRegister(RC);
16493   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16494   const X86RegisterInfo *RegInfo =
16495     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16496   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16497   unsigned SP = RegInfo->getStackRegister();
16498
16499   MachineInstrBuilder MIB;
16500
16501   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16502   const int64_t SPOffset = 2 * PVT.getStoreSize();
16503
16504   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16505   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16506
16507   // Reload FP
16508   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16509   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16510     MIB.addOperand(MI->getOperand(i));
16511   MIB.setMemRefs(MMOBegin, MMOEnd);
16512   // Reload IP
16513   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16514   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16515     if (i == X86::AddrDisp)
16516       MIB.addDisp(MI->getOperand(i), LabelOffset);
16517     else
16518       MIB.addOperand(MI->getOperand(i));
16519   }
16520   MIB.setMemRefs(MMOBegin, MMOEnd);
16521   // Reload SP
16522   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16523   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16524     if (i == X86::AddrDisp)
16525       MIB.addDisp(MI->getOperand(i), SPOffset);
16526     else
16527       MIB.addOperand(MI->getOperand(i));
16528   }
16529   MIB.setMemRefs(MMOBegin, MMOEnd);
16530   // Jump
16531   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16532
16533   MI->eraseFromParent();
16534   return MBB;
16535 }
16536
16537 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16538 // accumulator loops. Writing back to the accumulator allows the coalescer
16539 // to remove extra copies in the loop.   
16540 MachineBasicBlock *
16541 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16542                                  MachineBasicBlock *MBB) const {
16543   MachineOperand &AddendOp = MI->getOperand(3);
16544
16545   // Bail out early if the addend isn't a register - we can't switch these.
16546   if (!AddendOp.isReg())
16547     return MBB;
16548
16549   MachineFunction &MF = *MBB->getParent();
16550   MachineRegisterInfo &MRI = MF.getRegInfo();
16551
16552   // Check whether the addend is defined by a PHI:
16553   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16554   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16555   if (!AddendDef.isPHI())
16556     return MBB;
16557
16558   // Look for the following pattern:
16559   // loop:
16560   //   %addend = phi [%entry, 0], [%loop, %result]
16561   //   ...
16562   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16563
16564   // Replace with:
16565   //   loop:
16566   //   %addend = phi [%entry, 0], [%loop, %result]
16567   //   ...
16568   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16569
16570   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16571     assert(AddendDef.getOperand(i).isReg());
16572     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16573     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16574     if (&PHISrcInst == MI) {
16575       // Found a matching instruction.
16576       unsigned NewFMAOpc = 0;
16577       switch (MI->getOpcode()) {
16578         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16579         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16580         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16581         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16582         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16583         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16584         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16585         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16586         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16587         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16588         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16589         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16590         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16591         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16592         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16593         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16594         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16595         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16596         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16597         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16598         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16599         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16600         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16601         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16602         default: llvm_unreachable("Unrecognized FMA variant.");
16603       }
16604
16605       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16606       MachineInstrBuilder MIB =
16607         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16608         .addOperand(MI->getOperand(0))
16609         .addOperand(MI->getOperand(3))
16610         .addOperand(MI->getOperand(2))
16611         .addOperand(MI->getOperand(1));
16612       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16613       MI->eraseFromParent();
16614     }
16615   }
16616
16617   return MBB;
16618 }
16619
16620 MachineBasicBlock *
16621 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
16622                                                MachineBasicBlock *BB) const {
16623   switch (MI->getOpcode()) {
16624   default: llvm_unreachable("Unexpected instr type to insert");
16625   case X86::TAILJMPd64:
16626   case X86::TAILJMPr64:
16627   case X86::TAILJMPm64:
16628     llvm_unreachable("TAILJMP64 would not be touched here.");
16629   case X86::TCRETURNdi64:
16630   case X86::TCRETURNri64:
16631   case X86::TCRETURNmi64:
16632     return BB;
16633   case X86::WIN_ALLOCA:
16634     return EmitLoweredWinAlloca(MI, BB);
16635   case X86::SEG_ALLOCA_32:
16636     return EmitLoweredSegAlloca(MI, BB, false);
16637   case X86::SEG_ALLOCA_64:
16638     return EmitLoweredSegAlloca(MI, BB, true);
16639   case X86::TLSCall_32:
16640   case X86::TLSCall_64:
16641     return EmitLoweredTLSCall(MI, BB);
16642   case X86::CMOV_GR8:
16643   case X86::CMOV_FR32:
16644   case X86::CMOV_FR64:
16645   case X86::CMOV_V4F32:
16646   case X86::CMOV_V2F64:
16647   case X86::CMOV_V2I64:
16648   case X86::CMOV_V8F32:
16649   case X86::CMOV_V4F64:
16650   case X86::CMOV_V4I64:
16651   case X86::CMOV_V16F32:
16652   case X86::CMOV_V8F64:
16653   case X86::CMOV_V8I64:
16654   case X86::CMOV_GR16:
16655   case X86::CMOV_GR32:
16656   case X86::CMOV_RFP32:
16657   case X86::CMOV_RFP64:
16658   case X86::CMOV_RFP80:
16659     return EmitLoweredSelect(MI, BB);
16660
16661   case X86::FP32_TO_INT16_IN_MEM:
16662   case X86::FP32_TO_INT32_IN_MEM:
16663   case X86::FP32_TO_INT64_IN_MEM:
16664   case X86::FP64_TO_INT16_IN_MEM:
16665   case X86::FP64_TO_INT32_IN_MEM:
16666   case X86::FP64_TO_INT64_IN_MEM:
16667   case X86::FP80_TO_INT16_IN_MEM:
16668   case X86::FP80_TO_INT32_IN_MEM:
16669   case X86::FP80_TO_INT64_IN_MEM: {
16670     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16671     DebugLoc DL = MI->getDebugLoc();
16672
16673     // Change the floating point control register to use "round towards zero"
16674     // mode when truncating to an integer value.
16675     MachineFunction *F = BB->getParent();
16676     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
16677     addFrameReference(BuildMI(*BB, MI, DL,
16678                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
16679
16680     // Load the old value of the high byte of the control word...
16681     unsigned OldCW =
16682       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
16683     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
16684                       CWFrameIdx);
16685
16686     // Set the high part to be round to zero...
16687     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
16688       .addImm(0xC7F);
16689
16690     // Reload the modified control word now...
16691     addFrameReference(BuildMI(*BB, MI, DL,
16692                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16693
16694     // Restore the memory image of control word to original value
16695     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
16696       .addReg(OldCW);
16697
16698     // Get the X86 opcode to use.
16699     unsigned Opc;
16700     switch (MI->getOpcode()) {
16701     default: llvm_unreachable("illegal opcode!");
16702     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
16703     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
16704     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
16705     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
16706     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
16707     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
16708     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
16709     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
16710     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
16711     }
16712
16713     X86AddressMode AM;
16714     MachineOperand &Op = MI->getOperand(0);
16715     if (Op.isReg()) {
16716       AM.BaseType = X86AddressMode::RegBase;
16717       AM.Base.Reg = Op.getReg();
16718     } else {
16719       AM.BaseType = X86AddressMode::FrameIndexBase;
16720       AM.Base.FrameIndex = Op.getIndex();
16721     }
16722     Op = MI->getOperand(1);
16723     if (Op.isImm())
16724       AM.Scale = Op.getImm();
16725     Op = MI->getOperand(2);
16726     if (Op.isImm())
16727       AM.IndexReg = Op.getImm();
16728     Op = MI->getOperand(3);
16729     if (Op.isGlobal()) {
16730       AM.GV = Op.getGlobal();
16731     } else {
16732       AM.Disp = Op.getImm();
16733     }
16734     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
16735                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
16736
16737     // Reload the original control word now.
16738     addFrameReference(BuildMI(*BB, MI, DL,
16739                               TII->get(X86::FLDCW16m)), CWFrameIdx);
16740
16741     MI->eraseFromParent();   // The pseudo instruction is gone now.
16742     return BB;
16743   }
16744     // String/text processing lowering.
16745   case X86::PCMPISTRM128REG:
16746   case X86::VPCMPISTRM128REG:
16747   case X86::PCMPISTRM128MEM:
16748   case X86::VPCMPISTRM128MEM:
16749   case X86::PCMPESTRM128REG:
16750   case X86::VPCMPESTRM128REG:
16751   case X86::PCMPESTRM128MEM:
16752   case X86::VPCMPESTRM128MEM:
16753     assert(Subtarget->hasSSE42() &&
16754            "Target must have SSE4.2 or AVX features enabled");
16755     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
16756
16757   // String/text processing lowering.
16758   case X86::PCMPISTRIREG:
16759   case X86::VPCMPISTRIREG:
16760   case X86::PCMPISTRIMEM:
16761   case X86::VPCMPISTRIMEM:
16762   case X86::PCMPESTRIREG:
16763   case X86::VPCMPESTRIREG:
16764   case X86::PCMPESTRIMEM:
16765   case X86::VPCMPESTRIMEM:
16766     assert(Subtarget->hasSSE42() &&
16767            "Target must have SSE4.2 or AVX features enabled");
16768     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
16769
16770   // Thread synchronization.
16771   case X86::MONITOR:
16772     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
16773
16774   // xbegin
16775   case X86::XBEGIN:
16776     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
16777
16778   // Atomic Lowering.
16779   case X86::ATOMAND8:
16780   case X86::ATOMAND16:
16781   case X86::ATOMAND32:
16782   case X86::ATOMAND64:
16783     // Fall through
16784   case X86::ATOMOR8:
16785   case X86::ATOMOR16:
16786   case X86::ATOMOR32:
16787   case X86::ATOMOR64:
16788     // Fall through
16789   case X86::ATOMXOR16:
16790   case X86::ATOMXOR8:
16791   case X86::ATOMXOR32:
16792   case X86::ATOMXOR64:
16793     // Fall through
16794   case X86::ATOMNAND8:
16795   case X86::ATOMNAND16:
16796   case X86::ATOMNAND32:
16797   case X86::ATOMNAND64:
16798     // Fall through
16799   case X86::ATOMMAX8:
16800   case X86::ATOMMAX16:
16801   case X86::ATOMMAX32:
16802   case X86::ATOMMAX64:
16803     // Fall through
16804   case X86::ATOMMIN8:
16805   case X86::ATOMMIN16:
16806   case X86::ATOMMIN32:
16807   case X86::ATOMMIN64:
16808     // Fall through
16809   case X86::ATOMUMAX8:
16810   case X86::ATOMUMAX16:
16811   case X86::ATOMUMAX32:
16812   case X86::ATOMUMAX64:
16813     // Fall through
16814   case X86::ATOMUMIN8:
16815   case X86::ATOMUMIN16:
16816   case X86::ATOMUMIN32:
16817   case X86::ATOMUMIN64:
16818     return EmitAtomicLoadArith(MI, BB);
16819
16820   // This group does 64-bit operations on a 32-bit host.
16821   case X86::ATOMAND6432:
16822   case X86::ATOMOR6432:
16823   case X86::ATOMXOR6432:
16824   case X86::ATOMNAND6432:
16825   case X86::ATOMADD6432:
16826   case X86::ATOMSUB6432:
16827   case X86::ATOMMAX6432:
16828   case X86::ATOMMIN6432:
16829   case X86::ATOMUMAX6432:
16830   case X86::ATOMUMIN6432:
16831   case X86::ATOMSWAP6432:
16832     return EmitAtomicLoadArith6432(MI, BB);
16833
16834   case X86::VASTART_SAVE_XMM_REGS:
16835     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
16836
16837   case X86::VAARG_64:
16838     return EmitVAARG64WithCustomInserter(MI, BB);
16839
16840   case X86::EH_SjLj_SetJmp32:
16841   case X86::EH_SjLj_SetJmp64:
16842     return emitEHSjLjSetJmp(MI, BB);
16843
16844   case X86::EH_SjLj_LongJmp32:
16845   case X86::EH_SjLj_LongJmp64:
16846     return emitEHSjLjLongJmp(MI, BB);
16847
16848   case TargetOpcode::STACKMAP:
16849   case TargetOpcode::PATCHPOINT:
16850     return emitPatchPoint(MI, BB);
16851
16852   case X86::VFMADDPDr213r:
16853   case X86::VFMADDPSr213r:
16854   case X86::VFMADDSDr213r:
16855   case X86::VFMADDSSr213r:
16856   case X86::VFMSUBPDr213r:
16857   case X86::VFMSUBPSr213r:
16858   case X86::VFMSUBSDr213r:
16859   case X86::VFMSUBSSr213r:
16860   case X86::VFNMADDPDr213r:
16861   case X86::VFNMADDPSr213r:
16862   case X86::VFNMADDSDr213r:
16863   case X86::VFNMADDSSr213r:
16864   case X86::VFNMSUBPDr213r:
16865   case X86::VFNMSUBPSr213r:
16866   case X86::VFNMSUBSDr213r:
16867   case X86::VFNMSUBSSr213r:
16868   case X86::VFMADDPDr213rY:
16869   case X86::VFMADDPSr213rY:
16870   case X86::VFMSUBPDr213rY:
16871   case X86::VFMSUBPSr213rY:
16872   case X86::VFNMADDPDr213rY:
16873   case X86::VFNMADDPSr213rY:
16874   case X86::VFNMSUBPDr213rY:
16875   case X86::VFNMSUBPSr213rY:
16876     return emitFMA3Instr(MI, BB);
16877   }
16878 }
16879
16880 //===----------------------------------------------------------------------===//
16881 //                           X86 Optimization Hooks
16882 //===----------------------------------------------------------------------===//
16883
16884 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
16885                                                        APInt &KnownZero,
16886                                                        APInt &KnownOne,
16887                                                        const SelectionDAG &DAG,
16888                                                        unsigned Depth) const {
16889   unsigned BitWidth = KnownZero.getBitWidth();
16890   unsigned Opc = Op.getOpcode();
16891   assert((Opc >= ISD::BUILTIN_OP_END ||
16892           Opc == ISD::INTRINSIC_WO_CHAIN ||
16893           Opc == ISD::INTRINSIC_W_CHAIN ||
16894           Opc == ISD::INTRINSIC_VOID) &&
16895          "Should use MaskedValueIsZero if you don't know whether Op"
16896          " is a target node!");
16897
16898   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
16899   switch (Opc) {
16900   default: break;
16901   case X86ISD::ADD:
16902   case X86ISD::SUB:
16903   case X86ISD::ADC:
16904   case X86ISD::SBB:
16905   case X86ISD::SMUL:
16906   case X86ISD::UMUL:
16907   case X86ISD::INC:
16908   case X86ISD::DEC:
16909   case X86ISD::OR:
16910   case X86ISD::XOR:
16911   case X86ISD::AND:
16912     // These nodes' second result is a boolean.
16913     if (Op.getResNo() == 0)
16914       break;
16915     // Fallthrough
16916   case X86ISD::SETCC:
16917     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16918     break;
16919   case ISD::INTRINSIC_WO_CHAIN: {
16920     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16921     unsigned NumLoBits = 0;
16922     switch (IntId) {
16923     default: break;
16924     case Intrinsic::x86_sse_movmsk_ps:
16925     case Intrinsic::x86_avx_movmsk_ps_256:
16926     case Intrinsic::x86_sse2_movmsk_pd:
16927     case Intrinsic::x86_avx_movmsk_pd_256:
16928     case Intrinsic::x86_mmx_pmovmskb:
16929     case Intrinsic::x86_sse2_pmovmskb_128:
16930     case Intrinsic::x86_avx2_pmovmskb: {
16931       // High bits of movmskp{s|d}, pmovmskb are known zero.
16932       switch (IntId) {
16933         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
16934         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
16935         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
16936         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
16937         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
16938         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
16939         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
16940         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
16941       }
16942       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
16943       break;
16944     }
16945     }
16946     break;
16947   }
16948   }
16949 }
16950
16951 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
16952   SDValue Op,
16953   const SelectionDAG &,
16954   unsigned Depth) const {
16955   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
16956   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
16957     return Op.getValueType().getScalarType().getSizeInBits();
16958
16959   // Fallback case.
16960   return 1;
16961 }
16962
16963 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
16964 /// node is a GlobalAddress + offset.
16965 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
16966                                        const GlobalValue* &GA,
16967                                        int64_t &Offset) const {
16968   if (N->getOpcode() == X86ISD::Wrapper) {
16969     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
16970       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
16971       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
16972       return true;
16973     }
16974   }
16975   return TargetLowering::isGAPlusOffset(N, GA, Offset);
16976 }
16977
16978 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
16979 /// same as extracting the high 128-bit part of 256-bit vector and then
16980 /// inserting the result into the low part of a new 256-bit vector
16981 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
16982   EVT VT = SVOp->getValueType(0);
16983   unsigned NumElems = VT.getVectorNumElements();
16984
16985   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
16986   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
16987     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
16988         SVOp->getMaskElt(j) >= 0)
16989       return false;
16990
16991   return true;
16992 }
16993
16994 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
16995 /// same as extracting the low 128-bit part of 256-bit vector and then
16996 /// inserting the result into the high part of a new 256-bit vector
16997 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
16998   EVT VT = SVOp->getValueType(0);
16999   unsigned NumElems = VT.getVectorNumElements();
17000
17001   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17002   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17003     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17004         SVOp->getMaskElt(j) >= 0)
17005       return false;
17006
17007   return true;
17008 }
17009
17010 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17011 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17012                                         TargetLowering::DAGCombinerInfo &DCI,
17013                                         const X86Subtarget* Subtarget) {
17014   SDLoc dl(N);
17015   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17016   SDValue V1 = SVOp->getOperand(0);
17017   SDValue V2 = SVOp->getOperand(1);
17018   EVT VT = SVOp->getValueType(0);
17019   unsigned NumElems = VT.getVectorNumElements();
17020
17021   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17022       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17023     //
17024     //                   0,0,0,...
17025     //                      |
17026     //    V      UNDEF    BUILD_VECTOR    UNDEF
17027     //     \      /           \           /
17028     //  CONCAT_VECTOR         CONCAT_VECTOR
17029     //         \                  /
17030     //          \                /
17031     //          RESULT: V + zero extended
17032     //
17033     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17034         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17035         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17036       return SDValue();
17037
17038     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17039       return SDValue();
17040
17041     // To match the shuffle mask, the first half of the mask should
17042     // be exactly the first vector, and all the rest a splat with the
17043     // first element of the second one.
17044     for (unsigned i = 0; i != NumElems/2; ++i)
17045       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17046           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17047         return SDValue();
17048
17049     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17050     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17051       if (Ld->hasNUsesOfValue(1, 0)) {
17052         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17053         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17054         SDValue ResNode =
17055           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17056                                   Ld->getMemoryVT(),
17057                                   Ld->getPointerInfo(),
17058                                   Ld->getAlignment(),
17059                                   false/*isVolatile*/, true/*ReadMem*/,
17060                                   false/*WriteMem*/);
17061
17062         // Make sure the newly-created LOAD is in the same position as Ld in
17063         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17064         // and update uses of Ld's output chain to use the TokenFactor.
17065         if (Ld->hasAnyUseOfValue(1)) {
17066           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17067                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17068           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17069           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17070                                  SDValue(ResNode.getNode(), 1));
17071         }
17072
17073         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17074       }
17075     }
17076
17077     // Emit a zeroed vector and insert the desired subvector on its
17078     // first half.
17079     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17080     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17081     return DCI.CombineTo(N, InsV);
17082   }
17083
17084   //===--------------------------------------------------------------------===//
17085   // Combine some shuffles into subvector extracts and inserts:
17086   //
17087
17088   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17089   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17090     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17091     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17092     return DCI.CombineTo(N, InsV);
17093   }
17094
17095   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17096   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17097     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17098     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17099     return DCI.CombineTo(N, InsV);
17100   }
17101
17102   return SDValue();
17103 }
17104
17105 /// PerformShuffleCombine - Performs several different shuffle combines.
17106 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17107                                      TargetLowering::DAGCombinerInfo &DCI,
17108                                      const X86Subtarget *Subtarget) {
17109   SDLoc dl(N);
17110   EVT VT = N->getValueType(0);
17111
17112   // Don't create instructions with illegal types after legalize types has run.
17113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17114   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17115     return SDValue();
17116
17117   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17118   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17119       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17120     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17121
17122   // Only handle 128 wide vector from here on.
17123   if (!VT.is128BitVector())
17124     return SDValue();
17125
17126   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17127   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17128   // consecutive, non-overlapping, and in the right order.
17129   SmallVector<SDValue, 16> Elts;
17130   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17131     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17132
17133   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17134 }
17135
17136 /// PerformTruncateCombine - Converts truncate operation to
17137 /// a sequence of vector shuffle operations.
17138 /// It is possible when we truncate 256-bit vector to 128-bit vector
17139 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17140                                       TargetLowering::DAGCombinerInfo &DCI,
17141                                       const X86Subtarget *Subtarget)  {
17142   return SDValue();
17143 }
17144
17145 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17146 /// specific shuffle of a load can be folded into a single element load.
17147 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17148 /// shuffles have been customed lowered so we need to handle those here.
17149 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17150                                          TargetLowering::DAGCombinerInfo &DCI) {
17151   if (DCI.isBeforeLegalizeOps())
17152     return SDValue();
17153
17154   SDValue InVec = N->getOperand(0);
17155   SDValue EltNo = N->getOperand(1);
17156
17157   if (!isa<ConstantSDNode>(EltNo))
17158     return SDValue();
17159
17160   EVT VT = InVec.getValueType();
17161
17162   bool HasShuffleIntoBitcast = false;
17163   if (InVec.getOpcode() == ISD::BITCAST) {
17164     // Don't duplicate a load with other uses.
17165     if (!InVec.hasOneUse())
17166       return SDValue();
17167     EVT BCVT = InVec.getOperand(0).getValueType();
17168     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17169       return SDValue();
17170     InVec = InVec.getOperand(0);
17171     HasShuffleIntoBitcast = true;
17172   }
17173
17174   if (!isTargetShuffle(InVec.getOpcode()))
17175     return SDValue();
17176
17177   // Don't duplicate a load with other uses.
17178   if (!InVec.hasOneUse())
17179     return SDValue();
17180
17181   SmallVector<int, 16> ShuffleMask;
17182   bool UnaryShuffle;
17183   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17184                             UnaryShuffle))
17185     return SDValue();
17186
17187   // Select the input vector, guarding against out of range extract vector.
17188   unsigned NumElems = VT.getVectorNumElements();
17189   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17190   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17191   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17192                                          : InVec.getOperand(1);
17193
17194   // If inputs to shuffle are the same for both ops, then allow 2 uses
17195   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17196
17197   if (LdNode.getOpcode() == ISD::BITCAST) {
17198     // Don't duplicate a load with other uses.
17199     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17200       return SDValue();
17201
17202     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17203     LdNode = LdNode.getOperand(0);
17204   }
17205
17206   if (!ISD::isNormalLoad(LdNode.getNode()))
17207     return SDValue();
17208
17209   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17210
17211   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17212     return SDValue();
17213
17214   if (HasShuffleIntoBitcast) {
17215     // If there's a bitcast before the shuffle, check if the load type and
17216     // alignment is valid.
17217     unsigned Align = LN0->getAlignment();
17218     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17219     unsigned NewAlign = TLI.getDataLayout()->
17220       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17221
17222     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17223       return SDValue();
17224   }
17225
17226   // All checks match so transform back to vector_shuffle so that DAG combiner
17227   // can finish the job
17228   SDLoc dl(N);
17229
17230   // Create shuffle node taking into account the case that its a unary shuffle
17231   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17232   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17233                                  InVec.getOperand(0), Shuffle,
17234                                  &ShuffleMask[0]);
17235   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17236   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17237                      EltNo);
17238 }
17239
17240 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17241 /// generation and convert it from being a bunch of shuffles and extracts
17242 /// to a simple store and scalar loads to extract the elements.
17243 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17244                                          TargetLowering::DAGCombinerInfo &DCI) {
17245   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17246   if (NewOp.getNode())
17247     return NewOp;
17248
17249   SDValue InputVector = N->getOperand(0);
17250
17251   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17252   // from mmx to v2i32 has a single usage.
17253   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17254       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17255       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17256     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17257                        N->getValueType(0),
17258                        InputVector.getNode()->getOperand(0));
17259
17260   // Only operate on vectors of 4 elements, where the alternative shuffling
17261   // gets to be more expensive.
17262   if (InputVector.getValueType() != MVT::v4i32)
17263     return SDValue();
17264
17265   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17266   // single use which is a sign-extend or zero-extend, and all elements are
17267   // used.
17268   SmallVector<SDNode *, 4> Uses;
17269   unsigned ExtractedElements = 0;
17270   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17271        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17272     if (UI.getUse().getResNo() != InputVector.getResNo())
17273       return SDValue();
17274
17275     SDNode *Extract = *UI;
17276     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17277       return SDValue();
17278
17279     if (Extract->getValueType(0) != MVT::i32)
17280       return SDValue();
17281     if (!Extract->hasOneUse())
17282       return SDValue();
17283     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17284         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17285       return SDValue();
17286     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17287       return SDValue();
17288
17289     // Record which element was extracted.
17290     ExtractedElements |=
17291       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17292
17293     Uses.push_back(Extract);
17294   }
17295
17296   // If not all the elements were used, this may not be worthwhile.
17297   if (ExtractedElements != 15)
17298     return SDValue();
17299
17300   // Ok, we've now decided to do the transformation.
17301   SDLoc dl(InputVector);
17302
17303   // Store the value to a temporary stack slot.
17304   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17305   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17306                             MachinePointerInfo(), false, false, 0);
17307
17308   // Replace each use (extract) with a load of the appropriate element.
17309   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17310        UE = Uses.end(); UI != UE; ++UI) {
17311     SDNode *Extract = *UI;
17312
17313     // cOMpute the element's address.
17314     SDValue Idx = Extract->getOperand(1);
17315     unsigned EltSize =
17316         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17317     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17318     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17319     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17320
17321     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17322                                      StackPtr, OffsetVal);
17323
17324     // Load the scalar.
17325     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17326                                      ScalarAddr, MachinePointerInfo(),
17327                                      false, false, false, 0);
17328
17329     // Replace the exact with the load.
17330     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17331   }
17332
17333   // The replacement was made in place; don't return anything.
17334   return SDValue();
17335 }
17336
17337 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17338 static std::pair<unsigned, bool>
17339 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17340                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17341   if (!VT.isVector())
17342     return std::make_pair(0, false);
17343
17344   bool NeedSplit = false;
17345   switch (VT.getSimpleVT().SimpleTy) {
17346   default: return std::make_pair(0, false);
17347   case MVT::v32i8:
17348   case MVT::v16i16:
17349   case MVT::v8i32:
17350     if (!Subtarget->hasAVX2())
17351       NeedSplit = true;
17352     if (!Subtarget->hasAVX())
17353       return std::make_pair(0, false);
17354     break;
17355   case MVT::v16i8:
17356   case MVT::v8i16:
17357   case MVT::v4i32:
17358     if (!Subtarget->hasSSE2())
17359       return std::make_pair(0, false);
17360   }
17361
17362   // SSE2 has only a small subset of the operations.
17363   bool hasUnsigned = Subtarget->hasSSE41() ||
17364                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17365   bool hasSigned = Subtarget->hasSSE41() ||
17366                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17367
17368   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17369
17370   unsigned Opc = 0;
17371   // Check for x CC y ? x : y.
17372   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17373       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17374     switch (CC) {
17375     default: break;
17376     case ISD::SETULT:
17377     case ISD::SETULE:
17378       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17379     case ISD::SETUGT:
17380     case ISD::SETUGE:
17381       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17382     case ISD::SETLT:
17383     case ISD::SETLE:
17384       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17385     case ISD::SETGT:
17386     case ISD::SETGE:
17387       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17388     }
17389   // Check for x CC y ? y : x -- a min/max with reversed arms.
17390   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17391              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17392     switch (CC) {
17393     default: break;
17394     case ISD::SETULT:
17395     case ISD::SETULE:
17396       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17397     case ISD::SETUGT:
17398     case ISD::SETUGE:
17399       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17400     case ISD::SETLT:
17401     case ISD::SETLE:
17402       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17403     case ISD::SETGT:
17404     case ISD::SETGE:
17405       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17406     }
17407   }
17408
17409   return std::make_pair(Opc, NeedSplit);
17410 }
17411
17412 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17413 /// nodes.
17414 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17415                                     TargetLowering::DAGCombinerInfo &DCI,
17416                                     const X86Subtarget *Subtarget) {
17417   SDLoc DL(N);
17418   SDValue Cond = N->getOperand(0);
17419   // Get the LHS/RHS of the select.
17420   SDValue LHS = N->getOperand(1);
17421   SDValue RHS = N->getOperand(2);
17422   EVT VT = LHS.getValueType();
17423   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17424
17425   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17426   // instructions match the semantics of the common C idiom x<y?x:y but not
17427   // x<=y?x:y, because of how they handle negative zero (which can be
17428   // ignored in unsafe-math mode).
17429   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17430       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17431       (Subtarget->hasSSE2() ||
17432        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17433     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17434
17435     unsigned Opcode = 0;
17436     // Check for x CC y ? x : y.
17437     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17438         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17439       switch (CC) {
17440       default: break;
17441       case ISD::SETULT:
17442         // Converting this to a min would handle NaNs incorrectly, and swapping
17443         // the operands would cause it to handle comparisons between positive
17444         // and negative zero incorrectly.
17445         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17446           if (!DAG.getTarget().Options.UnsafeFPMath &&
17447               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17448             break;
17449           std::swap(LHS, RHS);
17450         }
17451         Opcode = X86ISD::FMIN;
17452         break;
17453       case ISD::SETOLE:
17454         // Converting this to a min would handle comparisons between positive
17455         // and negative zero incorrectly.
17456         if (!DAG.getTarget().Options.UnsafeFPMath &&
17457             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17458           break;
17459         Opcode = X86ISD::FMIN;
17460         break;
17461       case ISD::SETULE:
17462         // Converting this to a min would handle both negative zeros and NaNs
17463         // incorrectly, but we can swap the operands to fix both.
17464         std::swap(LHS, RHS);
17465       case ISD::SETOLT:
17466       case ISD::SETLT:
17467       case ISD::SETLE:
17468         Opcode = X86ISD::FMIN;
17469         break;
17470
17471       case ISD::SETOGE:
17472         // Converting this to a max would handle comparisons between positive
17473         // and negative zero incorrectly.
17474         if (!DAG.getTarget().Options.UnsafeFPMath &&
17475             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17476           break;
17477         Opcode = X86ISD::FMAX;
17478         break;
17479       case ISD::SETUGT:
17480         // Converting this to a max would handle NaNs incorrectly, and swapping
17481         // the operands would cause it to handle comparisons between positive
17482         // and negative zero incorrectly.
17483         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17484           if (!DAG.getTarget().Options.UnsafeFPMath &&
17485               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17486             break;
17487           std::swap(LHS, RHS);
17488         }
17489         Opcode = X86ISD::FMAX;
17490         break;
17491       case ISD::SETUGE:
17492         // Converting this to a max would handle both negative zeros and NaNs
17493         // incorrectly, but we can swap the operands to fix both.
17494         std::swap(LHS, RHS);
17495       case ISD::SETOGT:
17496       case ISD::SETGT:
17497       case ISD::SETGE:
17498         Opcode = X86ISD::FMAX;
17499         break;
17500       }
17501     // Check for x CC y ? y : x -- a min/max with reversed arms.
17502     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17503                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17504       switch (CC) {
17505       default: break;
17506       case ISD::SETOGE:
17507         // Converting this to a min would handle comparisons between positive
17508         // and negative zero incorrectly, and swapping the operands would
17509         // cause it to handle NaNs incorrectly.
17510         if (!DAG.getTarget().Options.UnsafeFPMath &&
17511             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17512           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17513             break;
17514           std::swap(LHS, RHS);
17515         }
17516         Opcode = X86ISD::FMIN;
17517         break;
17518       case ISD::SETUGT:
17519         // Converting this to a min would handle NaNs incorrectly.
17520         if (!DAG.getTarget().Options.UnsafeFPMath &&
17521             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
17522           break;
17523         Opcode = X86ISD::FMIN;
17524         break;
17525       case ISD::SETUGE:
17526         // Converting this to a min would handle both negative zeros and NaNs
17527         // incorrectly, but we can swap the operands to fix both.
17528         std::swap(LHS, RHS);
17529       case ISD::SETOGT:
17530       case ISD::SETGT:
17531       case ISD::SETGE:
17532         Opcode = X86ISD::FMIN;
17533         break;
17534
17535       case ISD::SETULT:
17536         // Converting this to a max would handle NaNs incorrectly.
17537         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17538           break;
17539         Opcode = X86ISD::FMAX;
17540         break;
17541       case ISD::SETOLE:
17542         // Converting this to a max would handle comparisons between positive
17543         // and negative zero incorrectly, and swapping the operands would
17544         // cause it to handle NaNs incorrectly.
17545         if (!DAG.getTarget().Options.UnsafeFPMath &&
17546             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
17547           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17548             break;
17549           std::swap(LHS, RHS);
17550         }
17551         Opcode = X86ISD::FMAX;
17552         break;
17553       case ISD::SETULE:
17554         // Converting this to a max would handle both negative zeros and NaNs
17555         // incorrectly, but we can swap the operands to fix both.
17556         std::swap(LHS, RHS);
17557       case ISD::SETOLT:
17558       case ISD::SETLT:
17559       case ISD::SETLE:
17560         Opcode = X86ISD::FMAX;
17561         break;
17562       }
17563     }
17564
17565     if (Opcode)
17566       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
17567   }
17568
17569   EVT CondVT = Cond.getValueType();
17570   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
17571       CondVT.getVectorElementType() == MVT::i1) {
17572     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
17573     // lowering on AVX-512. In this case we convert it to
17574     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
17575     // The same situation for all 128 and 256-bit vectors of i8 and i16
17576     EVT OpVT = LHS.getValueType();
17577     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
17578         (OpVT.getVectorElementType() == MVT::i8 ||
17579          OpVT.getVectorElementType() == MVT::i16)) {
17580       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
17581       DCI.AddToWorklist(Cond.getNode());
17582       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
17583     }
17584   }
17585   // If this is a select between two integer constants, try to do some
17586   // optimizations.
17587   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
17588     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
17589       // Don't do this for crazy integer types.
17590       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
17591         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
17592         // so that TrueC (the true value) is larger than FalseC.
17593         bool NeedsCondInvert = false;
17594
17595         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
17596             // Efficiently invertible.
17597             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
17598              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
17599               isa<ConstantSDNode>(Cond.getOperand(1))))) {
17600           NeedsCondInvert = true;
17601           std::swap(TrueC, FalseC);
17602         }
17603
17604         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
17605         if (FalseC->getAPIntValue() == 0 &&
17606             TrueC->getAPIntValue().isPowerOf2()) {
17607           if (NeedsCondInvert) // Invert the condition if needed.
17608             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17609                                DAG.getConstant(1, Cond.getValueType()));
17610
17611           // Zero extend the condition if needed.
17612           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
17613
17614           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
17615           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
17616                              DAG.getConstant(ShAmt, MVT::i8));
17617         }
17618
17619         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
17620         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
17621           if (NeedsCondInvert) // Invert the condition if needed.
17622             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17623                                DAG.getConstant(1, Cond.getValueType()));
17624
17625           // Zero extend the condition if needed.
17626           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
17627                              FalseC->getValueType(0), Cond);
17628           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17629                              SDValue(FalseC, 0));
17630         }
17631
17632         // Optimize cases that will turn into an LEA instruction.  This requires
17633         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
17634         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
17635           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
17636           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
17637
17638           bool isFastMultiplier = false;
17639           if (Diff < 10) {
17640             switch ((unsigned char)Diff) {
17641               default: break;
17642               case 1:  // result = add base, cond
17643               case 2:  // result = lea base(    , cond*2)
17644               case 3:  // result = lea base(cond, cond*2)
17645               case 4:  // result = lea base(    , cond*4)
17646               case 5:  // result = lea base(cond, cond*4)
17647               case 8:  // result = lea base(    , cond*8)
17648               case 9:  // result = lea base(cond, cond*8)
17649                 isFastMultiplier = true;
17650                 break;
17651             }
17652           }
17653
17654           if (isFastMultiplier) {
17655             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
17656             if (NeedsCondInvert) // Invert the condition if needed.
17657               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
17658                                  DAG.getConstant(1, Cond.getValueType()));
17659
17660             // Zero extend the condition if needed.
17661             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
17662                                Cond);
17663             // Scale the condition by the difference.
17664             if (Diff != 1)
17665               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
17666                                  DAG.getConstant(Diff, Cond.getValueType()));
17667
17668             // Add the base if non-zero.
17669             if (FalseC->getAPIntValue() != 0)
17670               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
17671                                  SDValue(FalseC, 0));
17672             return Cond;
17673           }
17674         }
17675       }
17676   }
17677
17678   // Canonicalize max and min:
17679   // (x > y) ? x : y -> (x >= y) ? x : y
17680   // (x < y) ? x : y -> (x <= y) ? x : y
17681   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
17682   // the need for an extra compare
17683   // against zero. e.g.
17684   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
17685   // subl   %esi, %edi
17686   // testl  %edi, %edi
17687   // movl   $0, %eax
17688   // cmovgl %edi, %eax
17689   // =>
17690   // xorl   %eax, %eax
17691   // subl   %esi, $edi
17692   // cmovsl %eax, %edi
17693   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
17694       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17695       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17696     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17697     switch (CC) {
17698     default: break;
17699     case ISD::SETLT:
17700     case ISD::SETGT: {
17701       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
17702       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
17703                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
17704       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
17705     }
17706     }
17707   }
17708
17709   // Early exit check
17710   if (!TLI.isTypeLegal(VT))
17711     return SDValue();
17712
17713   // Match VSELECTs into subs with unsigned saturation.
17714   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17715       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
17716       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
17717        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
17718     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17719
17720     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
17721     // left side invert the predicate to simplify logic below.
17722     SDValue Other;
17723     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
17724       Other = RHS;
17725       CC = ISD::getSetCCInverse(CC, true);
17726     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
17727       Other = LHS;
17728     }
17729
17730     if (Other.getNode() && Other->getNumOperands() == 2 &&
17731         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
17732       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
17733       SDValue CondRHS = Cond->getOperand(1);
17734
17735       // Look for a general sub with unsigned saturation first.
17736       // x >= y ? x-y : 0 --> subus x, y
17737       // x >  y ? x-y : 0 --> subus x, y
17738       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
17739           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
17740         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17741
17742       // If the RHS is a constant we have to reverse the const canonicalization.
17743       // x > C-1 ? x+-C : 0 --> subus x, C
17744       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
17745           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
17746         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17747         if (CondRHS.getConstantOperandVal(0) == -A-1)
17748           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
17749                              DAG.getConstant(-A, VT));
17750       }
17751
17752       // Another special case: If C was a sign bit, the sub has been
17753       // canonicalized into a xor.
17754       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
17755       //        it's safe to decanonicalize the xor?
17756       // x s< 0 ? x^C : 0 --> subus x, C
17757       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
17758           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
17759           isSplatVector(OpRHS.getNode())) {
17760         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
17761         if (A.isSignBit())
17762           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
17763       }
17764     }
17765   }
17766
17767   // Try to match a min/max vector operation.
17768   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
17769     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
17770     unsigned Opc = ret.first;
17771     bool NeedSplit = ret.second;
17772
17773     if (Opc && NeedSplit) {
17774       unsigned NumElems = VT.getVectorNumElements();
17775       // Extract the LHS vectors
17776       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
17777       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
17778
17779       // Extract the RHS vectors
17780       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
17781       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
17782
17783       // Create min/max for each subvector
17784       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
17785       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
17786
17787       // Merge the result
17788       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
17789     } else if (Opc)
17790       return DAG.getNode(Opc, DL, VT, LHS, RHS);
17791   }
17792
17793   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
17794   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
17795       // Check if SETCC has already been promoted
17796       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
17797       // Check that condition value type matches vselect operand type
17798       CondVT == VT) { 
17799
17800     assert(Cond.getValueType().isVector() &&
17801            "vector select expects a vector selector!");
17802
17803     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
17804     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
17805
17806     if (!TValIsAllOnes && !FValIsAllZeros) {
17807       // Try invert the condition if true value is not all 1s and false value
17808       // is not all 0s.
17809       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
17810       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
17811
17812       if (TValIsAllZeros || FValIsAllOnes) {
17813         SDValue CC = Cond.getOperand(2);
17814         ISD::CondCode NewCC =
17815           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
17816                                Cond.getOperand(0).getValueType().isInteger());
17817         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
17818         std::swap(LHS, RHS);
17819         TValIsAllOnes = FValIsAllOnes;
17820         FValIsAllZeros = TValIsAllZeros;
17821       }
17822     }
17823
17824     if (TValIsAllOnes || FValIsAllZeros) {
17825       SDValue Ret;
17826
17827       if (TValIsAllOnes && FValIsAllZeros)
17828         Ret = Cond;
17829       else if (TValIsAllOnes)
17830         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
17831                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
17832       else if (FValIsAllZeros)
17833         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
17834                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
17835
17836       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
17837     }
17838   }
17839
17840   // Try to fold this VSELECT into a MOVSS/MOVSD
17841   if (N->getOpcode() == ISD::VSELECT &&
17842       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
17843     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
17844         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
17845       bool CanFold = false;
17846       unsigned NumElems = Cond.getNumOperands();
17847       SDValue A = LHS;
17848       SDValue B = RHS;
17849       
17850       if (isZero(Cond.getOperand(0))) {
17851         CanFold = true;
17852
17853         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
17854         // fold (vselect <0,-1> -> (movsd A, B)
17855         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17856           CanFold = isAllOnes(Cond.getOperand(i));
17857       } else if (isAllOnes(Cond.getOperand(0))) {
17858         CanFold = true;
17859         std::swap(A, B);
17860
17861         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
17862         // fold (vselect <-1,0> -> (movsd B, A)
17863         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
17864           CanFold = isZero(Cond.getOperand(i));
17865       }
17866
17867       if (CanFold) {
17868         if (VT == MVT::v4i32 || VT == MVT::v4f32)
17869           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
17870         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
17871       }
17872
17873       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
17874         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
17875         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
17876         //                             (v2i64 (bitcast B)))))
17877         //
17878         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
17879         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
17880         //                             (v2f64 (bitcast B)))))
17881         //
17882         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
17883         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
17884         //                             (v2i64 (bitcast A)))))
17885         //
17886         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
17887         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
17888         //                             (v2f64 (bitcast A)))))
17889
17890         CanFold = (isZero(Cond.getOperand(0)) &&
17891                    isZero(Cond.getOperand(1)) &&
17892                    isAllOnes(Cond.getOperand(2)) &&
17893                    isAllOnes(Cond.getOperand(3)));
17894
17895         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
17896             isAllOnes(Cond.getOperand(1)) &&
17897             isZero(Cond.getOperand(2)) &&
17898             isZero(Cond.getOperand(3))) {
17899           CanFold = true;
17900           std::swap(LHS, RHS);
17901         }
17902
17903         if (CanFold) {
17904           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
17905           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
17906           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
17907           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
17908                                                 NewB, DAG);
17909           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
17910         }
17911       }
17912     }
17913   }
17914
17915   // If we know that this node is legal then we know that it is going to be
17916   // matched by one of the SSE/AVX BLEND instructions. These instructions only
17917   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
17918   // to simplify previous instructions.
17919   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
17920       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
17921     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
17922
17923     // Don't optimize vector selects that map to mask-registers.
17924     if (BitWidth == 1)
17925       return SDValue();
17926
17927     // Check all uses of that condition operand to check whether it will be
17928     // consumed by non-BLEND instructions, which may depend on all bits are set
17929     // properly.
17930     for (SDNode::use_iterator I = Cond->use_begin(),
17931                               E = Cond->use_end(); I != E; ++I)
17932       if (I->getOpcode() != ISD::VSELECT)
17933         // TODO: Add other opcodes eventually lowered into BLEND.
17934         return SDValue();
17935
17936     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
17937     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
17938
17939     APInt KnownZero, KnownOne;
17940     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
17941                                           DCI.isBeforeLegalizeOps());
17942     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
17943         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
17944       DCI.CommitTargetLoweringOpt(TLO);
17945   }
17946
17947   return SDValue();
17948 }
17949
17950 // Check whether a boolean test is testing a boolean value generated by
17951 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
17952 // code.
17953 //
17954 // Simplify the following patterns:
17955 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
17956 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
17957 // to (Op EFLAGS Cond)
17958 //
17959 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
17960 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
17961 // to (Op EFLAGS !Cond)
17962 //
17963 // where Op could be BRCOND or CMOV.
17964 //
17965 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
17966   // Quit if not CMP and SUB with its value result used.
17967   if (Cmp.getOpcode() != X86ISD::CMP &&
17968       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
17969       return SDValue();
17970
17971   // Quit if not used as a boolean value.
17972   if (CC != X86::COND_E && CC != X86::COND_NE)
17973     return SDValue();
17974
17975   // Check CMP operands. One of them should be 0 or 1 and the other should be
17976   // an SetCC or extended from it.
17977   SDValue Op1 = Cmp.getOperand(0);
17978   SDValue Op2 = Cmp.getOperand(1);
17979
17980   SDValue SetCC;
17981   const ConstantSDNode* C = nullptr;
17982   bool needOppositeCond = (CC == X86::COND_E);
17983   bool checkAgainstTrue = false; // Is it a comparison against 1?
17984
17985   if ((C = dyn_cast<ConstantSDNode>(Op1)))
17986     SetCC = Op2;
17987   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
17988     SetCC = Op1;
17989   else // Quit if all operands are not constants.
17990     return SDValue();
17991
17992   if (C->getZExtValue() == 1) {
17993     needOppositeCond = !needOppositeCond;
17994     checkAgainstTrue = true;
17995   } else if (C->getZExtValue() != 0)
17996     // Quit if the constant is neither 0 or 1.
17997     return SDValue();
17998
17999   bool truncatedToBoolWithAnd = false;
18000   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18001   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18002          SetCC.getOpcode() == ISD::TRUNCATE ||
18003          SetCC.getOpcode() == ISD::AND) {
18004     if (SetCC.getOpcode() == ISD::AND) {
18005       int OpIdx = -1;
18006       ConstantSDNode *CS;
18007       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18008           CS->getZExtValue() == 1)
18009         OpIdx = 1;
18010       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18011           CS->getZExtValue() == 1)
18012         OpIdx = 0;
18013       if (OpIdx == -1)
18014         break;
18015       SetCC = SetCC.getOperand(OpIdx);
18016       truncatedToBoolWithAnd = true;
18017     } else
18018       SetCC = SetCC.getOperand(0);
18019   }
18020
18021   switch (SetCC.getOpcode()) {
18022   case X86ISD::SETCC_CARRY:
18023     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18024     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18025     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18026     // truncated to i1 using 'and'.
18027     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18028       break;
18029     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18030            "Invalid use of SETCC_CARRY!");
18031     // FALL THROUGH
18032   case X86ISD::SETCC:
18033     // Set the condition code or opposite one if necessary.
18034     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18035     if (needOppositeCond)
18036       CC = X86::GetOppositeBranchCondition(CC);
18037     return SetCC.getOperand(1);
18038   case X86ISD::CMOV: {
18039     // Check whether false/true value has canonical one, i.e. 0 or 1.
18040     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18041     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18042     // Quit if true value is not a constant.
18043     if (!TVal)
18044       return SDValue();
18045     // Quit if false value is not a constant.
18046     if (!FVal) {
18047       SDValue Op = SetCC.getOperand(0);
18048       // Skip 'zext' or 'trunc' node.
18049       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18050           Op.getOpcode() == ISD::TRUNCATE)
18051         Op = Op.getOperand(0);
18052       // A special case for rdrand/rdseed, where 0 is set if false cond is
18053       // found.
18054       if ((Op.getOpcode() != X86ISD::RDRAND &&
18055            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18056         return SDValue();
18057     }
18058     // Quit if false value is not the constant 0 or 1.
18059     bool FValIsFalse = true;
18060     if (FVal && FVal->getZExtValue() != 0) {
18061       if (FVal->getZExtValue() != 1)
18062         return SDValue();
18063       // If FVal is 1, opposite cond is needed.
18064       needOppositeCond = !needOppositeCond;
18065       FValIsFalse = false;
18066     }
18067     // Quit if TVal is not the constant opposite of FVal.
18068     if (FValIsFalse && TVal->getZExtValue() != 1)
18069       return SDValue();
18070     if (!FValIsFalse && TVal->getZExtValue() != 0)
18071       return SDValue();
18072     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18073     if (needOppositeCond)
18074       CC = X86::GetOppositeBranchCondition(CC);
18075     return SetCC.getOperand(3);
18076   }
18077   }
18078
18079   return SDValue();
18080 }
18081
18082 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18083 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18084                                   TargetLowering::DAGCombinerInfo &DCI,
18085                                   const X86Subtarget *Subtarget) {
18086   SDLoc DL(N);
18087
18088   // If the flag operand isn't dead, don't touch this CMOV.
18089   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18090     return SDValue();
18091
18092   SDValue FalseOp = N->getOperand(0);
18093   SDValue TrueOp = N->getOperand(1);
18094   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18095   SDValue Cond = N->getOperand(3);
18096
18097   if (CC == X86::COND_E || CC == X86::COND_NE) {
18098     switch (Cond.getOpcode()) {
18099     default: break;
18100     case X86ISD::BSR:
18101     case X86ISD::BSF:
18102       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18103       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18104         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18105     }
18106   }
18107
18108   SDValue Flags;
18109
18110   Flags = checkBoolTestSetCCCombine(Cond, CC);
18111   if (Flags.getNode() &&
18112       // Extra check as FCMOV only supports a subset of X86 cond.
18113       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18114     SDValue Ops[] = { FalseOp, TrueOp,
18115                       DAG.getConstant(CC, MVT::i8), Flags };
18116     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18117   }
18118
18119   // If this is a select between two integer constants, try to do some
18120   // optimizations.  Note that the operands are ordered the opposite of SELECT
18121   // operands.
18122   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18123     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18124       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18125       // larger than FalseC (the false value).
18126       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18127         CC = X86::GetOppositeBranchCondition(CC);
18128         std::swap(TrueC, FalseC);
18129         std::swap(TrueOp, FalseOp);
18130       }
18131
18132       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18133       // This is efficient for any integer data type (including i8/i16) and
18134       // shift amount.
18135       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18136         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18137                            DAG.getConstant(CC, MVT::i8), Cond);
18138
18139         // Zero extend the condition if needed.
18140         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18141
18142         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18143         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18144                            DAG.getConstant(ShAmt, MVT::i8));
18145         if (N->getNumValues() == 2)  // Dead flag value?
18146           return DCI.CombineTo(N, Cond, SDValue());
18147         return Cond;
18148       }
18149
18150       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18151       // for any integer data type, including i8/i16.
18152       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18153         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18154                            DAG.getConstant(CC, MVT::i8), Cond);
18155
18156         // Zero extend the condition if needed.
18157         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18158                            FalseC->getValueType(0), Cond);
18159         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18160                            SDValue(FalseC, 0));
18161
18162         if (N->getNumValues() == 2)  // Dead flag value?
18163           return DCI.CombineTo(N, Cond, SDValue());
18164         return Cond;
18165       }
18166
18167       // Optimize cases that will turn into an LEA instruction.  This requires
18168       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18169       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18170         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18171         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18172
18173         bool isFastMultiplier = false;
18174         if (Diff < 10) {
18175           switch ((unsigned char)Diff) {
18176           default: break;
18177           case 1:  // result = add base, cond
18178           case 2:  // result = lea base(    , cond*2)
18179           case 3:  // result = lea base(cond, cond*2)
18180           case 4:  // result = lea base(    , cond*4)
18181           case 5:  // result = lea base(cond, cond*4)
18182           case 8:  // result = lea base(    , cond*8)
18183           case 9:  // result = lea base(cond, cond*8)
18184             isFastMultiplier = true;
18185             break;
18186           }
18187         }
18188
18189         if (isFastMultiplier) {
18190           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18191           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18192                              DAG.getConstant(CC, MVT::i8), Cond);
18193           // Zero extend the condition if needed.
18194           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18195                              Cond);
18196           // Scale the condition by the difference.
18197           if (Diff != 1)
18198             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18199                                DAG.getConstant(Diff, Cond.getValueType()));
18200
18201           // Add the base if non-zero.
18202           if (FalseC->getAPIntValue() != 0)
18203             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18204                                SDValue(FalseC, 0));
18205           if (N->getNumValues() == 2)  // Dead flag value?
18206             return DCI.CombineTo(N, Cond, SDValue());
18207           return Cond;
18208         }
18209       }
18210     }
18211   }
18212
18213   // Handle these cases:
18214   //   (select (x != c), e, c) -> select (x != c), e, x),
18215   //   (select (x == c), c, e) -> select (x == c), x, e)
18216   // where the c is an integer constant, and the "select" is the combination
18217   // of CMOV and CMP.
18218   //
18219   // The rationale for this change is that the conditional-move from a constant
18220   // needs two instructions, however, conditional-move from a register needs
18221   // only one instruction.
18222   //
18223   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18224   //  some instruction-combining opportunities. This opt needs to be
18225   //  postponed as late as possible.
18226   //
18227   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18228     // the DCI.xxxx conditions are provided to postpone the optimization as
18229     // late as possible.
18230
18231     ConstantSDNode *CmpAgainst = nullptr;
18232     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18233         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18234         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18235
18236       if (CC == X86::COND_NE &&
18237           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18238         CC = X86::GetOppositeBranchCondition(CC);
18239         std::swap(TrueOp, FalseOp);
18240       }
18241
18242       if (CC == X86::COND_E &&
18243           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18244         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18245                           DAG.getConstant(CC, MVT::i8), Cond };
18246         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18247       }
18248     }
18249   }
18250
18251   return SDValue();
18252 }
18253
18254 /// PerformMulCombine - Optimize a single multiply with constant into two
18255 /// in order to implement it with two cheaper instructions, e.g.
18256 /// LEA + SHL, LEA + LEA.
18257 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18258                                  TargetLowering::DAGCombinerInfo &DCI) {
18259   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18260     return SDValue();
18261
18262   EVT VT = N->getValueType(0);
18263   if (VT != MVT::i64)
18264     return SDValue();
18265
18266   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18267   if (!C)
18268     return SDValue();
18269   uint64_t MulAmt = C->getZExtValue();
18270   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18271     return SDValue();
18272
18273   uint64_t MulAmt1 = 0;
18274   uint64_t MulAmt2 = 0;
18275   if ((MulAmt % 9) == 0) {
18276     MulAmt1 = 9;
18277     MulAmt2 = MulAmt / 9;
18278   } else if ((MulAmt % 5) == 0) {
18279     MulAmt1 = 5;
18280     MulAmt2 = MulAmt / 5;
18281   } else if ((MulAmt % 3) == 0) {
18282     MulAmt1 = 3;
18283     MulAmt2 = MulAmt / 3;
18284   }
18285   if (MulAmt2 &&
18286       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18287     SDLoc DL(N);
18288
18289     if (isPowerOf2_64(MulAmt2) &&
18290         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18291       // If second multiplifer is pow2, issue it first. We want the multiply by
18292       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18293       // is an add.
18294       std::swap(MulAmt1, MulAmt2);
18295
18296     SDValue NewMul;
18297     if (isPowerOf2_64(MulAmt1))
18298       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18299                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18300     else
18301       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18302                            DAG.getConstant(MulAmt1, VT));
18303
18304     if (isPowerOf2_64(MulAmt2))
18305       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18306                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18307     else
18308       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18309                            DAG.getConstant(MulAmt2, VT));
18310
18311     // Do not add new nodes to DAG combiner worklist.
18312     DCI.CombineTo(N, NewMul, false);
18313   }
18314   return SDValue();
18315 }
18316
18317 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18318   SDValue N0 = N->getOperand(0);
18319   SDValue N1 = N->getOperand(1);
18320   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18321   EVT VT = N0.getValueType();
18322
18323   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18324   // since the result of setcc_c is all zero's or all ones.
18325   if (VT.isInteger() && !VT.isVector() &&
18326       N1C && N0.getOpcode() == ISD::AND &&
18327       N0.getOperand(1).getOpcode() == ISD::Constant) {
18328     SDValue N00 = N0.getOperand(0);
18329     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18330         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18331           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18332          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18333       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18334       APInt ShAmt = N1C->getAPIntValue();
18335       Mask = Mask.shl(ShAmt);
18336       if (Mask != 0)
18337         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18338                            N00, DAG.getConstant(Mask, VT));
18339     }
18340   }
18341
18342   // Hardware support for vector shifts is sparse which makes us scalarize the
18343   // vector operations in many cases. Also, on sandybridge ADD is faster than
18344   // shl.
18345   // (shl V, 1) -> add V,V
18346   if (isSplatVector(N1.getNode())) {
18347     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18348     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18349     // We shift all of the values by one. In many cases we do not have
18350     // hardware support for this operation. This is better expressed as an ADD
18351     // of two values.
18352     if (N1C && (1 == N1C->getZExtValue())) {
18353       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18354     }
18355   }
18356
18357   return SDValue();
18358 }
18359
18360 /// \brief Returns a vector of 0s if the node in input is a vector logical
18361 /// shift by a constant amount which is known to be bigger than or equal
18362 /// to the vector element size in bits.
18363 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18364                                       const X86Subtarget *Subtarget) {
18365   EVT VT = N->getValueType(0);
18366
18367   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18368       (!Subtarget->hasInt256() ||
18369        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18370     return SDValue();
18371
18372   SDValue Amt = N->getOperand(1);
18373   SDLoc DL(N);
18374   if (isSplatVector(Amt.getNode())) {
18375     SDValue SclrAmt = Amt->getOperand(0);
18376     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18377       APInt ShiftAmt = C->getAPIntValue();
18378       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18379
18380       // SSE2/AVX2 logical shifts always return a vector of 0s
18381       // if the shift amount is bigger than or equal to
18382       // the element size. The constant shift amount will be
18383       // encoded as a 8-bit immediate.
18384       if (ShiftAmt.trunc(8).uge(MaxAmount))
18385         return getZeroVector(VT, Subtarget, DAG, DL);
18386     }
18387   }
18388
18389   return SDValue();
18390 }
18391
18392 /// PerformShiftCombine - Combine shifts.
18393 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
18394                                    TargetLowering::DAGCombinerInfo &DCI,
18395                                    const X86Subtarget *Subtarget) {
18396   if (N->getOpcode() == ISD::SHL) {
18397     SDValue V = PerformSHLCombine(N, DAG);
18398     if (V.getNode()) return V;
18399   }
18400
18401   if (N->getOpcode() != ISD::SRA) {
18402     // Try to fold this logical shift into a zero vector.
18403     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
18404     if (V.getNode()) return V;
18405   }
18406
18407   return SDValue();
18408 }
18409
18410 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
18411 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
18412 // and friends.  Likewise for OR -> CMPNEQSS.
18413 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
18414                             TargetLowering::DAGCombinerInfo &DCI,
18415                             const X86Subtarget *Subtarget) {
18416   unsigned opcode;
18417
18418   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
18419   // we're requiring SSE2 for both.
18420   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
18421     SDValue N0 = N->getOperand(0);
18422     SDValue N1 = N->getOperand(1);
18423     SDValue CMP0 = N0->getOperand(1);
18424     SDValue CMP1 = N1->getOperand(1);
18425     SDLoc DL(N);
18426
18427     // The SETCCs should both refer to the same CMP.
18428     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
18429       return SDValue();
18430
18431     SDValue CMP00 = CMP0->getOperand(0);
18432     SDValue CMP01 = CMP0->getOperand(1);
18433     EVT     VT    = CMP00.getValueType();
18434
18435     if (VT == MVT::f32 || VT == MVT::f64) {
18436       bool ExpectingFlags = false;
18437       // Check for any users that want flags:
18438       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
18439            !ExpectingFlags && UI != UE; ++UI)
18440         switch (UI->getOpcode()) {
18441         default:
18442         case ISD::BR_CC:
18443         case ISD::BRCOND:
18444         case ISD::SELECT:
18445           ExpectingFlags = true;
18446           break;
18447         case ISD::CopyToReg:
18448         case ISD::SIGN_EXTEND:
18449         case ISD::ZERO_EXTEND:
18450         case ISD::ANY_EXTEND:
18451           break;
18452         }
18453
18454       if (!ExpectingFlags) {
18455         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
18456         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
18457
18458         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
18459           X86::CondCode tmp = cc0;
18460           cc0 = cc1;
18461           cc1 = tmp;
18462         }
18463
18464         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
18465             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
18466           // FIXME: need symbolic constants for these magic numbers.
18467           // See X86ATTInstPrinter.cpp:printSSECC().
18468           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
18469           if (Subtarget->hasAVX512()) {
18470             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
18471                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
18472             if (N->getValueType(0) != MVT::i1)
18473               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
18474                                  FSetCC);
18475             return FSetCC;
18476           }
18477           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
18478                                               CMP00.getValueType(), CMP00, CMP01,
18479                                               DAG.getConstant(x86cc, MVT::i8));
18480
18481           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
18482           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
18483
18484           if (is64BitFP && !Subtarget->is64Bit()) {
18485             // On a 32-bit target, we cannot bitcast the 64-bit float to a
18486             // 64-bit integer, since that's not a legal type. Since
18487             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
18488             // bits, but can do this little dance to extract the lowest 32 bits
18489             // and work with those going forward.
18490             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
18491                                            OnesOrZeroesF);
18492             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
18493                                            Vector64);
18494             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
18495                                         Vector32, DAG.getIntPtrConstant(0));
18496             IntVT = MVT::i32;
18497           }
18498
18499           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
18500           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
18501                                       DAG.getConstant(1, IntVT));
18502           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
18503           return OneBitOfTruth;
18504         }
18505       }
18506     }
18507   }
18508   return SDValue();
18509 }
18510
18511 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
18512 /// so it can be folded inside ANDNP.
18513 static bool CanFoldXORWithAllOnes(const SDNode *N) {
18514   EVT VT = N->getValueType(0);
18515
18516   // Match direct AllOnes for 128 and 256-bit vectors
18517   if (ISD::isBuildVectorAllOnes(N))
18518     return true;
18519
18520   // Look through a bit convert.
18521   if (N->getOpcode() == ISD::BITCAST)
18522     N = N->getOperand(0).getNode();
18523
18524   // Sometimes the operand may come from a insert_subvector building a 256-bit
18525   // allones vector
18526   if (VT.is256BitVector() &&
18527       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
18528     SDValue V1 = N->getOperand(0);
18529     SDValue V2 = N->getOperand(1);
18530
18531     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
18532         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
18533         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
18534         ISD::isBuildVectorAllOnes(V2.getNode()))
18535       return true;
18536   }
18537
18538   return false;
18539 }
18540
18541 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
18542 // register. In most cases we actually compare or select YMM-sized registers
18543 // and mixing the two types creates horrible code. This method optimizes
18544 // some of the transition sequences.
18545 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
18546                                  TargetLowering::DAGCombinerInfo &DCI,
18547                                  const X86Subtarget *Subtarget) {
18548   EVT VT = N->getValueType(0);
18549   if (!VT.is256BitVector())
18550     return SDValue();
18551
18552   assert((N->getOpcode() == ISD::ANY_EXTEND ||
18553           N->getOpcode() == ISD::ZERO_EXTEND ||
18554           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
18555
18556   SDValue Narrow = N->getOperand(0);
18557   EVT NarrowVT = Narrow->getValueType(0);
18558   if (!NarrowVT.is128BitVector())
18559     return SDValue();
18560
18561   if (Narrow->getOpcode() != ISD::XOR &&
18562       Narrow->getOpcode() != ISD::AND &&
18563       Narrow->getOpcode() != ISD::OR)
18564     return SDValue();
18565
18566   SDValue N0  = Narrow->getOperand(0);
18567   SDValue N1  = Narrow->getOperand(1);
18568   SDLoc DL(Narrow);
18569
18570   // The Left side has to be a trunc.
18571   if (N0.getOpcode() != ISD::TRUNCATE)
18572     return SDValue();
18573
18574   // The type of the truncated inputs.
18575   EVT WideVT = N0->getOperand(0)->getValueType(0);
18576   if (WideVT != VT)
18577     return SDValue();
18578
18579   // The right side has to be a 'trunc' or a constant vector.
18580   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
18581   bool RHSConst = (isSplatVector(N1.getNode()) &&
18582                    isa<ConstantSDNode>(N1->getOperand(0)));
18583   if (!RHSTrunc && !RHSConst)
18584     return SDValue();
18585
18586   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18587
18588   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
18589     return SDValue();
18590
18591   // Set N0 and N1 to hold the inputs to the new wide operation.
18592   N0 = N0->getOperand(0);
18593   if (RHSConst) {
18594     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
18595                      N1->getOperand(0));
18596     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
18597     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
18598   } else if (RHSTrunc) {
18599     N1 = N1->getOperand(0);
18600   }
18601
18602   // Generate the wide operation.
18603   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
18604   unsigned Opcode = N->getOpcode();
18605   switch (Opcode) {
18606   case ISD::ANY_EXTEND:
18607     return Op;
18608   case ISD::ZERO_EXTEND: {
18609     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
18610     APInt Mask = APInt::getAllOnesValue(InBits);
18611     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
18612     return DAG.getNode(ISD::AND, DL, VT,
18613                        Op, DAG.getConstant(Mask, VT));
18614   }
18615   case ISD::SIGN_EXTEND:
18616     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
18617                        Op, DAG.getValueType(NarrowVT));
18618   default:
18619     llvm_unreachable("Unexpected opcode");
18620   }
18621 }
18622
18623 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
18624                                  TargetLowering::DAGCombinerInfo &DCI,
18625                                  const X86Subtarget *Subtarget) {
18626   EVT VT = N->getValueType(0);
18627   if (DCI.isBeforeLegalizeOps())
18628     return SDValue();
18629
18630   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18631   if (R.getNode())
18632     return R;
18633
18634   // Create BEXTR instructions
18635   // BEXTR is ((X >> imm) & (2**size-1))
18636   if (VT == MVT::i32 || VT == MVT::i64) {
18637     SDValue N0 = N->getOperand(0);
18638     SDValue N1 = N->getOperand(1);
18639     SDLoc DL(N);
18640
18641     // Check for BEXTR.
18642     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
18643         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
18644       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
18645       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
18646       if (MaskNode && ShiftNode) {
18647         uint64_t Mask = MaskNode->getZExtValue();
18648         uint64_t Shift = ShiftNode->getZExtValue();
18649         if (isMask_64(Mask)) {
18650           uint64_t MaskSize = CountPopulation_64(Mask);
18651           if (Shift + MaskSize <= VT.getSizeInBits())
18652             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
18653                                DAG.getConstant(Shift | (MaskSize << 8), VT));
18654         }
18655       }
18656     } // BEXTR
18657
18658     return SDValue();
18659   }
18660
18661   // Want to form ANDNP nodes:
18662   // 1) In the hopes of then easily combining them with OR and AND nodes
18663   //    to form PBLEND/PSIGN.
18664   // 2) To match ANDN packed intrinsics
18665   if (VT != MVT::v2i64 && VT != MVT::v4i64)
18666     return SDValue();
18667
18668   SDValue N0 = N->getOperand(0);
18669   SDValue N1 = N->getOperand(1);
18670   SDLoc DL(N);
18671
18672   // Check LHS for vnot
18673   if (N0.getOpcode() == ISD::XOR &&
18674       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
18675       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
18676     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
18677
18678   // Check RHS for vnot
18679   if (N1.getOpcode() == ISD::XOR &&
18680       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
18681       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
18682     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
18683
18684   return SDValue();
18685 }
18686
18687 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
18688                                 TargetLowering::DAGCombinerInfo &DCI,
18689                                 const X86Subtarget *Subtarget) {
18690   if (DCI.isBeforeLegalizeOps())
18691     return SDValue();
18692
18693   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
18694   if (R.getNode())
18695     return R;
18696
18697   SDValue N0 = N->getOperand(0);
18698   SDValue N1 = N->getOperand(1);
18699   EVT VT = N->getValueType(0);
18700
18701   // look for psign/blend
18702   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
18703     if (!Subtarget->hasSSSE3() ||
18704         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
18705       return SDValue();
18706
18707     // Canonicalize pandn to RHS
18708     if (N0.getOpcode() == X86ISD::ANDNP)
18709       std::swap(N0, N1);
18710     // or (and (m, y), (pandn m, x))
18711     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
18712       SDValue Mask = N1.getOperand(0);
18713       SDValue X    = N1.getOperand(1);
18714       SDValue Y;
18715       if (N0.getOperand(0) == Mask)
18716         Y = N0.getOperand(1);
18717       if (N0.getOperand(1) == Mask)
18718         Y = N0.getOperand(0);
18719
18720       // Check to see if the mask appeared in both the AND and ANDNP and
18721       if (!Y.getNode())
18722         return SDValue();
18723
18724       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
18725       // Look through mask bitcast.
18726       if (Mask.getOpcode() == ISD::BITCAST)
18727         Mask = Mask.getOperand(0);
18728       if (X.getOpcode() == ISD::BITCAST)
18729         X = X.getOperand(0);
18730       if (Y.getOpcode() == ISD::BITCAST)
18731         Y = Y.getOperand(0);
18732
18733       EVT MaskVT = Mask.getValueType();
18734
18735       // Validate that the Mask operand is a vector sra node.
18736       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
18737       // there is no psrai.b
18738       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
18739       unsigned SraAmt = ~0;
18740       if (Mask.getOpcode() == ISD::SRA) {
18741         SDValue Amt = Mask.getOperand(1);
18742         if (isSplatVector(Amt.getNode())) {
18743           SDValue SclrAmt = Amt->getOperand(0);
18744           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
18745             SraAmt = C->getZExtValue();
18746         }
18747       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
18748         SDValue SraC = Mask.getOperand(1);
18749         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
18750       }
18751       if ((SraAmt + 1) != EltBits)
18752         return SDValue();
18753
18754       SDLoc DL(N);
18755
18756       // Now we know we at least have a plendvb with the mask val.  See if
18757       // we can form a psignb/w/d.
18758       // psign = x.type == y.type == mask.type && y = sub(0, x);
18759       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
18760           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
18761           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
18762         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
18763                "Unsupported VT for PSIGN");
18764         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
18765         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18766       }
18767       // PBLENDVB only available on SSE 4.1
18768       if (!Subtarget->hasSSE41())
18769         return SDValue();
18770
18771       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
18772
18773       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
18774       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
18775       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
18776       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
18777       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
18778     }
18779   }
18780
18781   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
18782     return SDValue();
18783
18784   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
18785   MachineFunction &MF = DAG.getMachineFunction();
18786   bool OptForSize = MF.getFunction()->getAttributes().
18787     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
18788
18789   // SHLD/SHRD instructions have lower register pressure, but on some
18790   // platforms they have higher latency than the equivalent
18791   // series of shifts/or that would otherwise be generated.
18792   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
18793   // have higher latencies and we are not optimizing for size.
18794   if (!OptForSize && Subtarget->isSHLDSlow())
18795     return SDValue();
18796
18797   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
18798     std::swap(N0, N1);
18799   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
18800     return SDValue();
18801   if (!N0.hasOneUse() || !N1.hasOneUse())
18802     return SDValue();
18803
18804   SDValue ShAmt0 = N0.getOperand(1);
18805   if (ShAmt0.getValueType() != MVT::i8)
18806     return SDValue();
18807   SDValue ShAmt1 = N1.getOperand(1);
18808   if (ShAmt1.getValueType() != MVT::i8)
18809     return SDValue();
18810   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
18811     ShAmt0 = ShAmt0.getOperand(0);
18812   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
18813     ShAmt1 = ShAmt1.getOperand(0);
18814
18815   SDLoc DL(N);
18816   unsigned Opc = X86ISD::SHLD;
18817   SDValue Op0 = N0.getOperand(0);
18818   SDValue Op1 = N1.getOperand(0);
18819   if (ShAmt0.getOpcode() == ISD::SUB) {
18820     Opc = X86ISD::SHRD;
18821     std::swap(Op0, Op1);
18822     std::swap(ShAmt0, ShAmt1);
18823   }
18824
18825   unsigned Bits = VT.getSizeInBits();
18826   if (ShAmt1.getOpcode() == ISD::SUB) {
18827     SDValue Sum = ShAmt1.getOperand(0);
18828     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
18829       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
18830       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
18831         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
18832       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
18833         return DAG.getNode(Opc, DL, VT,
18834                            Op0, Op1,
18835                            DAG.getNode(ISD::TRUNCATE, DL,
18836                                        MVT::i8, ShAmt0));
18837     }
18838   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
18839     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
18840     if (ShAmt0C &&
18841         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
18842       return DAG.getNode(Opc, DL, VT,
18843                          N0.getOperand(0), N1.getOperand(0),
18844                          DAG.getNode(ISD::TRUNCATE, DL,
18845                                        MVT::i8, ShAmt0));
18846   }
18847
18848   return SDValue();
18849 }
18850
18851 // Generate NEG and CMOV for integer abs.
18852 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
18853   EVT VT = N->getValueType(0);
18854
18855   // Since X86 does not have CMOV for 8-bit integer, we don't convert
18856   // 8-bit integer abs to NEG and CMOV.
18857   if (VT.isInteger() && VT.getSizeInBits() == 8)
18858     return SDValue();
18859
18860   SDValue N0 = N->getOperand(0);
18861   SDValue N1 = N->getOperand(1);
18862   SDLoc DL(N);
18863
18864   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
18865   // and change it to SUB and CMOV.
18866   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
18867       N0.getOpcode() == ISD::ADD &&
18868       N0.getOperand(1) == N1 &&
18869       N1.getOpcode() == ISD::SRA &&
18870       N1.getOperand(0) == N0.getOperand(0))
18871     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
18872       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
18873         // Generate SUB & CMOV.
18874         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
18875                                   DAG.getConstant(0, VT), N0.getOperand(0));
18876
18877         SDValue Ops[] = { N0.getOperand(0), Neg,
18878                           DAG.getConstant(X86::COND_GE, MVT::i8),
18879                           SDValue(Neg.getNode(), 1) };
18880         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
18881       }
18882   return SDValue();
18883 }
18884
18885 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
18886 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
18887                                  TargetLowering::DAGCombinerInfo &DCI,
18888                                  const X86Subtarget *Subtarget) {
18889   if (DCI.isBeforeLegalizeOps())
18890     return SDValue();
18891
18892   if (Subtarget->hasCMov()) {
18893     SDValue RV = performIntegerAbsCombine(N, DAG);
18894     if (RV.getNode())
18895       return RV;
18896   }
18897
18898   return SDValue();
18899 }
18900
18901 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
18902 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
18903                                   TargetLowering::DAGCombinerInfo &DCI,
18904                                   const X86Subtarget *Subtarget) {
18905   LoadSDNode *Ld = cast<LoadSDNode>(N);
18906   EVT RegVT = Ld->getValueType(0);
18907   EVT MemVT = Ld->getMemoryVT();
18908   SDLoc dl(Ld);
18909   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18910   unsigned RegSz = RegVT.getSizeInBits();
18911
18912   // On Sandybridge unaligned 256bit loads are inefficient.
18913   ISD::LoadExtType Ext = Ld->getExtensionType();
18914   unsigned Alignment = Ld->getAlignment();
18915   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
18916   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
18917       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
18918     unsigned NumElems = RegVT.getVectorNumElements();
18919     if (NumElems < 2)
18920       return SDValue();
18921
18922     SDValue Ptr = Ld->getBasePtr();
18923     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
18924
18925     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
18926                                   NumElems/2);
18927     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18928                                 Ld->getPointerInfo(), Ld->isVolatile(),
18929                                 Ld->isNonTemporal(), Ld->isInvariant(),
18930                                 Alignment);
18931     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18932     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
18933                                 Ld->getPointerInfo(), Ld->isVolatile(),
18934                                 Ld->isNonTemporal(), Ld->isInvariant(),
18935                                 std::min(16U, Alignment));
18936     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18937                              Load1.getValue(1),
18938                              Load2.getValue(1));
18939
18940     SDValue NewVec = DAG.getUNDEF(RegVT);
18941     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
18942     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
18943     return DCI.CombineTo(N, NewVec, TF, true);
18944   }
18945
18946   // If this is a vector EXT Load then attempt to optimize it using a
18947   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
18948   // expansion is still better than scalar code.
18949   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
18950   // emit a shuffle and a arithmetic shift.
18951   // TODO: It is possible to support ZExt by zeroing the undef values
18952   // during the shuffle phase or after the shuffle.
18953   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
18954       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
18955     assert(MemVT != RegVT && "Cannot extend to the same type");
18956     assert(MemVT.isVector() && "Must load a vector from memory");
18957
18958     unsigned NumElems = RegVT.getVectorNumElements();
18959     unsigned MemSz = MemVT.getSizeInBits();
18960     assert(RegSz > MemSz && "Register size must be greater than the mem size");
18961
18962     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
18963       return SDValue();
18964
18965     // All sizes must be a power of two.
18966     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
18967       return SDValue();
18968
18969     // Attempt to load the original value using scalar loads.
18970     // Find the largest scalar type that divides the total loaded size.
18971     MVT SclrLoadTy = MVT::i8;
18972     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
18973          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
18974       MVT Tp = (MVT::SimpleValueType)tp;
18975       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
18976         SclrLoadTy = Tp;
18977       }
18978     }
18979
18980     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
18981     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
18982         (64 <= MemSz))
18983       SclrLoadTy = MVT::f64;
18984
18985     // Calculate the number of scalar loads that we need to perform
18986     // in order to load our vector from memory.
18987     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
18988     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
18989       return SDValue();
18990
18991     unsigned loadRegZize = RegSz;
18992     if (Ext == ISD::SEXTLOAD && RegSz == 256)
18993       loadRegZize /= 2;
18994
18995     // Represent our vector as a sequence of elements which are the
18996     // largest scalar that we can load.
18997     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
18998       loadRegZize/SclrLoadTy.getSizeInBits());
18999
19000     // Represent the data using the same element type that is stored in
19001     // memory. In practice, we ''widen'' MemVT.
19002     EVT WideVecVT =
19003           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19004                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19005
19006     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19007       "Invalid vector type");
19008
19009     // We can't shuffle using an illegal type.
19010     if (!TLI.isTypeLegal(WideVecVT))
19011       return SDValue();
19012
19013     SmallVector<SDValue, 8> Chains;
19014     SDValue Ptr = Ld->getBasePtr();
19015     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19016                                         TLI.getPointerTy());
19017     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19018
19019     for (unsigned i = 0; i < NumLoads; ++i) {
19020       // Perform a single load.
19021       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19022                                        Ptr, Ld->getPointerInfo(),
19023                                        Ld->isVolatile(), Ld->isNonTemporal(),
19024                                        Ld->isInvariant(), Ld->getAlignment());
19025       Chains.push_back(ScalarLoad.getValue(1));
19026       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19027       // another round of DAGCombining.
19028       if (i == 0)
19029         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19030       else
19031         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19032                           ScalarLoad, DAG.getIntPtrConstant(i));
19033
19034       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19035     }
19036
19037     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19038
19039     // Bitcast the loaded value to a vector of the original element type, in
19040     // the size of the target vector type.
19041     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19042     unsigned SizeRatio = RegSz/MemSz;
19043
19044     if (Ext == ISD::SEXTLOAD) {
19045       // If we have SSE4.1 we can directly emit a VSEXT node.
19046       if (Subtarget->hasSSE41()) {
19047         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19048         return DCI.CombineTo(N, Sext, TF, true);
19049       }
19050
19051       // Otherwise we'll shuffle the small elements in the high bits of the
19052       // larger type and perform an arithmetic shift. If the shift is not legal
19053       // it's better to scalarize.
19054       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19055         return SDValue();
19056
19057       // Redistribute the loaded elements into the different locations.
19058       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19059       for (unsigned i = 0; i != NumElems; ++i)
19060         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19061
19062       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19063                                            DAG.getUNDEF(WideVecVT),
19064                                            &ShuffleVec[0]);
19065
19066       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19067
19068       // Build the arithmetic shift.
19069       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19070                      MemVT.getVectorElementType().getSizeInBits();
19071       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19072                           DAG.getConstant(Amt, RegVT));
19073
19074       return DCI.CombineTo(N, Shuff, TF, true);
19075     }
19076
19077     // Redistribute the loaded elements into the different locations.
19078     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19079     for (unsigned i = 0; i != NumElems; ++i)
19080       ShuffleVec[i*SizeRatio] = i;
19081
19082     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19083                                          DAG.getUNDEF(WideVecVT),
19084                                          &ShuffleVec[0]);
19085
19086     // Bitcast to the requested type.
19087     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19088     // Replace the original load with the new sequence
19089     // and return the new chain.
19090     return DCI.CombineTo(N, Shuff, TF, true);
19091   }
19092
19093   return SDValue();
19094 }
19095
19096 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19097 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19098                                    const X86Subtarget *Subtarget) {
19099   StoreSDNode *St = cast<StoreSDNode>(N);
19100   EVT VT = St->getValue().getValueType();
19101   EVT StVT = St->getMemoryVT();
19102   SDLoc dl(St);
19103   SDValue StoredVal = St->getOperand(1);
19104   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19105
19106   // If we are saving a concatenation of two XMM registers, perform two stores.
19107   // On Sandy Bridge, 256-bit memory operations are executed by two
19108   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19109   // memory  operation.
19110   unsigned Alignment = St->getAlignment();
19111   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19112   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19113       StVT == VT && !IsAligned) {
19114     unsigned NumElems = VT.getVectorNumElements();
19115     if (NumElems < 2)
19116       return SDValue();
19117
19118     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19119     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19120
19121     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19122     SDValue Ptr0 = St->getBasePtr();
19123     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19124
19125     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19126                                 St->getPointerInfo(), St->isVolatile(),
19127                                 St->isNonTemporal(), Alignment);
19128     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19129                                 St->getPointerInfo(), St->isVolatile(),
19130                                 St->isNonTemporal(),
19131                                 std::min(16U, Alignment));
19132     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19133   }
19134
19135   // Optimize trunc store (of multiple scalars) to shuffle and store.
19136   // First, pack all of the elements in one place. Next, store to memory
19137   // in fewer chunks.
19138   if (St->isTruncatingStore() && VT.isVector()) {
19139     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19140     unsigned NumElems = VT.getVectorNumElements();
19141     assert(StVT != VT && "Cannot truncate to the same type");
19142     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19143     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19144
19145     // From, To sizes and ElemCount must be pow of two
19146     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19147     // We are going to use the original vector elt for storing.
19148     // Accumulated smaller vector elements must be a multiple of the store size.
19149     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19150
19151     unsigned SizeRatio  = FromSz / ToSz;
19152
19153     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19154
19155     // Create a type on which we perform the shuffle
19156     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19157             StVT.getScalarType(), NumElems*SizeRatio);
19158
19159     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19160
19161     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19162     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19163     for (unsigned i = 0; i != NumElems; ++i)
19164       ShuffleVec[i] = i * SizeRatio;
19165
19166     // Can't shuffle using an illegal type.
19167     if (!TLI.isTypeLegal(WideVecVT))
19168       return SDValue();
19169
19170     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19171                                          DAG.getUNDEF(WideVecVT),
19172                                          &ShuffleVec[0]);
19173     // At this point all of the data is stored at the bottom of the
19174     // register. We now need to save it to mem.
19175
19176     // Find the largest store unit
19177     MVT StoreType = MVT::i8;
19178     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19179          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19180       MVT Tp = (MVT::SimpleValueType)tp;
19181       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19182         StoreType = Tp;
19183     }
19184
19185     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19186     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19187         (64 <= NumElems * ToSz))
19188       StoreType = MVT::f64;
19189
19190     // Bitcast the original vector into a vector of store-size units
19191     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19192             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19193     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19194     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19195     SmallVector<SDValue, 8> Chains;
19196     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19197                                         TLI.getPointerTy());
19198     SDValue Ptr = St->getBasePtr();
19199
19200     // Perform one or more big stores into memory.
19201     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19202       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19203                                    StoreType, ShuffWide,
19204                                    DAG.getIntPtrConstant(i));
19205       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19206                                 St->getPointerInfo(), St->isVolatile(),
19207                                 St->isNonTemporal(), St->getAlignment());
19208       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19209       Chains.push_back(Ch);
19210     }
19211
19212     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19213   }
19214
19215   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19216   // the FP state in cases where an emms may be missing.
19217   // A preferable solution to the general problem is to figure out the right
19218   // places to insert EMMS.  This qualifies as a quick hack.
19219
19220   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19221   if (VT.getSizeInBits() != 64)
19222     return SDValue();
19223
19224   const Function *F = DAG.getMachineFunction().getFunction();
19225   bool NoImplicitFloatOps = F->getAttributes().
19226     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19227   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19228                      && Subtarget->hasSSE2();
19229   if ((VT.isVector() ||
19230        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19231       isa<LoadSDNode>(St->getValue()) &&
19232       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19233       St->getChain().hasOneUse() && !St->isVolatile()) {
19234     SDNode* LdVal = St->getValue().getNode();
19235     LoadSDNode *Ld = nullptr;
19236     int TokenFactorIndex = -1;
19237     SmallVector<SDValue, 8> Ops;
19238     SDNode* ChainVal = St->getChain().getNode();
19239     // Must be a store of a load.  We currently handle two cases:  the load
19240     // is a direct child, and it's under an intervening TokenFactor.  It is
19241     // possible to dig deeper under nested TokenFactors.
19242     if (ChainVal == LdVal)
19243       Ld = cast<LoadSDNode>(St->getChain());
19244     else if (St->getValue().hasOneUse() &&
19245              ChainVal->getOpcode() == ISD::TokenFactor) {
19246       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19247         if (ChainVal->getOperand(i).getNode() == LdVal) {
19248           TokenFactorIndex = i;
19249           Ld = cast<LoadSDNode>(St->getValue());
19250         } else
19251           Ops.push_back(ChainVal->getOperand(i));
19252       }
19253     }
19254
19255     if (!Ld || !ISD::isNormalLoad(Ld))
19256       return SDValue();
19257
19258     // If this is not the MMX case, i.e. we are just turning i64 load/store
19259     // into f64 load/store, avoid the transformation if there are multiple
19260     // uses of the loaded value.
19261     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19262       return SDValue();
19263
19264     SDLoc LdDL(Ld);
19265     SDLoc StDL(N);
19266     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19267     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19268     // pair instead.
19269     if (Subtarget->is64Bit() || F64IsLegal) {
19270       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19271       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19272                                   Ld->getPointerInfo(), Ld->isVolatile(),
19273                                   Ld->isNonTemporal(), Ld->isInvariant(),
19274                                   Ld->getAlignment());
19275       SDValue NewChain = NewLd.getValue(1);
19276       if (TokenFactorIndex != -1) {
19277         Ops.push_back(NewChain);
19278         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19279       }
19280       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19281                           St->getPointerInfo(),
19282                           St->isVolatile(), St->isNonTemporal(),
19283                           St->getAlignment());
19284     }
19285
19286     // Otherwise, lower to two pairs of 32-bit loads / stores.
19287     SDValue LoAddr = Ld->getBasePtr();
19288     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19289                                  DAG.getConstant(4, MVT::i32));
19290
19291     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19292                                Ld->getPointerInfo(),
19293                                Ld->isVolatile(), Ld->isNonTemporal(),
19294                                Ld->isInvariant(), Ld->getAlignment());
19295     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19296                                Ld->getPointerInfo().getWithOffset(4),
19297                                Ld->isVolatile(), Ld->isNonTemporal(),
19298                                Ld->isInvariant(),
19299                                MinAlign(Ld->getAlignment(), 4));
19300
19301     SDValue NewChain = LoLd.getValue(1);
19302     if (TokenFactorIndex != -1) {
19303       Ops.push_back(LoLd);
19304       Ops.push_back(HiLd);
19305       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19306     }
19307
19308     LoAddr = St->getBasePtr();
19309     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19310                          DAG.getConstant(4, MVT::i32));
19311
19312     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19313                                 St->getPointerInfo(),
19314                                 St->isVolatile(), St->isNonTemporal(),
19315                                 St->getAlignment());
19316     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19317                                 St->getPointerInfo().getWithOffset(4),
19318                                 St->isVolatile(),
19319                                 St->isNonTemporal(),
19320                                 MinAlign(St->getAlignment(), 4));
19321     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19322   }
19323   return SDValue();
19324 }
19325
19326 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19327 /// and return the operands for the horizontal operation in LHS and RHS.  A
19328 /// horizontal operation performs the binary operation on successive elements
19329 /// of its first operand, then on successive elements of its second operand,
19330 /// returning the resulting values in a vector.  For example, if
19331 ///   A = < float a0, float a1, float a2, float a3 >
19332 /// and
19333 ///   B = < float b0, float b1, float b2, float b3 >
19334 /// then the result of doing a horizontal operation on A and B is
19335 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19336 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19337 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19338 /// set to A, RHS to B, and the routine returns 'true'.
19339 /// Note that the binary operation should have the property that if one of the
19340 /// operands is UNDEF then the result is UNDEF.
19341 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19342   // Look for the following pattern: if
19343   //   A = < float a0, float a1, float a2, float a3 >
19344   //   B = < float b0, float b1, float b2, float b3 >
19345   // and
19346   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19347   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19348   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19349   // which is A horizontal-op B.
19350
19351   // At least one of the operands should be a vector shuffle.
19352   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19353       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19354     return false;
19355
19356   MVT VT = LHS.getSimpleValueType();
19357
19358   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19359          "Unsupported vector type for horizontal add/sub");
19360
19361   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19362   // operate independently on 128-bit lanes.
19363   unsigned NumElts = VT.getVectorNumElements();
19364   unsigned NumLanes = VT.getSizeInBits()/128;
19365   unsigned NumLaneElts = NumElts / NumLanes;
19366   assert((NumLaneElts % 2 == 0) &&
19367          "Vector type should have an even number of elements in each lane");
19368   unsigned HalfLaneElts = NumLaneElts/2;
19369
19370   // View LHS in the form
19371   //   LHS = VECTOR_SHUFFLE A, B, LMask
19372   // If LHS is not a shuffle then pretend it is the shuffle
19373   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19374   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19375   // type VT.
19376   SDValue A, B;
19377   SmallVector<int, 16> LMask(NumElts);
19378   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19379     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19380       A = LHS.getOperand(0);
19381     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19382       B = LHS.getOperand(1);
19383     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19384     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19385   } else {
19386     if (LHS.getOpcode() != ISD::UNDEF)
19387       A = LHS;
19388     for (unsigned i = 0; i != NumElts; ++i)
19389       LMask[i] = i;
19390   }
19391
19392   // Likewise, view RHS in the form
19393   //   RHS = VECTOR_SHUFFLE C, D, RMask
19394   SDValue C, D;
19395   SmallVector<int, 16> RMask(NumElts);
19396   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19397     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
19398       C = RHS.getOperand(0);
19399     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
19400       D = RHS.getOperand(1);
19401     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
19402     std::copy(Mask.begin(), Mask.end(), RMask.begin());
19403   } else {
19404     if (RHS.getOpcode() != ISD::UNDEF)
19405       C = RHS;
19406     for (unsigned i = 0; i != NumElts; ++i)
19407       RMask[i] = i;
19408   }
19409
19410   // Check that the shuffles are both shuffling the same vectors.
19411   if (!(A == C && B == D) && !(A == D && B == C))
19412     return false;
19413
19414   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
19415   if (!A.getNode() && !B.getNode())
19416     return false;
19417
19418   // If A and B occur in reverse order in RHS, then "swap" them (which means
19419   // rewriting the mask).
19420   if (A != C)
19421     CommuteVectorShuffleMask(RMask, NumElts);
19422
19423   // At this point LHS and RHS are equivalent to
19424   //   LHS = VECTOR_SHUFFLE A, B, LMask
19425   //   RHS = VECTOR_SHUFFLE A, B, RMask
19426   // Check that the masks correspond to performing a horizontal operation.
19427   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
19428     for (unsigned i = 0; i != NumLaneElts; ++i) {
19429       int LIdx = LMask[i+l], RIdx = RMask[i+l];
19430
19431       // Ignore any UNDEF components.
19432       if (LIdx < 0 || RIdx < 0 ||
19433           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
19434           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
19435         continue;
19436
19437       // Check that successive elements are being operated on.  If not, this is
19438       // not a horizontal operation.
19439       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
19440       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
19441       if (!(LIdx == Index && RIdx == Index + 1) &&
19442           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
19443         return false;
19444     }
19445   }
19446
19447   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
19448   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
19449   return true;
19450 }
19451
19452 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
19453 static SDValue PerformFADDCombine(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 adds from adds 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, true))
19463     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
19464   return SDValue();
19465 }
19466
19467 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
19468 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
19469                                   const X86Subtarget *Subtarget) {
19470   EVT VT = N->getValueType(0);
19471   SDValue LHS = N->getOperand(0);
19472   SDValue RHS = N->getOperand(1);
19473
19474   // Try to synthesize horizontal subs from subs of shuffles.
19475   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19476        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19477       isHorizontalBinOp(LHS, RHS, false))
19478     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
19479   return SDValue();
19480 }
19481
19482 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
19483 /// X86ISD::FXOR nodes.
19484 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
19485   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
19486   // F[X]OR(0.0, x) -> x
19487   // F[X]OR(x, 0.0) -> x
19488   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19489     if (C->getValueAPF().isPosZero())
19490       return N->getOperand(1);
19491   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19492     if (C->getValueAPF().isPosZero())
19493       return N->getOperand(0);
19494   return SDValue();
19495 }
19496
19497 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
19498 /// X86ISD::FMAX nodes.
19499 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
19500   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
19501
19502   // Only perform optimizations if UnsafeMath is used.
19503   if (!DAG.getTarget().Options.UnsafeFPMath)
19504     return SDValue();
19505
19506   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
19507   // into FMINC and FMAXC, which are Commutative operations.
19508   unsigned NewOp = 0;
19509   switch (N->getOpcode()) {
19510     default: llvm_unreachable("unknown opcode");
19511     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
19512     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
19513   }
19514
19515   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
19516                      N->getOperand(0), N->getOperand(1));
19517 }
19518
19519 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
19520 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
19521   // FAND(0.0, x) -> 0.0
19522   // FAND(x, 0.0) -> 0.0
19523   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19524     if (C->getValueAPF().isPosZero())
19525       return N->getOperand(0);
19526   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19527     if (C->getValueAPF().isPosZero())
19528       return N->getOperand(1);
19529   return SDValue();
19530 }
19531
19532 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
19533 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
19534   // FANDN(x, 0.0) -> 0.0
19535   // FANDN(0.0, x) -> x
19536   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
19537     if (C->getValueAPF().isPosZero())
19538       return N->getOperand(1);
19539   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
19540     if (C->getValueAPF().isPosZero())
19541       return N->getOperand(1);
19542   return SDValue();
19543 }
19544
19545 static SDValue PerformBTCombine(SDNode *N,
19546                                 SelectionDAG &DAG,
19547                                 TargetLowering::DAGCombinerInfo &DCI) {
19548   // BT ignores high bits in the bit index operand.
19549   SDValue Op1 = N->getOperand(1);
19550   if (Op1.hasOneUse()) {
19551     unsigned BitWidth = Op1.getValueSizeInBits();
19552     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
19553     APInt KnownZero, KnownOne;
19554     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
19555                                           !DCI.isBeforeLegalizeOps());
19556     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19557     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
19558         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
19559       DCI.CommitTargetLoweringOpt(TLO);
19560   }
19561   return SDValue();
19562 }
19563
19564 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
19565   SDValue Op = N->getOperand(0);
19566   if (Op.getOpcode() == ISD::BITCAST)
19567     Op = Op.getOperand(0);
19568   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
19569   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
19570       VT.getVectorElementType().getSizeInBits() ==
19571       OpVT.getVectorElementType().getSizeInBits()) {
19572     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
19573   }
19574   return SDValue();
19575 }
19576
19577 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
19578                                                const X86Subtarget *Subtarget) {
19579   EVT VT = N->getValueType(0);
19580   if (!VT.isVector())
19581     return SDValue();
19582
19583   SDValue N0 = N->getOperand(0);
19584   SDValue N1 = N->getOperand(1);
19585   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
19586   SDLoc dl(N);
19587
19588   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
19589   // both SSE and AVX2 since there is no sign-extended shift right
19590   // operation on a vector with 64-bit elements.
19591   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
19592   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
19593   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
19594       N0.getOpcode() == ISD::SIGN_EXTEND)) {
19595     SDValue N00 = N0.getOperand(0);
19596
19597     // EXTLOAD has a better solution on AVX2,
19598     // it may be replaced with X86ISD::VSEXT node.
19599     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
19600       if (!ISD::isNormalLoad(N00.getNode()))
19601         return SDValue();
19602
19603     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
19604         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
19605                                   N00, N1);
19606       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
19607     }
19608   }
19609   return SDValue();
19610 }
19611
19612 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
19613                                   TargetLowering::DAGCombinerInfo &DCI,
19614                                   const X86Subtarget *Subtarget) {
19615   if (!DCI.isBeforeLegalizeOps())
19616     return SDValue();
19617
19618   if (!Subtarget->hasFp256())
19619     return SDValue();
19620
19621   EVT VT = N->getValueType(0);
19622   if (VT.isVector() && VT.getSizeInBits() == 256) {
19623     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19624     if (R.getNode())
19625       return R;
19626   }
19627
19628   return SDValue();
19629 }
19630
19631 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
19632                                  const X86Subtarget* Subtarget) {
19633   SDLoc dl(N);
19634   EVT VT = N->getValueType(0);
19635
19636   // Let legalize expand this if it isn't a legal type yet.
19637   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19638     return SDValue();
19639
19640   EVT ScalarVT = VT.getScalarType();
19641   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
19642       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
19643     return SDValue();
19644
19645   SDValue A = N->getOperand(0);
19646   SDValue B = N->getOperand(1);
19647   SDValue C = N->getOperand(2);
19648
19649   bool NegA = (A.getOpcode() == ISD::FNEG);
19650   bool NegB = (B.getOpcode() == ISD::FNEG);
19651   bool NegC = (C.getOpcode() == ISD::FNEG);
19652
19653   // Negative multiplication when NegA xor NegB
19654   bool NegMul = (NegA != NegB);
19655   if (NegA)
19656     A = A.getOperand(0);
19657   if (NegB)
19658     B = B.getOperand(0);
19659   if (NegC)
19660     C = C.getOperand(0);
19661
19662   unsigned Opcode;
19663   if (!NegMul)
19664     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
19665   else
19666     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
19667
19668   return DAG.getNode(Opcode, dl, VT, A, B, C);
19669 }
19670
19671 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
19672                                   TargetLowering::DAGCombinerInfo &DCI,
19673                                   const X86Subtarget *Subtarget) {
19674   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
19675   //           (and (i32 x86isd::setcc_carry), 1)
19676   // This eliminates the zext. This transformation is necessary because
19677   // ISD::SETCC is always legalized to i8.
19678   SDLoc dl(N);
19679   SDValue N0 = N->getOperand(0);
19680   EVT VT = N->getValueType(0);
19681
19682   if (N0.getOpcode() == ISD::AND &&
19683       N0.hasOneUse() &&
19684       N0.getOperand(0).hasOneUse()) {
19685     SDValue N00 = N0.getOperand(0);
19686     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19687       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19688       if (!C || C->getZExtValue() != 1)
19689         return SDValue();
19690       return DAG.getNode(ISD::AND, dl, VT,
19691                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19692                                      N00.getOperand(0), N00.getOperand(1)),
19693                          DAG.getConstant(1, VT));
19694     }
19695   }
19696
19697   if (N0.getOpcode() == ISD::TRUNCATE &&
19698       N0.hasOneUse() &&
19699       N0.getOperand(0).hasOneUse()) {
19700     SDValue N00 = N0.getOperand(0);
19701     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
19702       return DAG.getNode(ISD::AND, dl, VT,
19703                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
19704                                      N00.getOperand(0), N00.getOperand(1)),
19705                          DAG.getConstant(1, VT));
19706     }
19707   }
19708   if (VT.is256BitVector()) {
19709     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
19710     if (R.getNode())
19711       return R;
19712   }
19713
19714   return SDValue();
19715 }
19716
19717 // Optimize x == -y --> x+y == 0
19718 //          x != -y --> x+y != 0
19719 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
19720                                       const X86Subtarget* Subtarget) {
19721   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
19722   SDValue LHS = N->getOperand(0);
19723   SDValue RHS = N->getOperand(1);
19724   EVT VT = N->getValueType(0);
19725   SDLoc DL(N);
19726
19727   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
19728     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
19729       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
19730         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19731                                    LHS.getValueType(), RHS, LHS.getOperand(1));
19732         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19733                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19734       }
19735   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
19736     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
19737       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
19738         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
19739                                    RHS.getValueType(), LHS, RHS.getOperand(1));
19740         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
19741                             addV, DAG.getConstant(0, addV.getValueType()), CC);
19742       }
19743
19744   if (VT.getScalarType() == MVT::i1) {
19745     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
19746       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19747     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
19748     if (!IsSEXT0 && !IsVZero0)
19749       return SDValue();
19750     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
19751       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
19752     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
19753
19754     if (!IsSEXT1 && !IsVZero1)
19755       return SDValue();
19756
19757     if (IsSEXT0 && IsVZero1) {
19758       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
19759       if (CC == ISD::SETEQ)
19760         return DAG.getNOT(DL, LHS.getOperand(0), VT);
19761       return LHS.getOperand(0);
19762     }
19763     if (IsSEXT1 && IsVZero0) {
19764       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
19765       if (CC == ISD::SETEQ)
19766         return DAG.getNOT(DL, RHS.getOperand(0), VT);
19767       return RHS.getOperand(0);
19768     }
19769   }
19770
19771   return SDValue();
19772 }
19773
19774 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
19775 // as "sbb reg,reg", since it can be extended without zext and produces
19776 // an all-ones bit which is more useful than 0/1 in some cases.
19777 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
19778                                MVT VT) {
19779   if (VT == MVT::i8)
19780     return DAG.getNode(ISD::AND, DL, VT,
19781                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19782                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
19783                        DAG.getConstant(1, VT));
19784   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
19785   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
19786                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
19787                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
19788 }
19789
19790 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
19791 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
19792                                    TargetLowering::DAGCombinerInfo &DCI,
19793                                    const X86Subtarget *Subtarget) {
19794   SDLoc DL(N);
19795   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
19796   SDValue EFLAGS = N->getOperand(1);
19797
19798   if (CC == X86::COND_A) {
19799     // Try to convert COND_A into COND_B in an attempt to facilitate
19800     // materializing "setb reg".
19801     //
19802     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
19803     // cannot take an immediate as its first operand.
19804     //
19805     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
19806         EFLAGS.getValueType().isInteger() &&
19807         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
19808       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
19809                                    EFLAGS.getNode()->getVTList(),
19810                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
19811       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
19812       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
19813     }
19814   }
19815
19816   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
19817   // a zext and produces an all-ones bit which is more useful than 0/1 in some
19818   // cases.
19819   if (CC == X86::COND_B)
19820     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
19821
19822   SDValue Flags;
19823
19824   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19825   if (Flags.getNode()) {
19826     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19827     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
19828   }
19829
19830   return SDValue();
19831 }
19832
19833 // Optimize branch condition evaluation.
19834 //
19835 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
19836                                     TargetLowering::DAGCombinerInfo &DCI,
19837                                     const X86Subtarget *Subtarget) {
19838   SDLoc DL(N);
19839   SDValue Chain = N->getOperand(0);
19840   SDValue Dest = N->getOperand(1);
19841   SDValue EFLAGS = N->getOperand(3);
19842   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
19843
19844   SDValue Flags;
19845
19846   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
19847   if (Flags.getNode()) {
19848     SDValue Cond = DAG.getConstant(CC, MVT::i8);
19849     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
19850                        Flags);
19851   }
19852
19853   return SDValue();
19854 }
19855
19856 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
19857                                         const X86TargetLowering *XTLI) {
19858   SDValue Op0 = N->getOperand(0);
19859   EVT InVT = Op0->getValueType(0);
19860
19861   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
19862   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
19863     SDLoc dl(N);
19864     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
19865     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
19866     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
19867   }
19868
19869   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
19870   // a 32-bit target where SSE doesn't support i64->FP operations.
19871   if (Op0.getOpcode() == ISD::LOAD) {
19872     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
19873     EVT VT = Ld->getValueType(0);
19874     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
19875         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
19876         !XTLI->getSubtarget()->is64Bit() &&
19877         VT == MVT::i64) {
19878       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
19879                                           Ld->getChain(), Op0, DAG);
19880       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
19881       return FILDChain;
19882     }
19883   }
19884   return SDValue();
19885 }
19886
19887 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
19888 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
19889                                  X86TargetLowering::DAGCombinerInfo &DCI) {
19890   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
19891   // the result is either zero or one (depending on the input carry bit).
19892   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
19893   if (X86::isZeroNode(N->getOperand(0)) &&
19894       X86::isZeroNode(N->getOperand(1)) &&
19895       // We don't have a good way to replace an EFLAGS use, so only do this when
19896       // dead right now.
19897       SDValue(N, 1).use_empty()) {
19898     SDLoc DL(N);
19899     EVT VT = N->getValueType(0);
19900     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
19901     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
19902                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
19903                                            DAG.getConstant(X86::COND_B,MVT::i8),
19904                                            N->getOperand(2)),
19905                                DAG.getConstant(1, VT));
19906     return DCI.CombineTo(N, Res1, CarryOut);
19907   }
19908
19909   return SDValue();
19910 }
19911
19912 // fold (add Y, (sete  X, 0)) -> adc  0, Y
19913 //      (add Y, (setne X, 0)) -> sbb -1, Y
19914 //      (sub (sete  X, 0), Y) -> sbb  0, Y
19915 //      (sub (setne X, 0), Y) -> adc -1, Y
19916 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
19917   SDLoc DL(N);
19918
19919   // Look through ZExts.
19920   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
19921   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
19922     return SDValue();
19923
19924   SDValue SetCC = Ext.getOperand(0);
19925   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
19926     return SDValue();
19927
19928   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
19929   if (CC != X86::COND_E && CC != X86::COND_NE)
19930     return SDValue();
19931
19932   SDValue Cmp = SetCC.getOperand(1);
19933   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
19934       !X86::isZeroNode(Cmp.getOperand(1)) ||
19935       !Cmp.getOperand(0).getValueType().isInteger())
19936     return SDValue();
19937
19938   SDValue CmpOp0 = Cmp.getOperand(0);
19939   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
19940                                DAG.getConstant(1, CmpOp0.getValueType()));
19941
19942   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
19943   if (CC == X86::COND_NE)
19944     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
19945                        DL, OtherVal.getValueType(), OtherVal,
19946                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
19947   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
19948                      DL, OtherVal.getValueType(), OtherVal,
19949                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
19950 }
19951
19952 /// PerformADDCombine - Do target-specific dag combines on integer adds.
19953 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
19954                                  const X86Subtarget *Subtarget) {
19955   EVT VT = N->getValueType(0);
19956   SDValue Op0 = N->getOperand(0);
19957   SDValue Op1 = N->getOperand(1);
19958
19959   // Try to synthesize horizontal adds from adds of shuffles.
19960   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19961        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19962       isHorizontalBinOp(Op0, Op1, true))
19963     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
19964
19965   return OptimizeConditionalInDecrement(N, DAG);
19966 }
19967
19968 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
19969                                  const X86Subtarget *Subtarget) {
19970   SDValue Op0 = N->getOperand(0);
19971   SDValue Op1 = N->getOperand(1);
19972
19973   // X86 can't encode an immediate LHS of a sub. See if we can push the
19974   // negation into a preceding instruction.
19975   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
19976     // If the RHS of the sub is a XOR with one use and a constant, invert the
19977     // immediate. Then add one to the LHS of the sub so we can turn
19978     // X-Y -> X+~Y+1, saving one register.
19979     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
19980         isa<ConstantSDNode>(Op1.getOperand(1))) {
19981       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
19982       EVT VT = Op0.getValueType();
19983       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
19984                                    Op1.getOperand(0),
19985                                    DAG.getConstant(~XorC, VT));
19986       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
19987                          DAG.getConstant(C->getAPIntValue()+1, VT));
19988     }
19989   }
19990
19991   // Try to synthesize horizontal adds from adds of shuffles.
19992   EVT VT = N->getValueType(0);
19993   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
19994        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
19995       isHorizontalBinOp(Op0, Op1, true))
19996     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
19997
19998   return OptimizeConditionalInDecrement(N, DAG);
19999 }
20000
20001 /// performVZEXTCombine - Performs build vector combines
20002 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20003                                         TargetLowering::DAGCombinerInfo &DCI,
20004                                         const X86Subtarget *Subtarget) {
20005   // (vzext (bitcast (vzext (x)) -> (vzext x)
20006   SDValue In = N->getOperand(0);
20007   while (In.getOpcode() == ISD::BITCAST)
20008     In = In.getOperand(0);
20009
20010   if (In.getOpcode() != X86ISD::VZEXT)
20011     return SDValue();
20012
20013   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20014                      In.getOperand(0));
20015 }
20016
20017 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20018                                              DAGCombinerInfo &DCI) const {
20019   SelectionDAG &DAG = DCI.DAG;
20020   switch (N->getOpcode()) {
20021   default: break;
20022   case ISD::EXTRACT_VECTOR_ELT:
20023     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20024   case ISD::VSELECT:
20025   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20026   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20027   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20028   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20029   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20030   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20031   case ISD::SHL:
20032   case ISD::SRA:
20033   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20034   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20035   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20036   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20037   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20038   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20039   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20040   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20041   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20042   case X86ISD::FXOR:
20043   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20044   case X86ISD::FMIN:
20045   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20046   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20047   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20048   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20049   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20050   case ISD::ANY_EXTEND:
20051   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20052   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20053   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20054   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20055   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20056   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20057   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20058   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20059   case X86ISD::SHUFP:       // Handle all target specific shuffles
20060   case X86ISD::PALIGNR:
20061   case X86ISD::UNPCKH:
20062   case X86ISD::UNPCKL:
20063   case X86ISD::MOVHLPS:
20064   case X86ISD::MOVLHPS:
20065   case X86ISD::PSHUFD:
20066   case X86ISD::PSHUFHW:
20067   case X86ISD::PSHUFLW:
20068   case X86ISD::MOVSS:
20069   case X86ISD::MOVSD:
20070   case X86ISD::VPERMILP:
20071   case X86ISD::VPERM2X128:
20072   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20073   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20074   }
20075
20076   return SDValue();
20077 }
20078
20079 /// isTypeDesirableForOp - Return true if the target has native support for
20080 /// the specified value type and it is 'desirable' to use the type for the
20081 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20082 /// instruction encodings are longer and some i16 instructions are slow.
20083 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20084   if (!isTypeLegal(VT))
20085     return false;
20086   if (VT != MVT::i16)
20087     return true;
20088
20089   switch (Opc) {
20090   default:
20091     return true;
20092   case ISD::LOAD:
20093   case ISD::SIGN_EXTEND:
20094   case ISD::ZERO_EXTEND:
20095   case ISD::ANY_EXTEND:
20096   case ISD::SHL:
20097   case ISD::SRL:
20098   case ISD::SUB:
20099   case ISD::ADD:
20100   case ISD::MUL:
20101   case ISD::AND:
20102   case ISD::OR:
20103   case ISD::XOR:
20104     return false;
20105   }
20106 }
20107
20108 /// IsDesirableToPromoteOp - This method query the target whether it is
20109 /// beneficial for dag combiner to promote the specified node. If true, it
20110 /// should return the desired promotion type by reference.
20111 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20112   EVT VT = Op.getValueType();
20113   if (VT != MVT::i16)
20114     return false;
20115
20116   bool Promote = false;
20117   bool Commute = false;
20118   switch (Op.getOpcode()) {
20119   default: break;
20120   case ISD::LOAD: {
20121     LoadSDNode *LD = cast<LoadSDNode>(Op);
20122     // If the non-extending load has a single use and it's not live out, then it
20123     // might be folded.
20124     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20125                                                      Op.hasOneUse()*/) {
20126       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20127              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20128         // The only case where we'd want to promote LOAD (rather then it being
20129         // promoted as an operand is when it's only use is liveout.
20130         if (UI->getOpcode() != ISD::CopyToReg)
20131           return false;
20132       }
20133     }
20134     Promote = true;
20135     break;
20136   }
20137   case ISD::SIGN_EXTEND:
20138   case ISD::ZERO_EXTEND:
20139   case ISD::ANY_EXTEND:
20140     Promote = true;
20141     break;
20142   case ISD::SHL:
20143   case ISD::SRL: {
20144     SDValue N0 = Op.getOperand(0);
20145     // Look out for (store (shl (load), x)).
20146     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20147       return false;
20148     Promote = true;
20149     break;
20150   }
20151   case ISD::ADD:
20152   case ISD::MUL:
20153   case ISD::AND:
20154   case ISD::OR:
20155   case ISD::XOR:
20156     Commute = true;
20157     // fallthrough
20158   case ISD::SUB: {
20159     SDValue N0 = Op.getOperand(0);
20160     SDValue N1 = Op.getOperand(1);
20161     if (!Commute && MayFoldLoad(N1))
20162       return false;
20163     // Avoid disabling potential load folding opportunities.
20164     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20165       return false;
20166     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20167       return false;
20168     Promote = true;
20169   }
20170   }
20171
20172   PVT = MVT::i32;
20173   return Promote;
20174 }
20175
20176 //===----------------------------------------------------------------------===//
20177 //                           X86 Inline Assembly Support
20178 //===----------------------------------------------------------------------===//
20179
20180 namespace {
20181   // Helper to match a string separated by whitespace.
20182   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20183     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20184
20185     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20186       StringRef piece(*args[i]);
20187       if (!s.startswith(piece)) // Check if the piece matches.
20188         return false;
20189
20190       s = s.substr(piece.size());
20191       StringRef::size_type pos = s.find_first_not_of(" \t");
20192       if (pos == 0) // We matched a prefix.
20193         return false;
20194
20195       s = s.substr(pos);
20196     }
20197
20198     return s.empty();
20199   }
20200   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20201 }
20202
20203 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20204
20205   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20206     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20207         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20208         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20209
20210       if (AsmPieces.size() == 3)
20211         return true;
20212       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20213         return true;
20214     }
20215   }
20216   return false;
20217 }
20218
20219 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20220   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20221
20222   std::string AsmStr = IA->getAsmString();
20223
20224   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20225   if (!Ty || Ty->getBitWidth() % 16 != 0)
20226     return false;
20227
20228   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20229   SmallVector<StringRef, 4> AsmPieces;
20230   SplitString(AsmStr, AsmPieces, ";\n");
20231
20232   switch (AsmPieces.size()) {
20233   default: return false;
20234   case 1:
20235     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20236     // we will turn this bswap into something that will be lowered to logical
20237     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20238     // lower so don't worry about this.
20239     // bswap $0
20240     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20241         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20242         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20243         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20244         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20245         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20246       // No need to check constraints, nothing other than the equivalent of
20247       // "=r,0" would be valid here.
20248       return IntrinsicLowering::LowerToByteSwap(CI);
20249     }
20250
20251     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20252     if (CI->getType()->isIntegerTy(16) &&
20253         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20254         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20255          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20256       AsmPieces.clear();
20257       const std::string &ConstraintsStr = IA->getConstraintString();
20258       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20259       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20260       if (clobbersFlagRegisters(AsmPieces))
20261         return IntrinsicLowering::LowerToByteSwap(CI);
20262     }
20263     break;
20264   case 3:
20265     if (CI->getType()->isIntegerTy(32) &&
20266         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20267         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20268         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20269         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20270       AsmPieces.clear();
20271       const std::string &ConstraintsStr = IA->getConstraintString();
20272       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20273       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20274       if (clobbersFlagRegisters(AsmPieces))
20275         return IntrinsicLowering::LowerToByteSwap(CI);
20276     }
20277
20278     if (CI->getType()->isIntegerTy(64)) {
20279       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20280       if (Constraints.size() >= 2 &&
20281           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20282           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20283         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20284         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20285             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20286             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20287           return IntrinsicLowering::LowerToByteSwap(CI);
20288       }
20289     }
20290     break;
20291   }
20292   return false;
20293 }
20294
20295 /// getConstraintType - Given a constraint letter, return the type of
20296 /// constraint it is for this target.
20297 X86TargetLowering::ConstraintType
20298 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20299   if (Constraint.size() == 1) {
20300     switch (Constraint[0]) {
20301     case 'R':
20302     case 'q':
20303     case 'Q':
20304     case 'f':
20305     case 't':
20306     case 'u':
20307     case 'y':
20308     case 'x':
20309     case 'Y':
20310     case 'l':
20311       return C_RegisterClass;
20312     case 'a':
20313     case 'b':
20314     case 'c':
20315     case 'd':
20316     case 'S':
20317     case 'D':
20318     case 'A':
20319       return C_Register;
20320     case 'I':
20321     case 'J':
20322     case 'K':
20323     case 'L':
20324     case 'M':
20325     case 'N':
20326     case 'G':
20327     case 'C':
20328     case 'e':
20329     case 'Z':
20330       return C_Other;
20331     default:
20332       break;
20333     }
20334   }
20335   return TargetLowering::getConstraintType(Constraint);
20336 }
20337
20338 /// Examine constraint type and operand type and determine a weight value.
20339 /// This object must already have been set up with the operand type
20340 /// and the current alternative constraint selected.
20341 TargetLowering::ConstraintWeight
20342   X86TargetLowering::getSingleConstraintMatchWeight(
20343     AsmOperandInfo &info, const char *constraint) const {
20344   ConstraintWeight weight = CW_Invalid;
20345   Value *CallOperandVal = info.CallOperandVal;
20346     // If we don't have a value, we can't do a match,
20347     // but allow it at the lowest weight.
20348   if (!CallOperandVal)
20349     return CW_Default;
20350   Type *type = CallOperandVal->getType();
20351   // Look at the constraint type.
20352   switch (*constraint) {
20353   default:
20354     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20355   case 'R':
20356   case 'q':
20357   case 'Q':
20358   case 'a':
20359   case 'b':
20360   case 'c':
20361   case 'd':
20362   case 'S':
20363   case 'D':
20364   case 'A':
20365     if (CallOperandVal->getType()->isIntegerTy())
20366       weight = CW_SpecificReg;
20367     break;
20368   case 'f':
20369   case 't':
20370   case 'u':
20371     if (type->isFloatingPointTy())
20372       weight = CW_SpecificReg;
20373     break;
20374   case 'y':
20375     if (type->isX86_MMXTy() && Subtarget->hasMMX())
20376       weight = CW_SpecificReg;
20377     break;
20378   case 'x':
20379   case 'Y':
20380     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
20381         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
20382       weight = CW_Register;
20383     break;
20384   case 'I':
20385     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
20386       if (C->getZExtValue() <= 31)
20387         weight = CW_Constant;
20388     }
20389     break;
20390   case 'J':
20391     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20392       if (C->getZExtValue() <= 63)
20393         weight = CW_Constant;
20394     }
20395     break;
20396   case 'K':
20397     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20398       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
20399         weight = CW_Constant;
20400     }
20401     break;
20402   case 'L':
20403     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20404       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
20405         weight = CW_Constant;
20406     }
20407     break;
20408   case 'M':
20409     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20410       if (C->getZExtValue() <= 3)
20411         weight = CW_Constant;
20412     }
20413     break;
20414   case 'N':
20415     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20416       if (C->getZExtValue() <= 0xff)
20417         weight = CW_Constant;
20418     }
20419     break;
20420   case 'G':
20421   case 'C':
20422     if (dyn_cast<ConstantFP>(CallOperandVal)) {
20423       weight = CW_Constant;
20424     }
20425     break;
20426   case 'e':
20427     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20428       if ((C->getSExtValue() >= -0x80000000LL) &&
20429           (C->getSExtValue() <= 0x7fffffffLL))
20430         weight = CW_Constant;
20431     }
20432     break;
20433   case 'Z':
20434     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
20435       if (C->getZExtValue() <= 0xffffffff)
20436         weight = CW_Constant;
20437     }
20438     break;
20439   }
20440   return weight;
20441 }
20442
20443 /// LowerXConstraint - try to replace an X constraint, which matches anything,
20444 /// with another that has more specific requirements based on the type of the
20445 /// corresponding operand.
20446 const char *X86TargetLowering::
20447 LowerXConstraint(EVT ConstraintVT) const {
20448   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
20449   // 'f' like normal targets.
20450   if (ConstraintVT.isFloatingPoint()) {
20451     if (Subtarget->hasSSE2())
20452       return "Y";
20453     if (Subtarget->hasSSE1())
20454       return "x";
20455   }
20456
20457   return TargetLowering::LowerXConstraint(ConstraintVT);
20458 }
20459
20460 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
20461 /// vector.  If it is invalid, don't add anything to Ops.
20462 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
20463                                                      std::string &Constraint,
20464                                                      std::vector<SDValue>&Ops,
20465                                                      SelectionDAG &DAG) const {
20466   SDValue Result;
20467
20468   // Only support length 1 constraints for now.
20469   if (Constraint.length() > 1) return;
20470
20471   char ConstraintLetter = Constraint[0];
20472   switch (ConstraintLetter) {
20473   default: break;
20474   case 'I':
20475     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20476       if (C->getZExtValue() <= 31) {
20477         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20478         break;
20479       }
20480     }
20481     return;
20482   case 'J':
20483     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20484       if (C->getZExtValue() <= 63) {
20485         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20486         break;
20487       }
20488     }
20489     return;
20490   case 'K':
20491     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20492       if (isInt<8>(C->getSExtValue())) {
20493         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20494         break;
20495       }
20496     }
20497     return;
20498   case 'N':
20499     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20500       if (C->getZExtValue() <= 255) {
20501         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20502         break;
20503       }
20504     }
20505     return;
20506   case 'e': {
20507     // 32-bit signed value
20508     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20509       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20510                                            C->getSExtValue())) {
20511         // Widen to 64 bits here to get it sign extended.
20512         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
20513         break;
20514       }
20515     // FIXME gcc accepts some relocatable values here too, but only in certain
20516     // memory models; it's complicated.
20517     }
20518     return;
20519   }
20520   case 'Z': {
20521     // 32-bit unsigned value
20522     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
20523       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
20524                                            C->getZExtValue())) {
20525         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
20526         break;
20527       }
20528     }
20529     // FIXME gcc accepts some relocatable values here too, but only in certain
20530     // memory models; it's complicated.
20531     return;
20532   }
20533   case 'i': {
20534     // Literal immediates are always ok.
20535     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
20536       // Widen to 64 bits here to get it sign extended.
20537       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
20538       break;
20539     }
20540
20541     // In any sort of PIC mode addresses need to be computed at runtime by
20542     // adding in a register or some sort of table lookup.  These can't
20543     // be used as immediates.
20544     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
20545       return;
20546
20547     // If we are in non-pic codegen mode, we allow the address of a global (with
20548     // an optional displacement) to be used with 'i'.
20549     GlobalAddressSDNode *GA = nullptr;
20550     int64_t Offset = 0;
20551
20552     // Match either (GA), (GA+C), (GA+C1+C2), etc.
20553     while (1) {
20554       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
20555         Offset += GA->getOffset();
20556         break;
20557       } else if (Op.getOpcode() == ISD::ADD) {
20558         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20559           Offset += C->getZExtValue();
20560           Op = Op.getOperand(0);
20561           continue;
20562         }
20563       } else if (Op.getOpcode() == ISD::SUB) {
20564         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
20565           Offset += -C->getZExtValue();
20566           Op = Op.getOperand(0);
20567           continue;
20568         }
20569       }
20570
20571       // Otherwise, this isn't something we can handle, reject it.
20572       return;
20573     }
20574
20575     const GlobalValue *GV = GA->getGlobal();
20576     // If we require an extra load to get this address, as in PIC mode, we
20577     // can't accept it.
20578     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
20579                                                         getTargetMachine())))
20580       return;
20581
20582     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
20583                                         GA->getValueType(0), Offset);
20584     break;
20585   }
20586   }
20587
20588   if (Result.getNode()) {
20589     Ops.push_back(Result);
20590     return;
20591   }
20592   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
20593 }
20594
20595 std::pair<unsigned, const TargetRegisterClass*>
20596 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
20597                                                 MVT VT) const {
20598   // First, see if this is a constraint that directly corresponds to an LLVM
20599   // register class.
20600   if (Constraint.size() == 1) {
20601     // GCC Constraint Letters
20602     switch (Constraint[0]) {
20603     default: break;
20604       // TODO: Slight differences here in allocation order and leaving
20605       // RIP in the class. Do they matter any more here than they do
20606       // in the normal allocation?
20607     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
20608       if (Subtarget->is64Bit()) {
20609         if (VT == MVT::i32 || VT == MVT::f32)
20610           return std::make_pair(0U, &X86::GR32RegClass);
20611         if (VT == MVT::i16)
20612           return std::make_pair(0U, &X86::GR16RegClass);
20613         if (VT == MVT::i8 || VT == MVT::i1)
20614           return std::make_pair(0U, &X86::GR8RegClass);
20615         if (VT == MVT::i64 || VT == MVT::f64)
20616           return std::make_pair(0U, &X86::GR64RegClass);
20617         break;
20618       }
20619       // 32-bit fallthrough
20620     case 'Q':   // Q_REGS
20621       if (VT == MVT::i32 || VT == MVT::f32)
20622         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
20623       if (VT == MVT::i16)
20624         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
20625       if (VT == MVT::i8 || VT == MVT::i1)
20626         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
20627       if (VT == MVT::i64)
20628         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
20629       break;
20630     case 'r':   // GENERAL_REGS
20631     case 'l':   // INDEX_REGS
20632       if (VT == MVT::i8 || VT == MVT::i1)
20633         return std::make_pair(0U, &X86::GR8RegClass);
20634       if (VT == MVT::i16)
20635         return std::make_pair(0U, &X86::GR16RegClass);
20636       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
20637         return std::make_pair(0U, &X86::GR32RegClass);
20638       return std::make_pair(0U, &X86::GR64RegClass);
20639     case 'R':   // LEGACY_REGS
20640       if (VT == MVT::i8 || VT == MVT::i1)
20641         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
20642       if (VT == MVT::i16)
20643         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
20644       if (VT == MVT::i32 || !Subtarget->is64Bit())
20645         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
20646       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
20647     case 'f':  // FP Stack registers.
20648       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
20649       // value to the correct fpstack register class.
20650       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
20651         return std::make_pair(0U, &X86::RFP32RegClass);
20652       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
20653         return std::make_pair(0U, &X86::RFP64RegClass);
20654       return std::make_pair(0U, &X86::RFP80RegClass);
20655     case 'y':   // MMX_REGS if MMX allowed.
20656       if (!Subtarget->hasMMX()) break;
20657       return std::make_pair(0U, &X86::VR64RegClass);
20658     case 'Y':   // SSE_REGS if SSE2 allowed
20659       if (!Subtarget->hasSSE2()) break;
20660       // FALL THROUGH.
20661     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
20662       if (!Subtarget->hasSSE1()) break;
20663
20664       switch (VT.SimpleTy) {
20665       default: break;
20666       // Scalar SSE types.
20667       case MVT::f32:
20668       case MVT::i32:
20669         return std::make_pair(0U, &X86::FR32RegClass);
20670       case MVT::f64:
20671       case MVT::i64:
20672         return std::make_pair(0U, &X86::FR64RegClass);
20673       // Vector types.
20674       case MVT::v16i8:
20675       case MVT::v8i16:
20676       case MVT::v4i32:
20677       case MVT::v2i64:
20678       case MVT::v4f32:
20679       case MVT::v2f64:
20680         return std::make_pair(0U, &X86::VR128RegClass);
20681       // AVX types.
20682       case MVT::v32i8:
20683       case MVT::v16i16:
20684       case MVT::v8i32:
20685       case MVT::v4i64:
20686       case MVT::v8f32:
20687       case MVT::v4f64:
20688         return std::make_pair(0U, &X86::VR256RegClass);
20689       case MVT::v8f64:
20690       case MVT::v16f32:
20691       case MVT::v16i32:
20692       case MVT::v8i64:
20693         return std::make_pair(0U, &X86::VR512RegClass);
20694       }
20695       break;
20696     }
20697   }
20698
20699   // Use the default implementation in TargetLowering to convert the register
20700   // constraint into a member of a register class.
20701   std::pair<unsigned, const TargetRegisterClass*> Res;
20702   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
20703
20704   // Not found as a standard register?
20705   if (!Res.second) {
20706     // Map st(0) -> st(7) -> ST0
20707     if (Constraint.size() == 7 && Constraint[0] == '{' &&
20708         tolower(Constraint[1]) == 's' &&
20709         tolower(Constraint[2]) == 't' &&
20710         Constraint[3] == '(' &&
20711         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
20712         Constraint[5] == ')' &&
20713         Constraint[6] == '}') {
20714
20715       Res.first = X86::ST0+Constraint[4]-'0';
20716       Res.second = &X86::RFP80RegClass;
20717       return Res;
20718     }
20719
20720     // GCC allows "st(0)" to be called just plain "st".
20721     if (StringRef("{st}").equals_lower(Constraint)) {
20722       Res.first = X86::ST0;
20723       Res.second = &X86::RFP80RegClass;
20724       return Res;
20725     }
20726
20727     // flags -> EFLAGS
20728     if (StringRef("{flags}").equals_lower(Constraint)) {
20729       Res.first = X86::EFLAGS;
20730       Res.second = &X86::CCRRegClass;
20731       return Res;
20732     }
20733
20734     // 'A' means EAX + EDX.
20735     if (Constraint == "A") {
20736       Res.first = X86::EAX;
20737       Res.second = &X86::GR32_ADRegClass;
20738       return Res;
20739     }
20740     return Res;
20741   }
20742
20743   // Otherwise, check to see if this is a register class of the wrong value
20744   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
20745   // turn into {ax},{dx}.
20746   if (Res.second->hasType(VT))
20747     return Res;   // Correct type already, nothing to do.
20748
20749   // All of the single-register GCC register classes map their values onto
20750   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
20751   // really want an 8-bit or 32-bit register, map to the appropriate register
20752   // class and return the appropriate register.
20753   if (Res.second == &X86::GR16RegClass) {
20754     if (VT == MVT::i8 || VT == MVT::i1) {
20755       unsigned DestReg = 0;
20756       switch (Res.first) {
20757       default: break;
20758       case X86::AX: DestReg = X86::AL; break;
20759       case X86::DX: DestReg = X86::DL; break;
20760       case X86::CX: DestReg = X86::CL; break;
20761       case X86::BX: DestReg = X86::BL; break;
20762       }
20763       if (DestReg) {
20764         Res.first = DestReg;
20765         Res.second = &X86::GR8RegClass;
20766       }
20767     } else if (VT == MVT::i32 || VT == MVT::f32) {
20768       unsigned DestReg = 0;
20769       switch (Res.first) {
20770       default: break;
20771       case X86::AX: DestReg = X86::EAX; break;
20772       case X86::DX: DestReg = X86::EDX; break;
20773       case X86::CX: DestReg = X86::ECX; break;
20774       case X86::BX: DestReg = X86::EBX; break;
20775       case X86::SI: DestReg = X86::ESI; break;
20776       case X86::DI: DestReg = X86::EDI; break;
20777       case X86::BP: DestReg = X86::EBP; break;
20778       case X86::SP: DestReg = X86::ESP; break;
20779       }
20780       if (DestReg) {
20781         Res.first = DestReg;
20782         Res.second = &X86::GR32RegClass;
20783       }
20784     } else if (VT == MVT::i64 || VT == MVT::f64) {
20785       unsigned DestReg = 0;
20786       switch (Res.first) {
20787       default: break;
20788       case X86::AX: DestReg = X86::RAX; break;
20789       case X86::DX: DestReg = X86::RDX; break;
20790       case X86::CX: DestReg = X86::RCX; break;
20791       case X86::BX: DestReg = X86::RBX; break;
20792       case X86::SI: DestReg = X86::RSI; break;
20793       case X86::DI: DestReg = X86::RDI; break;
20794       case X86::BP: DestReg = X86::RBP; break;
20795       case X86::SP: DestReg = X86::RSP; break;
20796       }
20797       if (DestReg) {
20798         Res.first = DestReg;
20799         Res.second = &X86::GR64RegClass;
20800       }
20801     }
20802   } else if (Res.second == &X86::FR32RegClass ||
20803              Res.second == &X86::FR64RegClass ||
20804              Res.second == &X86::VR128RegClass ||
20805              Res.second == &X86::VR256RegClass ||
20806              Res.second == &X86::FR32XRegClass ||
20807              Res.second == &X86::FR64XRegClass ||
20808              Res.second == &X86::VR128XRegClass ||
20809              Res.second == &X86::VR256XRegClass ||
20810              Res.second == &X86::VR512RegClass) {
20811     // Handle references to XMM physical registers that got mapped into the
20812     // wrong class.  This can happen with constraints like {xmm0} where the
20813     // target independent register mapper will just pick the first match it can
20814     // find, ignoring the required type.
20815
20816     if (VT == MVT::f32 || VT == MVT::i32)
20817       Res.second = &X86::FR32RegClass;
20818     else if (VT == MVT::f64 || VT == MVT::i64)
20819       Res.second = &X86::FR64RegClass;
20820     else if (X86::VR128RegClass.hasType(VT))
20821       Res.second = &X86::VR128RegClass;
20822     else if (X86::VR256RegClass.hasType(VT))
20823       Res.second = &X86::VR256RegClass;
20824     else if (X86::VR512RegClass.hasType(VT))
20825       Res.second = &X86::VR512RegClass;
20826   }
20827
20828   return Res;
20829 }
20830
20831 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
20832                                             Type *Ty) const {
20833   // Scaling factors are not free at all.
20834   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
20835   // will take 2 allocations instead of 1 for plain addressing mode,
20836   // i.e. inst (reg1).
20837   if (isLegalAddressingMode(AM, Ty))
20838     // Scale represents reg2 * scale, thus account for 1
20839     // as soon as we use a second register.
20840     return AM.Scale != 0;
20841   return -1;
20842 }