Add 'static' keyword to some const arrays for consistency.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
18 #include "X86.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference.  Idx is an index in the 128 bits we
64 /// want.  It need not be aligned to a 128-bit bounday.  That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                    SelectionDAG &DAG, SDLoc dl) {
68   EVT VT = Vec.getValueType();
69   assert(VT.is256BitVector() && "Unexpected vector size!");
70   EVT ElVT = VT.getVectorElementType();
71   unsigned Factor = VT.getSizeInBits()/128;
72   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                   VT.getVectorNumElements()/Factor);
74
75   // Extract from UNDEF is UNDEF.
76   if (Vec.getOpcode() == ISD::UNDEF)
77     return DAG.getUNDEF(ResultVT);
78
79   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80   // we can match to VEXTRACTF128.
81   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83   // This is the index of the first element of the 128-bit chunk
84   // we want.
85   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                                * ElemsPerChunk);
87
88   // If the input is a buildvector just emit a smaller one.
89   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
90     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
91                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
92
93   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
94   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95                                VecIdx);
96
97   return Result;
98 }
99
100 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
101 /// sets things up to match to an AVX VINSERTF128 instruction or a
102 /// simple superregister reference.  Idx is an index in the 128 bits
103 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
104 /// lowering INSERT_VECTOR_ELT operations easier.
105 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
106                                   unsigned IdxVal, SelectionDAG &DAG,
107                                   SDLoc dl) {
108   // Inserting UNDEF is Result
109   if (Vec.getOpcode() == ISD::UNDEF)
110     return Result;
111
112   EVT VT = Vec.getValueType();
113   assert(VT.is128BitVector() && "Unexpected vector size!");
114
115   EVT ElVT = VT.getVectorElementType();
116   EVT ResultVT = Result.getValueType();
117
118   // Insert the relevant 128 bits.
119   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
120
121   // This is the index of the first element of the 128-bit chunk
122   // we want.
123   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
124                                * ElemsPerChunk);
125
126   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
127   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
128                      VecIdx);
129 }
130
131 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
132 /// instructions. This is used because creating CONCAT_VECTOR nodes of
133 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
134 /// large BUILD_VECTORS.
135 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
136                                    unsigned NumElems, SelectionDAG &DAG,
137                                    SDLoc dl) {
138   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
139   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
140 }
141
142 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
143   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
144   bool is64Bit = Subtarget->is64Bit();
145
146   if (Subtarget->isTargetEnvMacho()) {
147     if (is64Bit)
148       return new X86_64MachoTargetObjectFile();
149     return new TargetLoweringObjectFileMachO();
150   }
151
152   if (Subtarget->isTargetLinux())
153     return new X86LinuxTargetObjectFile();
154   if (Subtarget->isTargetELF())
155     return new TargetLoweringObjectFileELF();
156   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
157     return new TargetLoweringObjectFileCOFF();
158   llvm_unreachable("unknown subtarget type");
159 }
160
161 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
162   : TargetLowering(TM, createTLOF(TM)) {
163   Subtarget = &TM.getSubtarget<X86Subtarget>();
164   X86ScalarSSEf64 = Subtarget->hasSSE2();
165   X86ScalarSSEf32 = Subtarget->hasSSE1();
166   TD = getDataLayout();
167
168   resetOperationActions();
169 }
170
171 void X86TargetLowering::resetOperationActions() {
172   const TargetMachine &TM = getTargetMachine();
173   static bool FirstTimeThrough = true;
174
175   // If none of the target options have changed, then we don't need to reset the
176   // operation actions.
177   if (!FirstTimeThrough && TO == TM.Options) return;
178
179   if (!FirstTimeThrough) {
180     // Reinitialize the actions.
181     initActions();
182     FirstTimeThrough = false;
183   }
184
185   TO = TM.Options;
186
187   // Set up the TargetLowering object.
188   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
189
190   // X86 is weird, it always uses i8 for shift amounts and setcc results.
191   setBooleanContents(ZeroOrOneBooleanContent);
192   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
193   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
194
195   // For 64-bit since we have so many registers use the ILP scheduler, for
196   // 32-bit code use the register pressure specific scheduling.
197   // For Atom, always use ILP scheduling.
198   if (Subtarget->isAtom())
199     setSchedulingPreference(Sched::ILP);
200   else if (Subtarget->is64Bit())
201     setSchedulingPreference(Sched::ILP);
202   else
203     setSchedulingPreference(Sched::RegPressure);
204   const X86RegisterInfo *RegInfo =
205     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
206   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
207
208   // Bypass expensive divides on Atom when compiling with O2
209   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
210     addBypassSlowDiv(32, 8);
211     if (Subtarget->is64Bit())
212       addBypassSlowDiv(64, 16);
213   }
214
215   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
216     // Setup Windows compiler runtime calls.
217     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
218     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
219     setLibcallName(RTLIB::SREM_I64, "_allrem");
220     setLibcallName(RTLIB::UREM_I64, "_aullrem");
221     setLibcallName(RTLIB::MUL_I64, "_allmul");
222     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
223     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
224     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
225     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
226     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
227
228     // The _ftol2 runtime function has an unusual calling conv, which
229     // is modeled by a special pseudo-instruction.
230     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
231     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
232     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
233     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
234   }
235
236   if (Subtarget->isTargetDarwin()) {
237     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
238     setUseUnderscoreSetJmp(false);
239     setUseUnderscoreLongJmp(false);
240   } else if (Subtarget->isTargetMingw()) {
241     // MS runtime is weird: it exports _setjmp, but longjmp!
242     setUseUnderscoreSetJmp(true);
243     setUseUnderscoreLongJmp(false);
244   } else {
245     setUseUnderscoreSetJmp(true);
246     setUseUnderscoreLongJmp(true);
247   }
248
249   // Set up the register classes.
250   addRegisterClass(MVT::i8, &X86::GR8RegClass);
251   addRegisterClass(MVT::i16, &X86::GR16RegClass);
252   addRegisterClass(MVT::i32, &X86::GR32RegClass);
253   if (Subtarget->is64Bit())
254     addRegisterClass(MVT::i64, &X86::GR64RegClass);
255
256   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
257
258   // We don't accept any truncstore of integer registers.
259   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
260   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
261   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
262   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
263   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
264   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
265
266   // SETOEQ and SETUNE require checking two conditions.
267   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
268   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
269   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
270   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
271   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
272   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
273
274   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
275   // operation.
276   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
277   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
278   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
279
280   if (Subtarget->is64Bit()) {
281     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
282     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
283   } else if (!TM.Options.UseSoftFloat) {
284     // We have an algorithm for SSE2->double, and we turn this into a
285     // 64-bit FILD followed by conditional FADD for other targets.
286     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
287     // We have an algorithm for SSE2, and we turn this into a 64-bit
288     // FILD for other targets.
289     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
290   }
291
292   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
293   // this operation.
294   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
295   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
296
297   if (!TM.Options.UseSoftFloat) {
298     // SSE has no i16 to fp conversion, only i32
299     if (X86ScalarSSEf32) {
300       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
301       // f32 and f64 cases are Legal, f80 case is not
302       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
303     } else {
304       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
305       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
306     }
307   } else {
308     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
309     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
310   }
311
312   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
313   // are Legal, f80 is custom lowered.
314   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
315   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
316
317   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
318   // this operation.
319   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
320   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
321
322   if (X86ScalarSSEf32) {
323     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
324     // f32 and f64 cases are Legal, f80 case is not
325     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
326   } else {
327     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
328     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
329   }
330
331   // Handle FP_TO_UINT by promoting the destination to a larger signed
332   // conversion.
333   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
334   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
335   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
336
337   if (Subtarget->is64Bit()) {
338     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
339     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
340   } else if (!TM.Options.UseSoftFloat) {
341     // Since AVX is a superset of SSE3, only check for SSE here.
342     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
343       // Expand FP_TO_UINT into a select.
344       // FIXME: We would like to use a Custom expander here eventually to do
345       // the optimal thing for SSE vs. the default expansion in the legalizer.
346       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
347     else
348       // With SSE3 we can use fisttpll to convert to a signed i64; without
349       // SSE, we're stuck with a fistpll.
350       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
351   }
352
353   if (isTargetFTOL()) {
354     // Use the _ftol2 runtime function, which has a pseudo-instruction
355     // to handle its weird calling convention.
356     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
357   }
358
359   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
360   if (!X86ScalarSSEf64) {
361     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
362     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
363     if (Subtarget->is64Bit()) {
364       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
365       // Without SSE, i64->f64 goes through memory.
366       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
367     }
368   }
369
370   // Scalar integer divide and remainder are lowered to use operations that
371   // produce two results, to match the available instructions. This exposes
372   // the two-result form to trivial CSE, which is able to combine x/y and x%y
373   // into a single instruction.
374   //
375   // Scalar integer multiply-high is also lowered to use two-result
376   // operations, to match the available instructions. However, plain multiply
377   // (low) operations are left as Legal, as there are single-result
378   // instructions for this in x86. Using the two-result multiply instructions
379   // when both high and low results are needed must be arranged by dagcombine.
380   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
381     MVT VT = IntVTs[i];
382     setOperationAction(ISD::MULHS, VT, Expand);
383     setOperationAction(ISD::MULHU, VT, Expand);
384     setOperationAction(ISD::SDIV, VT, Expand);
385     setOperationAction(ISD::UDIV, VT, Expand);
386     setOperationAction(ISD::SREM, VT, Expand);
387     setOperationAction(ISD::UREM, VT, Expand);
388
389     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
390     setOperationAction(ISD::ADDC, VT, Custom);
391     setOperationAction(ISD::ADDE, VT, Custom);
392     setOperationAction(ISD::SUBC, VT, Custom);
393     setOperationAction(ISD::SUBE, VT, Custom);
394   }
395
396   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
397   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
398   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
399   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
400   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
401   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
402   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
403   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
404   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
405   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
406   if (Subtarget->is64Bit())
407     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
408   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
409   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
410   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
411   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
412   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
413   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
414   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
415   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
416
417   // Promote the i8 variants and force them on up to i32 which has a shorter
418   // encoding.
419   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
420   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
421   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
422   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
423   if (Subtarget->hasBMI()) {
424     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
425     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
426     if (Subtarget->is64Bit())
427       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
428   } else {
429     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
430     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
431     if (Subtarget->is64Bit())
432       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
433   }
434
435   if (Subtarget->hasLZCNT()) {
436     // When promoting the i8 variants, force them to i32 for a shorter
437     // encoding.
438     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
439     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
440     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
441     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
442     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
443     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
444     if (Subtarget->is64Bit())
445       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
446   } else {
447     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
448     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
449     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
450     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
451     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
452     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
453     if (Subtarget->is64Bit()) {
454       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
455       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
456     }
457   }
458
459   if (Subtarget->hasPOPCNT()) {
460     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
461   } else {
462     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
463     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
464     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
465     if (Subtarget->is64Bit())
466       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
467   }
468
469   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
470   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
471
472   // These should be promoted to a larger select which is supported.
473   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
474   // X86 wants to expand cmov itself.
475   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
476   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
477   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
478   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
479   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
480   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
481   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
482   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
483   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
484   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
485   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
486   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
487   if (Subtarget->is64Bit()) {
488     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
489     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
490   }
491   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
492   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
493   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
494   // support continuation, user-level threading, and etc.. As a result, no
495   // other SjLj exception interfaces are implemented and please don't build
496   // your own exception handling based on them.
497   // LLVM/Clang supports zero-cost DWARF exception handling.
498   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
499   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
500
501   // Darwin ABI issue.
502   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
503   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
504   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
505   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
506   if (Subtarget->is64Bit())
507     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
508   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
509   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
510   if (Subtarget->is64Bit()) {
511     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
512     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
513     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
514     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
515     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
516   }
517   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
518   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
519   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
520   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
521   if (Subtarget->is64Bit()) {
522     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
523     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
524     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
525   }
526
527   if (Subtarget->hasSSE1())
528     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
529
530   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
531
532   // Expand certain atomics
533   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
534     MVT VT = IntVTs[i];
535     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
536     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
537     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
538   }
539
540   if (!Subtarget->is64Bit()) {
541     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
542     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
543     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
544     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
545     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
546     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
547     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
548     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
549     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
550     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
551     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
552     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
553   }
554
555   if (Subtarget->hasCmpxchg16b()) {
556     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
557   }
558
559   // FIXME - use subtarget debug flags
560   if (!Subtarget->isTargetDarwin() &&
561       !Subtarget->isTargetELF() &&
562       !Subtarget->isTargetCygMing()) {
563     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
564   }
565
566   if (Subtarget->is64Bit()) {
567     setExceptionPointerRegister(X86::RAX);
568     setExceptionSelectorRegister(X86::RDX);
569   } else {
570     setExceptionPointerRegister(X86::EAX);
571     setExceptionSelectorRegister(X86::EDX);
572   }
573   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
574   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
575
576   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
577   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
578
579   setOperationAction(ISD::TRAP, MVT::Other, Legal);
580   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
581
582   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
583   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
584   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
585   if (Subtarget->is64Bit()) {
586     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
587     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
588   } else {
589     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
590     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
591   }
592
593   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
594   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
595
596   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
597     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
598                        MVT::i64 : MVT::i32, Custom);
599   else if (TM.Options.EnableSegmentedStacks)
600     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
601                        MVT::i64 : MVT::i32, Custom);
602   else
603     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
604                        MVT::i64 : MVT::i32, Expand);
605
606   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
607     // f32 and f64 use SSE.
608     // Set up the FP register classes.
609     addRegisterClass(MVT::f32, &X86::FR32RegClass);
610     addRegisterClass(MVT::f64, &X86::FR64RegClass);
611
612     // Use ANDPD to simulate FABS.
613     setOperationAction(ISD::FABS , MVT::f64, Custom);
614     setOperationAction(ISD::FABS , MVT::f32, Custom);
615
616     // Use XORP to simulate FNEG.
617     setOperationAction(ISD::FNEG , MVT::f64, Custom);
618     setOperationAction(ISD::FNEG , MVT::f32, Custom);
619
620     // Use ANDPD and ORPD to simulate FCOPYSIGN.
621     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
623
624     // Lower this to FGETSIGNx86 plus an AND.
625     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
626     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
627
628     // We don't support sin/cos/fmod
629     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
630     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
631     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
632     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
633     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
634     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
635
636     // Expand FP immediates into loads from the stack, except for the special
637     // cases we handle.
638     addLegalFPImmediate(APFloat(+0.0)); // xorpd
639     addLegalFPImmediate(APFloat(+0.0f)); // xorps
640   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
641     // Use SSE for f32, x87 for f64.
642     // Set up the FP register classes.
643     addRegisterClass(MVT::f32, &X86::FR32RegClass);
644     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
645
646     // Use ANDPS to simulate FABS.
647     setOperationAction(ISD::FABS , MVT::f32, Custom);
648
649     // Use XORP to simulate FNEG.
650     setOperationAction(ISD::FNEG , MVT::f32, Custom);
651
652     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
653
654     // Use ANDPS and ORPS to simulate FCOPYSIGN.
655     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
656     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
657
658     // We don't support sin/cos/fmod
659     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
660     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
661     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
662
663     // Special cases we handle for FP constants.
664     addLegalFPImmediate(APFloat(+0.0f)); // xorps
665     addLegalFPImmediate(APFloat(+0.0)); // FLD0
666     addLegalFPImmediate(APFloat(+1.0)); // FLD1
667     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
668     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
669
670     if (!TM.Options.UnsafeFPMath) {
671       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
672       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
673       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
674     }
675   } else if (!TM.Options.UseSoftFloat) {
676     // f32 and f64 in x87.
677     // Set up the FP register classes.
678     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
679     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
680
681     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
682     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
683     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
684     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
685
686     if (!TM.Options.UnsafeFPMath) {
687       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
688       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
689       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
690       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
691       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
692       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
693     }
694     addLegalFPImmediate(APFloat(+0.0)); // FLD0
695     addLegalFPImmediate(APFloat(+1.0)); // FLD1
696     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
697     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
698     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
699     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
700     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
701     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
702   }
703
704   // We don't support FMA.
705   setOperationAction(ISD::FMA, MVT::f64, Expand);
706   setOperationAction(ISD::FMA, MVT::f32, Expand);
707
708   // Long double always uses X87.
709   if (!TM.Options.UseSoftFloat) {
710     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
711     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
712     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
713     {
714       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
715       addLegalFPImmediate(TmpFlt);  // FLD0
716       TmpFlt.changeSign();
717       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
718
719       bool ignored;
720       APFloat TmpFlt2(+1.0);
721       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
722                       &ignored);
723       addLegalFPImmediate(TmpFlt2);  // FLD1
724       TmpFlt2.changeSign();
725       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
726     }
727
728     if (!TM.Options.UnsafeFPMath) {
729       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
730       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
731       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
732     }
733
734     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
735     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
736     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
737     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
738     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
739     setOperationAction(ISD::FMA, MVT::f80, Expand);
740   }
741
742   // Always use a library call for pow.
743   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
744   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
745   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
746
747   setOperationAction(ISD::FLOG, MVT::f80, Expand);
748   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
749   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
750   setOperationAction(ISD::FEXP, MVT::f80, Expand);
751   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
752
753   // First set operation action for all vector types to either promote
754   // (for widening) or expand (for scalarization). Then we will selectively
755   // turn on ones that can be effectively codegen'd.
756   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
757            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
758     MVT VT = (MVT::SimpleValueType)i;
759     setOperationAction(ISD::ADD , VT, Expand);
760     setOperationAction(ISD::SUB , VT, Expand);
761     setOperationAction(ISD::FADD, VT, Expand);
762     setOperationAction(ISD::FNEG, VT, Expand);
763     setOperationAction(ISD::FSUB, VT, Expand);
764     setOperationAction(ISD::MUL , VT, Expand);
765     setOperationAction(ISD::FMUL, VT, Expand);
766     setOperationAction(ISD::SDIV, VT, Expand);
767     setOperationAction(ISD::UDIV, VT, Expand);
768     setOperationAction(ISD::FDIV, VT, Expand);
769     setOperationAction(ISD::SREM, VT, Expand);
770     setOperationAction(ISD::UREM, VT, Expand);
771     setOperationAction(ISD::LOAD, VT, Expand);
772     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
773     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
774     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
775     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
776     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
777     setOperationAction(ISD::FABS, VT, Expand);
778     setOperationAction(ISD::FSIN, VT, Expand);
779     setOperationAction(ISD::FSINCOS, VT, Expand);
780     setOperationAction(ISD::FCOS, VT, Expand);
781     setOperationAction(ISD::FSINCOS, VT, Expand);
782     setOperationAction(ISD::FREM, VT, Expand);
783     setOperationAction(ISD::FMA,  VT, Expand);
784     setOperationAction(ISD::FPOWI, VT, Expand);
785     setOperationAction(ISD::FSQRT, VT, Expand);
786     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
787     setOperationAction(ISD::FFLOOR, VT, Expand);
788     setOperationAction(ISD::FCEIL, VT, Expand);
789     setOperationAction(ISD::FTRUNC, VT, Expand);
790     setOperationAction(ISD::FRINT, VT, Expand);
791     setOperationAction(ISD::FNEARBYINT, VT, Expand);
792     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
793     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
794     setOperationAction(ISD::SDIVREM, VT, Expand);
795     setOperationAction(ISD::UDIVREM, VT, Expand);
796     setOperationAction(ISD::FPOW, VT, Expand);
797     setOperationAction(ISD::CTPOP, VT, Expand);
798     setOperationAction(ISD::CTTZ, VT, Expand);
799     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
800     setOperationAction(ISD::CTLZ, VT, Expand);
801     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
802     setOperationAction(ISD::SHL, VT, Expand);
803     setOperationAction(ISD::SRA, VT, Expand);
804     setOperationAction(ISD::SRL, VT, Expand);
805     setOperationAction(ISD::ROTL, VT, Expand);
806     setOperationAction(ISD::ROTR, VT, Expand);
807     setOperationAction(ISD::BSWAP, VT, Expand);
808     setOperationAction(ISD::SETCC, VT, Expand);
809     setOperationAction(ISD::FLOG, VT, Expand);
810     setOperationAction(ISD::FLOG2, VT, Expand);
811     setOperationAction(ISD::FLOG10, VT, Expand);
812     setOperationAction(ISD::FEXP, VT, Expand);
813     setOperationAction(ISD::FEXP2, VT, Expand);
814     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
815     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
816     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
817     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
818     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
819     setOperationAction(ISD::TRUNCATE, VT, Expand);
820     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
821     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
822     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
823     setOperationAction(ISD::VSELECT, VT, Expand);
824     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
825              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
826       setTruncStoreAction(VT,
827                           (MVT::SimpleValueType)InnerVT, Expand);
828     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
829     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
830     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
831   }
832
833   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
834   // with -msoft-float, disable use of MMX as well.
835   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
836     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
837     // No operations on x86mmx supported, everything uses intrinsics.
838   }
839
840   // MMX-sized vectors (other than x86mmx) are expected to be expanded
841   // into smaller operations.
842   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
843   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
844   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
845   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
846   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
847   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
848   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
849   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
850   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
851   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
852   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
853   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
854   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
855   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
856   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
857   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
858   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
859   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
860   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
861   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
862   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
863   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
864   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
865   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
866   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
867   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
868   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
869   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
870   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
871
872   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
873     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
874
875     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
876     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
877     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
878     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
879     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
880     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
881     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
882     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
883     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
884     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
885     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
886     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
887   }
888
889   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
890     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
891
892     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
893     // registers cannot be used even for integer operations.
894     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
895     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
896     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
897     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
898
899     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
900     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
901     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
902     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
903     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
904     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
905     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
906     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
907     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
908     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
909     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
910     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
911     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
912     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
913     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
914     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
915     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
916     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
917
918     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
919     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
920     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
921     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
922
923     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
924     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
925     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
926     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
927     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
928
929     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
930     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
931       MVT VT = (MVT::SimpleValueType)i;
932       // Do not attempt to custom lower non-power-of-2 vectors
933       if (!isPowerOf2_32(VT.getVectorNumElements()))
934         continue;
935       // Do not attempt to custom lower non-128-bit vectors
936       if (!VT.is128BitVector())
937         continue;
938       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
939       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
940       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
941     }
942
943     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
944     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
945     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
946     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
947     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
948     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
949
950     if (Subtarget->is64Bit()) {
951       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
952       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
953     }
954
955     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
956     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
957       MVT VT = (MVT::SimpleValueType)i;
958
959       // Do not attempt to promote non-128-bit vectors
960       if (!VT.is128BitVector())
961         continue;
962
963       setOperationAction(ISD::AND,    VT, Promote);
964       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
965       setOperationAction(ISD::OR,     VT, Promote);
966       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
967       setOperationAction(ISD::XOR,    VT, Promote);
968       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
969       setOperationAction(ISD::LOAD,   VT, Promote);
970       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
971       setOperationAction(ISD::SELECT, VT, Promote);
972       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
973     }
974
975     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
976
977     // Custom lower v2i64 and v2f64 selects.
978     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
979     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
980     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
981     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
982
983     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
984     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
985
986     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
987     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
988     // As there is no 64-bit GPR available, we need build a special custom
989     // sequence to convert from v2i32 to v2f32.
990     if (!Subtarget->is64Bit())
991       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
992
993     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
994     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
995
996     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
997   }
998
999   if (Subtarget->hasSSE41()) {
1000     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1001     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1002     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1003     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1004     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1005     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1006     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1007     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1008     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1009     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1010
1011     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1012     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1013     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1014     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1015     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1016     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1017     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1018     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1019     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1020     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1021
1022     // FIXME: Do we need to handle scalar-to-vector here?
1023     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1024
1025     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1026     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1027     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1028     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1029     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1030
1031     // i8 and i16 vectors are custom , because the source register and source
1032     // source memory operand types are not the same width.  f32 vectors are
1033     // custom since the immediate controlling the insert encodes additional
1034     // information.
1035     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1036     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1037     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1038     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1039
1040     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1041     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1042     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1043     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1044
1045     // FIXME: these should be Legal but thats only for the case where
1046     // the index is constant.  For now custom expand to deal with that.
1047     if (Subtarget->is64Bit()) {
1048       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1049       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1050     }
1051   }
1052
1053   if (Subtarget->hasSSE2()) {
1054     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1055     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1056
1057     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1058     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1059
1060     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1061     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1062
1063     // In the customized shift lowering, the legal cases in AVX2 will be
1064     // recognized.
1065     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1066     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1067
1068     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1069     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1070
1071     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1072
1073     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1074     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1075   }
1076
1077   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1078     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1079     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1080     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1081     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1082     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1083     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1084
1085     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1086     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1087     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1088
1089     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1090     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1091     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1092     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1093     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1094     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1095     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1096     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1097     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1098     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1099     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1100     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1101
1102     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1103     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1104     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1105     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1106     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1107     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1108     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1109     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1110     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1111     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1112     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1113     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1114
1115     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1116     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1117
1118     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1119
1120     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1121     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1122     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1123     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1124
1125     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1126     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1127     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1128
1129     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1130
1131     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1132     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1133
1134     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1135     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1136
1137     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1138     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1139
1140     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1141
1142     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1143     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1144     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1145     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1146
1147     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1148     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1149     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1150
1151     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1152     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1153     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1154     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1155
1156     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1157     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1158     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1159     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1160     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1161     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1162
1163     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1164       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1165       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1166       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1167       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1168       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1169       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1170     }
1171
1172     if (Subtarget->hasInt256()) {
1173       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1174       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1175       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1176       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1177
1178       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1179       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1180       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1181       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1182
1183       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1184       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1185       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1186       // Don't lower v32i8 because there is no 128-bit byte mul
1187
1188       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1189
1190       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1191     } else {
1192       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1193       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1195       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1196
1197       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1198       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1200       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1201
1202       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1203       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1205       // Don't lower v32i8 because there is no 128-bit byte mul
1206     }
1207
1208     // In the customized shift lowering, the legal cases in AVX2 will be
1209     // recognized.
1210     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1211     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1212
1213     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1214     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1215
1216     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1217
1218     // Custom lower several nodes for 256-bit types.
1219     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1220              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1221       MVT VT = (MVT::SimpleValueType)i;
1222
1223       // Extract subvector is special because the value type
1224       // (result) is 128-bit but the source is 256-bit wide.
1225       if (VT.is128BitVector())
1226         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1227
1228       // Do not attempt to custom lower other non-256-bit vectors
1229       if (!VT.is256BitVector())
1230         continue;
1231
1232       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1233       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1234       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1235       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1236       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1237       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1238       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1239     }
1240
1241     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1242     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1243       MVT VT = (MVT::SimpleValueType)i;
1244
1245       // Do not attempt to promote non-256-bit vectors
1246       if (!VT.is256BitVector())
1247         continue;
1248
1249       setOperationAction(ISD::AND,    VT, Promote);
1250       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1251       setOperationAction(ISD::OR,     VT, Promote);
1252       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1253       setOperationAction(ISD::XOR,    VT, Promote);
1254       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1255       setOperationAction(ISD::LOAD,   VT, Promote);
1256       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1257       setOperationAction(ISD::SELECT, VT, Promote);
1258       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1259     }
1260   }
1261
1262   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1263   // of this type with custom code.
1264   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1265            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1266     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1267                        Custom);
1268   }
1269
1270   // We want to custom lower some of our intrinsics.
1271   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1272   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1273
1274   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1275   // handle type legalization for these operations here.
1276   //
1277   // FIXME: We really should do custom legalization for addition and
1278   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1279   // than generic legalization for 64-bit multiplication-with-overflow, though.
1280   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1281     // Add/Sub/Mul with overflow operations are custom lowered.
1282     MVT VT = IntVTs[i];
1283     setOperationAction(ISD::SADDO, VT, Custom);
1284     setOperationAction(ISD::UADDO, VT, Custom);
1285     setOperationAction(ISD::SSUBO, VT, Custom);
1286     setOperationAction(ISD::USUBO, VT, Custom);
1287     setOperationAction(ISD::SMULO, VT, Custom);
1288     setOperationAction(ISD::UMULO, VT, Custom);
1289   }
1290
1291   // There are no 8-bit 3-address imul/mul instructions
1292   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1293   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1294
1295   if (!Subtarget->is64Bit()) {
1296     // These libcalls are not available in 32-bit.
1297     setLibcallName(RTLIB::SHL_I128, 0);
1298     setLibcallName(RTLIB::SRL_I128, 0);
1299     setLibcallName(RTLIB::SRA_I128, 0);
1300   }
1301
1302   // Combine sin / cos into one node or libcall if possible.
1303   if (Subtarget->hasSinCos()) {
1304     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1305     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1306     if (Subtarget->isTargetDarwin()) {
1307       // For MacOSX, we don't want to the normal expansion of a libcall to
1308       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1309       // traffic.
1310       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1311       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1312     }
1313   }
1314
1315   // We have target-specific dag combine patterns for the following nodes:
1316   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1317   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1318   setTargetDAGCombine(ISD::VSELECT);
1319   setTargetDAGCombine(ISD::SELECT);
1320   setTargetDAGCombine(ISD::SHL);
1321   setTargetDAGCombine(ISD::SRA);
1322   setTargetDAGCombine(ISD::SRL);
1323   setTargetDAGCombine(ISD::OR);
1324   setTargetDAGCombine(ISD::AND);
1325   setTargetDAGCombine(ISD::ADD);
1326   setTargetDAGCombine(ISD::FADD);
1327   setTargetDAGCombine(ISD::FSUB);
1328   setTargetDAGCombine(ISD::FMA);
1329   setTargetDAGCombine(ISD::SUB);
1330   setTargetDAGCombine(ISD::LOAD);
1331   setTargetDAGCombine(ISD::STORE);
1332   setTargetDAGCombine(ISD::ZERO_EXTEND);
1333   setTargetDAGCombine(ISD::ANY_EXTEND);
1334   setTargetDAGCombine(ISD::SIGN_EXTEND);
1335   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1336   setTargetDAGCombine(ISD::TRUNCATE);
1337   setTargetDAGCombine(ISD::SINT_TO_FP);
1338   setTargetDAGCombine(ISD::SETCC);
1339   if (Subtarget->is64Bit())
1340     setTargetDAGCombine(ISD::MUL);
1341   setTargetDAGCombine(ISD::XOR);
1342
1343   computeRegisterProperties();
1344
1345   // On Darwin, -Os means optimize for size without hurting performance,
1346   // do not reduce the limit.
1347   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1348   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1349   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1350   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1351   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1352   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1353   setPrefLoopAlignment(4); // 2^4 bytes.
1354
1355   // Predictable cmov don't hurt on atom because it's in-order.
1356   PredictableSelectIsExpensive = !Subtarget->isAtom();
1357
1358   setPrefFunctionAlignment(4); // 2^4 bytes.
1359 }
1360
1361 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1362   if (!VT.isVector()) return MVT::i8;
1363   return VT.changeVectorElementTypeToInteger();
1364 }
1365
1366 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1367 /// the desired ByVal argument alignment.
1368 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1369   if (MaxAlign == 16)
1370     return;
1371   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1372     if (VTy->getBitWidth() == 128)
1373       MaxAlign = 16;
1374   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1375     unsigned EltAlign = 0;
1376     getMaxByValAlign(ATy->getElementType(), EltAlign);
1377     if (EltAlign > MaxAlign)
1378       MaxAlign = EltAlign;
1379   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1380     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1381       unsigned EltAlign = 0;
1382       getMaxByValAlign(STy->getElementType(i), EltAlign);
1383       if (EltAlign > MaxAlign)
1384         MaxAlign = EltAlign;
1385       if (MaxAlign == 16)
1386         break;
1387     }
1388   }
1389 }
1390
1391 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1392 /// function arguments in the caller parameter area. For X86, aggregates
1393 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1394 /// are at 4-byte boundaries.
1395 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1396   if (Subtarget->is64Bit()) {
1397     // Max of 8 and alignment of type.
1398     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1399     if (TyAlign > 8)
1400       return TyAlign;
1401     return 8;
1402   }
1403
1404   unsigned Align = 4;
1405   if (Subtarget->hasSSE1())
1406     getMaxByValAlign(Ty, Align);
1407   return Align;
1408 }
1409
1410 /// getOptimalMemOpType - Returns the target specific optimal type for load
1411 /// and store operations as a result of memset, memcpy, and memmove
1412 /// lowering. If DstAlign is zero that means it's safe to destination
1413 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1414 /// means there isn't a need to check it against alignment requirement,
1415 /// probably because the source does not need to be loaded. If 'IsMemset' is
1416 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1417 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1418 /// source is constant so it does not need to be loaded.
1419 /// It returns EVT::Other if the type should be determined using generic
1420 /// target-independent logic.
1421 EVT
1422 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1423                                        unsigned DstAlign, unsigned SrcAlign,
1424                                        bool IsMemset, bool ZeroMemset,
1425                                        bool MemcpyStrSrc,
1426                                        MachineFunction &MF) const {
1427   const Function *F = MF.getFunction();
1428   if ((!IsMemset || ZeroMemset) &&
1429       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1430                                        Attribute::NoImplicitFloat)) {
1431     if (Size >= 16 &&
1432         (Subtarget->isUnalignedMemAccessFast() ||
1433          ((DstAlign == 0 || DstAlign >= 16) &&
1434           (SrcAlign == 0 || SrcAlign >= 16)))) {
1435       if (Size >= 32) {
1436         if (Subtarget->hasInt256())
1437           return MVT::v8i32;
1438         if (Subtarget->hasFp256())
1439           return MVT::v8f32;
1440       }
1441       if (Subtarget->hasSSE2())
1442         return MVT::v4i32;
1443       if (Subtarget->hasSSE1())
1444         return MVT::v4f32;
1445     } else if (!MemcpyStrSrc && Size >= 8 &&
1446                !Subtarget->is64Bit() &&
1447                Subtarget->hasSSE2()) {
1448       // Do not use f64 to lower memcpy if source is string constant. It's
1449       // better to use i32 to avoid the loads.
1450       return MVT::f64;
1451     }
1452   }
1453   if (Subtarget->is64Bit() && Size >= 8)
1454     return MVT::i64;
1455   return MVT::i32;
1456 }
1457
1458 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1459   if (VT == MVT::f32)
1460     return X86ScalarSSEf32;
1461   else if (VT == MVT::f64)
1462     return X86ScalarSSEf64;
1463   return true;
1464 }
1465
1466 bool
1467 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1468   if (Fast)
1469     *Fast = Subtarget->isUnalignedMemAccessFast();
1470   return true;
1471 }
1472
1473 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1474 /// current function.  The returned value is a member of the
1475 /// MachineJumpTableInfo::JTEntryKind enum.
1476 unsigned X86TargetLowering::getJumpTableEncoding() const {
1477   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1478   // symbol.
1479   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1480       Subtarget->isPICStyleGOT())
1481     return MachineJumpTableInfo::EK_Custom32;
1482
1483   // Otherwise, use the normal jump table encoding heuristics.
1484   return TargetLowering::getJumpTableEncoding();
1485 }
1486
1487 const MCExpr *
1488 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1489                                              const MachineBasicBlock *MBB,
1490                                              unsigned uid,MCContext &Ctx) const{
1491   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1492          Subtarget->isPICStyleGOT());
1493   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1494   // entries.
1495   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1496                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1497 }
1498
1499 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1500 /// jumptable.
1501 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1502                                                     SelectionDAG &DAG) const {
1503   if (!Subtarget->is64Bit())
1504     // This doesn't have SDLoc associated with it, but is not really the
1505     // same as a Register.
1506     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1507   return Table;
1508 }
1509
1510 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1511 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1512 /// MCExpr.
1513 const MCExpr *X86TargetLowering::
1514 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1515                              MCContext &Ctx) const {
1516   // X86-64 uses RIP relative addressing based on the jump table label.
1517   if (Subtarget->isPICStyleRIPRel())
1518     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1519
1520   // Otherwise, the reference is relative to the PIC base.
1521   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1522 }
1523
1524 // FIXME: Why this routine is here? Move to RegInfo!
1525 std::pair<const TargetRegisterClass*, uint8_t>
1526 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1527   const TargetRegisterClass *RRC = 0;
1528   uint8_t Cost = 1;
1529   switch (VT.SimpleTy) {
1530   default:
1531     return TargetLowering::findRepresentativeClass(VT);
1532   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1533     RRC = Subtarget->is64Bit() ?
1534       (const TargetRegisterClass*)&X86::GR64RegClass :
1535       (const TargetRegisterClass*)&X86::GR32RegClass;
1536     break;
1537   case MVT::x86mmx:
1538     RRC = &X86::VR64RegClass;
1539     break;
1540   case MVT::f32: case MVT::f64:
1541   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1542   case MVT::v4f32: case MVT::v2f64:
1543   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1544   case MVT::v4f64:
1545     RRC = &X86::VR128RegClass;
1546     break;
1547   }
1548   return std::make_pair(RRC, Cost);
1549 }
1550
1551 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1552                                                unsigned &Offset) const {
1553   if (!Subtarget->isTargetLinux())
1554     return false;
1555
1556   if (Subtarget->is64Bit()) {
1557     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1558     Offset = 0x28;
1559     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1560       AddressSpace = 256;
1561     else
1562       AddressSpace = 257;
1563   } else {
1564     // %gs:0x14 on i386
1565     Offset = 0x14;
1566     AddressSpace = 256;
1567   }
1568   return true;
1569 }
1570
1571 //===----------------------------------------------------------------------===//
1572 //               Return Value Calling Convention Implementation
1573 //===----------------------------------------------------------------------===//
1574
1575 #include "X86GenCallingConv.inc"
1576
1577 bool
1578 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1579                                   MachineFunction &MF, bool isVarArg,
1580                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1581                         LLVMContext &Context) const {
1582   SmallVector<CCValAssign, 16> RVLocs;
1583   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1584                  RVLocs, Context);
1585   return CCInfo.CheckReturn(Outs, RetCC_X86);
1586 }
1587
1588 SDValue
1589 X86TargetLowering::LowerReturn(SDValue Chain,
1590                                CallingConv::ID CallConv, bool isVarArg,
1591                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1592                                const SmallVectorImpl<SDValue> &OutVals,
1593                                SDLoc dl, SelectionDAG &DAG) const {
1594   MachineFunction &MF = DAG.getMachineFunction();
1595   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1596
1597   SmallVector<CCValAssign, 16> RVLocs;
1598   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1599                  RVLocs, *DAG.getContext());
1600   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1601
1602   SDValue Flag;
1603   SmallVector<SDValue, 6> RetOps;
1604   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1605   // Operand #1 = Bytes To Pop
1606   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1607                    MVT::i16));
1608
1609   // Copy the result values into the output registers.
1610   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1611     CCValAssign &VA = RVLocs[i];
1612     assert(VA.isRegLoc() && "Can only return in registers!");
1613     SDValue ValToCopy = OutVals[i];
1614     EVT ValVT = ValToCopy.getValueType();
1615
1616     // Promote values to the appropriate types
1617     if (VA.getLocInfo() == CCValAssign::SExt)
1618       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1619     else if (VA.getLocInfo() == CCValAssign::ZExt)
1620       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1621     else if (VA.getLocInfo() == CCValAssign::AExt)
1622       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1623     else if (VA.getLocInfo() == CCValAssign::BCvt)
1624       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1625
1626     // If this is x86-64, and we disabled SSE, we can't return FP values,
1627     // or SSE or MMX vectors.
1628     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1629          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1630           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1631       report_fatal_error("SSE register return with SSE disabled");
1632     }
1633     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1634     // llvm-gcc has never done it right and no one has noticed, so this
1635     // should be OK for now.
1636     if (ValVT == MVT::f64 &&
1637         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1638       report_fatal_error("SSE2 register return with SSE2 disabled");
1639
1640     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1641     // the RET instruction and handled by the FP Stackifier.
1642     if (VA.getLocReg() == X86::ST0 ||
1643         VA.getLocReg() == X86::ST1) {
1644       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1645       // change the value to the FP stack register class.
1646       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1647         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1648       RetOps.push_back(ValToCopy);
1649       // Don't emit a copytoreg.
1650       continue;
1651     }
1652
1653     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1654     // which is returned in RAX / RDX.
1655     if (Subtarget->is64Bit()) {
1656       if (ValVT == MVT::x86mmx) {
1657         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1658           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1659           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1660                                   ValToCopy);
1661           // If we don't have SSE2 available, convert to v4f32 so the generated
1662           // register is legal.
1663           if (!Subtarget->hasSSE2())
1664             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1665         }
1666       }
1667     }
1668
1669     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1670     Flag = Chain.getValue(1);
1671     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1672   }
1673
1674   // The x86-64 ABIs require that for returning structs by value we copy
1675   // the sret argument into %rax/%eax (depending on ABI) for the return.
1676   // Win32 requires us to put the sret argument to %eax as well.
1677   // We saved the argument into a virtual register in the entry block,
1678   // so now we copy the value out and into %rax/%eax.
1679   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1680       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1681     MachineFunction &MF = DAG.getMachineFunction();
1682     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1683     unsigned Reg = FuncInfo->getSRetReturnReg();
1684     assert(Reg &&
1685            "SRetReturnReg should have been set in LowerFormalArguments().");
1686     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1687
1688     unsigned RetValReg
1689         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1690           X86::RAX : X86::EAX;
1691     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1692     Flag = Chain.getValue(1);
1693
1694     // RAX/EAX now acts like a return value.
1695     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1696   }
1697
1698   RetOps[0] = Chain;  // Update chain.
1699
1700   // Add the flag if we have it.
1701   if (Flag.getNode())
1702     RetOps.push_back(Flag);
1703
1704   return DAG.getNode(X86ISD::RET_FLAG, dl,
1705                      MVT::Other, &RetOps[0], RetOps.size());
1706 }
1707
1708 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1709   if (N->getNumValues() != 1)
1710     return false;
1711   if (!N->hasNUsesOfValue(1, 0))
1712     return false;
1713
1714   SDValue TCChain = Chain;
1715   SDNode *Copy = *N->use_begin();
1716   if (Copy->getOpcode() == ISD::CopyToReg) {
1717     // If the copy has a glue operand, we conservatively assume it isn't safe to
1718     // perform a tail call.
1719     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1720       return false;
1721     TCChain = Copy->getOperand(0);
1722   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1723     return false;
1724
1725   bool HasRet = false;
1726   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1727        UI != UE; ++UI) {
1728     if (UI->getOpcode() != X86ISD::RET_FLAG)
1729       return false;
1730     HasRet = true;
1731   }
1732
1733   if (!HasRet)
1734     return false;
1735
1736   Chain = TCChain;
1737   return true;
1738 }
1739
1740 MVT
1741 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1742                                             ISD::NodeType ExtendKind) const {
1743   MVT ReturnMVT;
1744   // TODO: Is this also valid on 32-bit?
1745   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1746     ReturnMVT = MVT::i8;
1747   else
1748     ReturnMVT = MVT::i32;
1749
1750   MVT MinVT = getRegisterType(ReturnMVT);
1751   return VT.bitsLT(MinVT) ? MinVT : VT;
1752 }
1753
1754 /// LowerCallResult - Lower the result values of a call into the
1755 /// appropriate copies out of appropriate physical registers.
1756 ///
1757 SDValue
1758 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1759                                    CallingConv::ID CallConv, bool isVarArg,
1760                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1761                                    SDLoc dl, SelectionDAG &DAG,
1762                                    SmallVectorImpl<SDValue> &InVals) const {
1763
1764   // Assign locations to each value returned by this call.
1765   SmallVector<CCValAssign, 16> RVLocs;
1766   bool Is64Bit = Subtarget->is64Bit();
1767   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1768                  getTargetMachine(), RVLocs, *DAG.getContext());
1769   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1770
1771   // Copy all of the result registers out of their specified physreg.
1772   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1773     CCValAssign &VA = RVLocs[i];
1774     EVT CopyVT = VA.getValVT();
1775
1776     // If this is x86-64, and we disabled SSE, we can't return FP values
1777     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1778         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1779       report_fatal_error("SSE register return with SSE disabled");
1780     }
1781
1782     SDValue Val;
1783
1784     // If this is a call to a function that returns an fp value on the floating
1785     // point stack, we must guarantee the value is popped from the stack, so
1786     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1787     // if the return value is not used. We use the FpPOP_RETVAL instruction
1788     // instead.
1789     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1790       // If we prefer to use the value in xmm registers, copy it out as f80 and
1791       // use a truncate to move it from fp stack reg to xmm reg.
1792       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1793       SDValue Ops[] = { Chain, InFlag };
1794       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1795                                          MVT::Other, MVT::Glue, Ops), 1);
1796       Val = Chain.getValue(0);
1797
1798       // Round the f80 to the right size, which also moves it to the appropriate
1799       // xmm register.
1800       if (CopyVT != VA.getValVT())
1801         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1802                           // This truncation won't change the value.
1803                           DAG.getIntPtrConstant(1));
1804     } else {
1805       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1806                                  CopyVT, InFlag).getValue(1);
1807       Val = Chain.getValue(0);
1808     }
1809     InFlag = Chain.getValue(2);
1810     InVals.push_back(Val);
1811   }
1812
1813   return Chain;
1814 }
1815
1816 //===----------------------------------------------------------------------===//
1817 //                C & StdCall & Fast Calling Convention implementation
1818 //===----------------------------------------------------------------------===//
1819 //  StdCall calling convention seems to be standard for many Windows' API
1820 //  routines and around. It differs from C calling convention just a little:
1821 //  callee should clean up the stack, not caller. Symbols should be also
1822 //  decorated in some fancy way :) It doesn't support any vector arguments.
1823 //  For info on fast calling convention see Fast Calling Convention (tail call)
1824 //  implementation LowerX86_32FastCCCallTo.
1825
1826 /// CallIsStructReturn - Determines whether a call uses struct return
1827 /// semantics.
1828 enum StructReturnType {
1829   NotStructReturn,
1830   RegStructReturn,
1831   StackStructReturn
1832 };
1833 static StructReturnType
1834 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1835   if (Outs.empty())
1836     return NotStructReturn;
1837
1838   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1839   if (!Flags.isSRet())
1840     return NotStructReturn;
1841   if (Flags.isInReg())
1842     return RegStructReturn;
1843   return StackStructReturn;
1844 }
1845
1846 /// ArgsAreStructReturn - Determines whether a function uses struct
1847 /// return semantics.
1848 static StructReturnType
1849 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1850   if (Ins.empty())
1851     return NotStructReturn;
1852
1853   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1854   if (!Flags.isSRet())
1855     return NotStructReturn;
1856   if (Flags.isInReg())
1857     return RegStructReturn;
1858   return StackStructReturn;
1859 }
1860
1861 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1862 /// by "Src" to address "Dst" with size and alignment information specified by
1863 /// the specific parameter attribute. The copy will be passed as a byval
1864 /// function parameter.
1865 static SDValue
1866 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1867                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1868                           SDLoc dl) {
1869   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1870
1871   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1872                        /*isVolatile*/false, /*AlwaysInline=*/true,
1873                        MachinePointerInfo(), MachinePointerInfo());
1874 }
1875
1876 /// IsTailCallConvention - Return true if the calling convention is one that
1877 /// supports tail call optimization.
1878 static bool IsTailCallConvention(CallingConv::ID CC) {
1879   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1880           CC == CallingConv::HiPE);
1881 }
1882
1883 /// \brief Return true if the calling convention is a C calling convention.
1884 static bool IsCCallConvention(CallingConv::ID CC) {
1885   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
1886           CC == CallingConv::X86_64_SysV);
1887 }
1888
1889 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1890   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1891     return false;
1892
1893   CallSite CS(CI);
1894   CallingConv::ID CalleeCC = CS.getCallingConv();
1895   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
1896     return false;
1897
1898   return true;
1899 }
1900
1901 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1902 /// a tailcall target by changing its ABI.
1903 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1904                                    bool GuaranteedTailCallOpt) {
1905   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1906 }
1907
1908 SDValue
1909 X86TargetLowering::LowerMemArgument(SDValue Chain,
1910                                     CallingConv::ID CallConv,
1911                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1912                                     SDLoc dl, SelectionDAG &DAG,
1913                                     const CCValAssign &VA,
1914                                     MachineFrameInfo *MFI,
1915                                     unsigned i) const {
1916   // Create the nodes corresponding to a load from this parameter slot.
1917   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1918   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1919                               getTargetMachine().Options.GuaranteedTailCallOpt);
1920   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1921   EVT ValVT;
1922
1923   // If value is passed by pointer we have address passed instead of the value
1924   // itself.
1925   if (VA.getLocInfo() == CCValAssign::Indirect)
1926     ValVT = VA.getLocVT();
1927   else
1928     ValVT = VA.getValVT();
1929
1930   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1931   // changed with more analysis.
1932   // In case of tail call optimization mark all arguments mutable. Since they
1933   // could be overwritten by lowering of arguments in case of a tail call.
1934   if (Flags.isByVal()) {
1935     unsigned Bytes = Flags.getByValSize();
1936     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1937     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1938     return DAG.getFrameIndex(FI, getPointerTy());
1939   } else {
1940     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1941                                     VA.getLocMemOffset(), isImmutable);
1942     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1943     return DAG.getLoad(ValVT, dl, Chain, FIN,
1944                        MachinePointerInfo::getFixedStack(FI),
1945                        false, false, false, 0);
1946   }
1947 }
1948
1949 SDValue
1950 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1951                                         CallingConv::ID CallConv,
1952                                         bool isVarArg,
1953                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1954                                         SDLoc dl,
1955                                         SelectionDAG &DAG,
1956                                         SmallVectorImpl<SDValue> &InVals)
1957                                           const {
1958   MachineFunction &MF = DAG.getMachineFunction();
1959   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1960
1961   const Function* Fn = MF.getFunction();
1962   if (Fn->hasExternalLinkage() &&
1963       Subtarget->isTargetCygMing() &&
1964       Fn->getName() == "main")
1965     FuncInfo->setForceFramePointer(true);
1966
1967   MachineFrameInfo *MFI = MF.getFrameInfo();
1968   bool Is64Bit = Subtarget->is64Bit();
1969   bool IsWindows = Subtarget->isTargetWindows();
1970   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
1971
1972   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1973          "Var args not supported with calling convention fastcc, ghc or hipe");
1974
1975   // Assign locations to all of the incoming arguments.
1976   SmallVector<CCValAssign, 16> ArgLocs;
1977   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1978                  ArgLocs, *DAG.getContext());
1979
1980   // Allocate shadow area for Win64
1981   if (IsWin64)
1982     CCInfo.AllocateStack(32, 8);
1983
1984   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1985
1986   unsigned LastVal = ~0U;
1987   SDValue ArgValue;
1988   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1989     CCValAssign &VA = ArgLocs[i];
1990     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1991     // places.
1992     assert(VA.getValNo() != LastVal &&
1993            "Don't support value assigned to multiple locs yet");
1994     (void)LastVal;
1995     LastVal = VA.getValNo();
1996
1997     if (VA.isRegLoc()) {
1998       EVT RegVT = VA.getLocVT();
1999       const TargetRegisterClass *RC;
2000       if (RegVT == MVT::i32)
2001         RC = &X86::GR32RegClass;
2002       else if (Is64Bit && RegVT == MVT::i64)
2003         RC = &X86::GR64RegClass;
2004       else if (RegVT == MVT::f32)
2005         RC = &X86::FR32RegClass;
2006       else if (RegVT == MVT::f64)
2007         RC = &X86::FR64RegClass;
2008       else if (RegVT.is256BitVector())
2009         RC = &X86::VR256RegClass;
2010       else if (RegVT.is128BitVector())
2011         RC = &X86::VR128RegClass;
2012       else if (RegVT == MVT::x86mmx)
2013         RC = &X86::VR64RegClass;
2014       else
2015         llvm_unreachable("Unknown argument type!");
2016
2017       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2018       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2019
2020       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2021       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2022       // right size.
2023       if (VA.getLocInfo() == CCValAssign::SExt)
2024         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2025                                DAG.getValueType(VA.getValVT()));
2026       else if (VA.getLocInfo() == CCValAssign::ZExt)
2027         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2028                                DAG.getValueType(VA.getValVT()));
2029       else if (VA.getLocInfo() == CCValAssign::BCvt)
2030         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2031
2032       if (VA.isExtInLoc()) {
2033         // Handle MMX values passed in XMM regs.
2034         if (RegVT.isVector())
2035           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2036         else
2037           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2038       }
2039     } else {
2040       assert(VA.isMemLoc());
2041       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2042     }
2043
2044     // If value is passed via pointer - do a load.
2045     if (VA.getLocInfo() == CCValAssign::Indirect)
2046       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2047                              MachinePointerInfo(), false, false, false, 0);
2048
2049     InVals.push_back(ArgValue);
2050   }
2051
2052   // The x86-64 ABIs require that for returning structs by value we copy
2053   // the sret argument into %rax/%eax (depending on ABI) for the return.
2054   // Win32 requires us to put the sret argument to %eax as well.
2055   // Save the argument into a virtual register so that we can access it
2056   // from the return points.
2057   if (MF.getFunction()->hasStructRetAttr() &&
2058       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2059     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2060     unsigned Reg = FuncInfo->getSRetReturnReg();
2061     if (!Reg) {
2062       MVT PtrTy = getPointerTy();
2063       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2064       FuncInfo->setSRetReturnReg(Reg);
2065     }
2066     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2067     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2068   }
2069
2070   unsigned StackSize = CCInfo.getNextStackOffset();
2071   // Align stack specially for tail calls.
2072   if (FuncIsMadeTailCallSafe(CallConv,
2073                              MF.getTarget().Options.GuaranteedTailCallOpt))
2074     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2075
2076   // If the function takes variable number of arguments, make a frame index for
2077   // the start of the first vararg value... for expansion of llvm.va_start.
2078   if (isVarArg) {
2079     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2080                     CallConv != CallingConv::X86_ThisCall)) {
2081       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2082     }
2083     if (Is64Bit) {
2084       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2085
2086       // FIXME: We should really autogenerate these arrays
2087       static const uint16_t GPR64ArgRegsWin64[] = {
2088         X86::RCX, X86::RDX, X86::R8,  X86::R9
2089       };
2090       static const uint16_t GPR64ArgRegs64Bit[] = {
2091         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2092       };
2093       static const uint16_t XMMArgRegs64Bit[] = {
2094         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2095         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2096       };
2097       const uint16_t *GPR64ArgRegs;
2098       unsigned NumXMMRegs = 0;
2099
2100       if (IsWin64) {
2101         // The XMM registers which might contain var arg parameters are shadowed
2102         // in their paired GPR.  So we only need to save the GPR to their home
2103         // slots.
2104         TotalNumIntRegs = 4;
2105         GPR64ArgRegs = GPR64ArgRegsWin64;
2106       } else {
2107         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2108         GPR64ArgRegs = GPR64ArgRegs64Bit;
2109
2110         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2111                                                 TotalNumXMMRegs);
2112       }
2113       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2114                                                        TotalNumIntRegs);
2115
2116       bool NoImplicitFloatOps = Fn->getAttributes().
2117         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2118       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2119              "SSE register cannot be used when SSE is disabled!");
2120       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2121                NoImplicitFloatOps) &&
2122              "SSE register cannot be used when SSE is disabled!");
2123       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2124           !Subtarget->hasSSE1())
2125         // Kernel mode asks for SSE to be disabled, so don't push them
2126         // on the stack.
2127         TotalNumXMMRegs = 0;
2128
2129       if (IsWin64) {
2130         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2131         // Get to the caller-allocated home save location.  Add 8 to account
2132         // for the return address.
2133         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2134         FuncInfo->setRegSaveFrameIndex(
2135           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2136         // Fixup to set vararg frame on shadow area (4 x i64).
2137         if (NumIntRegs < 4)
2138           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2139       } else {
2140         // For X86-64, if there are vararg parameters that are passed via
2141         // registers, then we must store them to their spots on the stack so
2142         // they may be loaded by deferencing the result of va_next.
2143         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2144         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2145         FuncInfo->setRegSaveFrameIndex(
2146           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2147                                false));
2148       }
2149
2150       // Store the integer parameter registers.
2151       SmallVector<SDValue, 8> MemOps;
2152       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2153                                         getPointerTy());
2154       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2155       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2156         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2157                                   DAG.getIntPtrConstant(Offset));
2158         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2159                                      &X86::GR64RegClass);
2160         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2161         SDValue Store =
2162           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2163                        MachinePointerInfo::getFixedStack(
2164                          FuncInfo->getRegSaveFrameIndex(), Offset),
2165                        false, false, 0);
2166         MemOps.push_back(Store);
2167         Offset += 8;
2168       }
2169
2170       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2171         // Now store the XMM (fp + vector) parameter registers.
2172         SmallVector<SDValue, 11> SaveXMMOps;
2173         SaveXMMOps.push_back(Chain);
2174
2175         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2176         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2177         SaveXMMOps.push_back(ALVal);
2178
2179         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2180                                FuncInfo->getRegSaveFrameIndex()));
2181         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2182                                FuncInfo->getVarArgsFPOffset()));
2183
2184         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2185           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2186                                        &X86::VR128RegClass);
2187           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2188           SaveXMMOps.push_back(Val);
2189         }
2190         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2191                                      MVT::Other,
2192                                      &SaveXMMOps[0], SaveXMMOps.size()));
2193       }
2194
2195       if (!MemOps.empty())
2196         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2197                             &MemOps[0], MemOps.size());
2198     }
2199   }
2200
2201   // Some CCs need callee pop.
2202   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2203                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2204     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2205   } else {
2206     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2207     // If this is an sret function, the return should pop the hidden pointer.
2208     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2209         argsAreStructReturn(Ins) == StackStructReturn)
2210       FuncInfo->setBytesToPopOnReturn(4);
2211   }
2212
2213   if (!Is64Bit) {
2214     // RegSaveFrameIndex is X86-64 only.
2215     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2216     if (CallConv == CallingConv::X86_FastCall ||
2217         CallConv == CallingConv::X86_ThisCall)
2218       // fastcc functions can't have varargs.
2219       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2220   }
2221
2222   FuncInfo->setArgumentStackSize(StackSize);
2223
2224   return Chain;
2225 }
2226
2227 SDValue
2228 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2229                                     SDValue StackPtr, SDValue Arg,
2230                                     SDLoc dl, SelectionDAG &DAG,
2231                                     const CCValAssign &VA,
2232                                     ISD::ArgFlagsTy Flags) const {
2233   unsigned LocMemOffset = VA.getLocMemOffset();
2234   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2235   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2236   if (Flags.isByVal())
2237     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2238
2239   return DAG.getStore(Chain, dl, Arg, PtrOff,
2240                       MachinePointerInfo::getStack(LocMemOffset),
2241                       false, false, 0);
2242 }
2243
2244 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2245 /// optimization is performed and it is required.
2246 SDValue
2247 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2248                                            SDValue &OutRetAddr, SDValue Chain,
2249                                            bool IsTailCall, bool Is64Bit,
2250                                            int FPDiff, SDLoc dl) const {
2251   // Adjust the Return address stack slot.
2252   EVT VT = getPointerTy();
2253   OutRetAddr = getReturnAddressFrameIndex(DAG);
2254
2255   // Load the "old" Return address.
2256   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2257                            false, false, false, 0);
2258   return SDValue(OutRetAddr.getNode(), 1);
2259 }
2260
2261 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2262 /// optimization is performed and it is required (FPDiff!=0).
2263 static SDValue
2264 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2265                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2266                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2267   // Store the return address to the appropriate stack slot.
2268   if (!FPDiff) return Chain;
2269   // Calculate the new stack slot for the return address.
2270   int NewReturnAddrFI =
2271     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2272   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2273   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2274                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2275                        false, false, 0);
2276   return Chain;
2277 }
2278
2279 SDValue
2280 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2281                              SmallVectorImpl<SDValue> &InVals) const {
2282   SelectionDAG &DAG                     = CLI.DAG;
2283   SDLoc &dl                             = CLI.DL;
2284   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2285   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2286   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2287   SDValue Chain                         = CLI.Chain;
2288   SDValue Callee                        = CLI.Callee;
2289   CallingConv::ID CallConv              = CLI.CallConv;
2290   bool &isTailCall                      = CLI.IsTailCall;
2291   bool isVarArg                         = CLI.IsVarArg;
2292
2293   MachineFunction &MF = DAG.getMachineFunction();
2294   bool Is64Bit        = Subtarget->is64Bit();
2295   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2296   bool IsWindows      = Subtarget->isTargetWindows();
2297   StructReturnType SR = callIsStructReturn(Outs);
2298   bool IsSibcall      = false;
2299
2300   if (MF.getTarget().Options.DisableTailCalls)
2301     isTailCall = false;
2302
2303   if (isTailCall) {
2304     // Check if it's really possible to do a tail call.
2305     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2306                     isVarArg, SR != NotStructReturn,
2307                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2308                     Outs, OutVals, Ins, DAG);
2309
2310     // Sibcalls are automatically detected tailcalls which do not require
2311     // ABI changes.
2312     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2313       IsSibcall = true;
2314
2315     if (isTailCall)
2316       ++NumTailCalls;
2317   }
2318
2319   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2320          "Var args not supported with calling convention fastcc, ghc or hipe");
2321
2322   // Analyze operands of the call, assigning locations to each operand.
2323   SmallVector<CCValAssign, 16> ArgLocs;
2324   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2325                  ArgLocs, *DAG.getContext());
2326
2327   // Allocate shadow area for Win64
2328   if (IsWin64)
2329     CCInfo.AllocateStack(32, 8);
2330
2331   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2332
2333   // Get a count of how many bytes are to be pushed on the stack.
2334   unsigned NumBytes = CCInfo.getNextStackOffset();
2335   if (IsSibcall)
2336     // This is a sibcall. The memory operands are available in caller's
2337     // own caller's stack.
2338     NumBytes = 0;
2339   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2340            IsTailCallConvention(CallConv))
2341     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2342
2343   int FPDiff = 0;
2344   if (isTailCall && !IsSibcall) {
2345     // Lower arguments at fp - stackoffset + fpdiff.
2346     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2347     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2348
2349     FPDiff = NumBytesCallerPushed - NumBytes;
2350
2351     // Set the delta of movement of the returnaddr stackslot.
2352     // But only set if delta is greater than previous delta.
2353     if (FPDiff < X86Info->getTCReturnAddrDelta())
2354       X86Info->setTCReturnAddrDelta(FPDiff);
2355   }
2356
2357   if (!IsSibcall)
2358     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2359                                  dl);
2360
2361   SDValue RetAddrFrIdx;
2362   // Load return address for tail calls.
2363   if (isTailCall && FPDiff)
2364     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2365                                     Is64Bit, FPDiff, dl);
2366
2367   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2368   SmallVector<SDValue, 8> MemOpChains;
2369   SDValue StackPtr;
2370
2371   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2372   // of tail call optimization arguments are handle later.
2373   const X86RegisterInfo *RegInfo =
2374     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2375   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2376     CCValAssign &VA = ArgLocs[i];
2377     EVT RegVT = VA.getLocVT();
2378     SDValue Arg = OutVals[i];
2379     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2380     bool isByVal = Flags.isByVal();
2381
2382     // Promote the value if needed.
2383     switch (VA.getLocInfo()) {
2384     default: llvm_unreachable("Unknown loc info!");
2385     case CCValAssign::Full: break;
2386     case CCValAssign::SExt:
2387       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2388       break;
2389     case CCValAssign::ZExt:
2390       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2391       break;
2392     case CCValAssign::AExt:
2393       if (RegVT.is128BitVector()) {
2394         // Special case: passing MMX values in XMM registers.
2395         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2396         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2397         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2398       } else
2399         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2400       break;
2401     case CCValAssign::BCvt:
2402       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2403       break;
2404     case CCValAssign::Indirect: {
2405       // Store the argument.
2406       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2407       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2408       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2409                            MachinePointerInfo::getFixedStack(FI),
2410                            false, false, 0);
2411       Arg = SpillSlot;
2412       break;
2413     }
2414     }
2415
2416     if (VA.isRegLoc()) {
2417       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2418       if (isVarArg && IsWin64) {
2419         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2420         // shadow reg if callee is a varargs function.
2421         unsigned ShadowReg = 0;
2422         switch (VA.getLocReg()) {
2423         case X86::XMM0: ShadowReg = X86::RCX; break;
2424         case X86::XMM1: ShadowReg = X86::RDX; break;
2425         case X86::XMM2: ShadowReg = X86::R8; break;
2426         case X86::XMM3: ShadowReg = X86::R9; break;
2427         }
2428         if (ShadowReg)
2429           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2430       }
2431     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2432       assert(VA.isMemLoc());
2433       if (StackPtr.getNode() == 0)
2434         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2435                                       getPointerTy());
2436       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2437                                              dl, DAG, VA, Flags));
2438     }
2439   }
2440
2441   if (!MemOpChains.empty())
2442     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2443                         &MemOpChains[0], MemOpChains.size());
2444
2445   if (Subtarget->isPICStyleGOT()) {
2446     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2447     // GOT pointer.
2448     if (!isTailCall) {
2449       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2450                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2451     } else {
2452       // If we are tail calling and generating PIC/GOT style code load the
2453       // address of the callee into ECX. The value in ecx is used as target of
2454       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2455       // for tail calls on PIC/GOT architectures. Normally we would just put the
2456       // address of GOT into ebx and then call target@PLT. But for tail calls
2457       // ebx would be restored (since ebx is callee saved) before jumping to the
2458       // target@PLT.
2459
2460       // Note: The actual moving to ECX is done further down.
2461       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2462       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2463           !G->getGlobal()->hasProtectedVisibility())
2464         Callee = LowerGlobalAddress(Callee, DAG);
2465       else if (isa<ExternalSymbolSDNode>(Callee))
2466         Callee = LowerExternalSymbol(Callee, DAG);
2467     }
2468   }
2469
2470   if (Is64Bit && isVarArg && !IsWin64) {
2471     // From AMD64 ABI document:
2472     // For calls that may call functions that use varargs or stdargs
2473     // (prototype-less calls or calls to functions containing ellipsis (...) in
2474     // the declaration) %al is used as hidden argument to specify the number
2475     // of SSE registers used. The contents of %al do not need to match exactly
2476     // the number of registers, but must be an ubound on the number of SSE
2477     // registers used and is in the range 0 - 8 inclusive.
2478
2479     // Count the number of XMM registers allocated.
2480     static const uint16_t XMMArgRegs[] = {
2481       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2482       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2483     };
2484     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2485     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2486            && "SSE registers cannot be used when SSE is disabled");
2487
2488     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2489                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2490   }
2491
2492   // For tail calls lower the arguments to the 'real' stack slot.
2493   if (isTailCall) {
2494     // Force all the incoming stack arguments to be loaded from the stack
2495     // before any new outgoing arguments are stored to the stack, because the
2496     // outgoing stack slots may alias the incoming argument stack slots, and
2497     // the alias isn't otherwise explicit. This is slightly more conservative
2498     // than necessary, because it means that each store effectively depends
2499     // on every argument instead of just those arguments it would clobber.
2500     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2501
2502     SmallVector<SDValue, 8> MemOpChains2;
2503     SDValue FIN;
2504     int FI = 0;
2505     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2506       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2507         CCValAssign &VA = ArgLocs[i];
2508         if (VA.isRegLoc())
2509           continue;
2510         assert(VA.isMemLoc());
2511         SDValue Arg = OutVals[i];
2512         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2513         // Create frame index.
2514         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2515         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2516         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2517         FIN = DAG.getFrameIndex(FI, getPointerTy());
2518
2519         if (Flags.isByVal()) {
2520           // Copy relative to framepointer.
2521           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2522           if (StackPtr.getNode() == 0)
2523             StackPtr = DAG.getCopyFromReg(Chain, dl,
2524                                           RegInfo->getStackRegister(),
2525                                           getPointerTy());
2526           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2527
2528           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2529                                                            ArgChain,
2530                                                            Flags, DAG, dl));
2531         } else {
2532           // Store relative to framepointer.
2533           MemOpChains2.push_back(
2534             DAG.getStore(ArgChain, dl, Arg, FIN,
2535                          MachinePointerInfo::getFixedStack(FI),
2536                          false, false, 0));
2537         }
2538       }
2539     }
2540
2541     if (!MemOpChains2.empty())
2542       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2543                           &MemOpChains2[0], MemOpChains2.size());
2544
2545     // Store the return address to the appropriate stack slot.
2546     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2547                                      getPointerTy(), RegInfo->getSlotSize(),
2548                                      FPDiff, dl);
2549   }
2550
2551   // Build a sequence of copy-to-reg nodes chained together with token chain
2552   // and flag operands which copy the outgoing args into registers.
2553   SDValue InFlag;
2554   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2555     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2556                              RegsToPass[i].second, InFlag);
2557     InFlag = Chain.getValue(1);
2558   }
2559
2560   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2561     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2562     // In the 64-bit large code model, we have to make all calls
2563     // through a register, since the call instruction's 32-bit
2564     // pc-relative offset may not be large enough to hold the whole
2565     // address.
2566   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2567     // If the callee is a GlobalAddress node (quite common, every direct call
2568     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2569     // it.
2570
2571     // We should use extra load for direct calls to dllimported functions in
2572     // non-JIT mode.
2573     const GlobalValue *GV = G->getGlobal();
2574     if (!GV->hasDLLImportLinkage()) {
2575       unsigned char OpFlags = 0;
2576       bool ExtraLoad = false;
2577       unsigned WrapperKind = ISD::DELETED_NODE;
2578
2579       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2580       // external symbols most go through the PLT in PIC mode.  If the symbol
2581       // has hidden or protected visibility, or if it is static or local, then
2582       // we don't need to use the PLT - we can directly call it.
2583       if (Subtarget->isTargetELF() &&
2584           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2585           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2586         OpFlags = X86II::MO_PLT;
2587       } else if (Subtarget->isPICStyleStubAny() &&
2588                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2589                  (!Subtarget->getTargetTriple().isMacOSX() ||
2590                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2591         // PC-relative references to external symbols should go through $stub,
2592         // unless we're building with the leopard linker or later, which
2593         // automatically synthesizes these stubs.
2594         OpFlags = X86II::MO_DARWIN_STUB;
2595       } else if (Subtarget->isPICStyleRIPRel() &&
2596                  isa<Function>(GV) &&
2597                  cast<Function>(GV)->getAttributes().
2598                    hasAttribute(AttributeSet::FunctionIndex,
2599                                 Attribute::NonLazyBind)) {
2600         // If the function is marked as non-lazy, generate an indirect call
2601         // which loads from the GOT directly. This avoids runtime overhead
2602         // at the cost of eager binding (and one extra byte of encoding).
2603         OpFlags = X86II::MO_GOTPCREL;
2604         WrapperKind = X86ISD::WrapperRIP;
2605         ExtraLoad = true;
2606       }
2607
2608       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2609                                           G->getOffset(), OpFlags);
2610
2611       // Add a wrapper if needed.
2612       if (WrapperKind != ISD::DELETED_NODE)
2613         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2614       // Add extra indirection if needed.
2615       if (ExtraLoad)
2616         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2617                              MachinePointerInfo::getGOT(),
2618                              false, false, false, 0);
2619     }
2620   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2621     unsigned char OpFlags = 0;
2622
2623     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2624     // external symbols should go through the PLT.
2625     if (Subtarget->isTargetELF() &&
2626         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2627       OpFlags = X86II::MO_PLT;
2628     } else if (Subtarget->isPICStyleStubAny() &&
2629                (!Subtarget->getTargetTriple().isMacOSX() ||
2630                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2631       // PC-relative references to external symbols should go through $stub,
2632       // unless we're building with the leopard linker or later, which
2633       // automatically synthesizes these stubs.
2634       OpFlags = X86II::MO_DARWIN_STUB;
2635     }
2636
2637     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2638                                          OpFlags);
2639   }
2640
2641   // Returns a chain & a flag for retval copy to use.
2642   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2643   SmallVector<SDValue, 8> Ops;
2644
2645   if (!IsSibcall && isTailCall) {
2646     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2647                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2648     InFlag = Chain.getValue(1);
2649   }
2650
2651   Ops.push_back(Chain);
2652   Ops.push_back(Callee);
2653
2654   if (isTailCall)
2655     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2656
2657   // Add argument registers to the end of the list so that they are known live
2658   // into the call.
2659   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2660     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2661                                   RegsToPass[i].second.getValueType()));
2662
2663   // Add a register mask operand representing the call-preserved registers.
2664   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2665   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2666   assert(Mask && "Missing call preserved mask for calling convention");
2667   Ops.push_back(DAG.getRegisterMask(Mask));
2668
2669   if (InFlag.getNode())
2670     Ops.push_back(InFlag);
2671
2672   if (isTailCall) {
2673     // We used to do:
2674     //// If this is the first return lowered for this function, add the regs
2675     //// to the liveout set for the function.
2676     // This isn't right, although it's probably harmless on x86; liveouts
2677     // should be computed from returns not tail calls.  Consider a void
2678     // function making a tail call to a function returning int.
2679     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2680   }
2681
2682   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2683   InFlag = Chain.getValue(1);
2684
2685   // Create the CALLSEQ_END node.
2686   unsigned NumBytesForCalleeToPush;
2687   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2688                        getTargetMachine().Options.GuaranteedTailCallOpt))
2689     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2690   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2691            SR == StackStructReturn)
2692     // If this is a call to a struct-return function, the callee
2693     // pops the hidden struct pointer, so we have to push it back.
2694     // This is common for Darwin/X86, Linux & Mingw32 targets.
2695     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2696     NumBytesForCalleeToPush = 4;
2697   else
2698     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2699
2700   // Returns a flag for retval copy to use.
2701   if (!IsSibcall) {
2702     Chain = DAG.getCALLSEQ_END(Chain,
2703                                DAG.getIntPtrConstant(NumBytes, true),
2704                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2705                                                      true),
2706                                InFlag, dl);
2707     InFlag = Chain.getValue(1);
2708   }
2709
2710   // Handle result values, copying them out of physregs into vregs that we
2711   // return.
2712   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2713                          Ins, dl, DAG, InVals);
2714 }
2715
2716 //===----------------------------------------------------------------------===//
2717 //                Fast Calling Convention (tail call) implementation
2718 //===----------------------------------------------------------------------===//
2719
2720 //  Like std call, callee cleans arguments, convention except that ECX is
2721 //  reserved for storing the tail called function address. Only 2 registers are
2722 //  free for argument passing (inreg). Tail call optimization is performed
2723 //  provided:
2724 //                * tailcallopt is enabled
2725 //                * caller/callee are fastcc
2726 //  On X86_64 architecture with GOT-style position independent code only local
2727 //  (within module) calls are supported at the moment.
2728 //  To keep the stack aligned according to platform abi the function
2729 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2730 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2731 //  If a tail called function callee has more arguments than the caller the
2732 //  caller needs to make sure that there is room to move the RETADDR to. This is
2733 //  achieved by reserving an area the size of the argument delta right after the
2734 //  original REtADDR, but before the saved framepointer or the spilled registers
2735 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2736 //  stack layout:
2737 //    arg1
2738 //    arg2
2739 //    RETADDR
2740 //    [ new RETADDR
2741 //      move area ]
2742 //    (possible EBP)
2743 //    ESI
2744 //    EDI
2745 //    local1 ..
2746
2747 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2748 /// for a 16 byte align requirement.
2749 unsigned
2750 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2751                                                SelectionDAG& DAG) const {
2752   MachineFunction &MF = DAG.getMachineFunction();
2753   const TargetMachine &TM = MF.getTarget();
2754   const X86RegisterInfo *RegInfo =
2755     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2756   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2757   unsigned StackAlignment = TFI.getStackAlignment();
2758   uint64_t AlignMask = StackAlignment - 1;
2759   int64_t Offset = StackSize;
2760   unsigned SlotSize = RegInfo->getSlotSize();
2761   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2762     // Number smaller than 12 so just add the difference.
2763     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2764   } else {
2765     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2766     Offset = ((~AlignMask) & Offset) + StackAlignment +
2767       (StackAlignment-SlotSize);
2768   }
2769   return Offset;
2770 }
2771
2772 /// MatchingStackOffset - Return true if the given stack call argument is
2773 /// already available in the same position (relatively) of the caller's
2774 /// incoming argument stack.
2775 static
2776 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2777                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2778                          const X86InstrInfo *TII) {
2779   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2780   int FI = INT_MAX;
2781   if (Arg.getOpcode() == ISD::CopyFromReg) {
2782     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2783     if (!TargetRegisterInfo::isVirtualRegister(VR))
2784       return false;
2785     MachineInstr *Def = MRI->getVRegDef(VR);
2786     if (!Def)
2787       return false;
2788     if (!Flags.isByVal()) {
2789       if (!TII->isLoadFromStackSlot(Def, FI))
2790         return false;
2791     } else {
2792       unsigned Opcode = Def->getOpcode();
2793       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2794           Def->getOperand(1).isFI()) {
2795         FI = Def->getOperand(1).getIndex();
2796         Bytes = Flags.getByValSize();
2797       } else
2798         return false;
2799     }
2800   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2801     if (Flags.isByVal())
2802       // ByVal argument is passed in as a pointer but it's now being
2803       // dereferenced. e.g.
2804       // define @foo(%struct.X* %A) {
2805       //   tail call @bar(%struct.X* byval %A)
2806       // }
2807       return false;
2808     SDValue Ptr = Ld->getBasePtr();
2809     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2810     if (!FINode)
2811       return false;
2812     FI = FINode->getIndex();
2813   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2814     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2815     FI = FINode->getIndex();
2816     Bytes = Flags.getByValSize();
2817   } else
2818     return false;
2819
2820   assert(FI != INT_MAX);
2821   if (!MFI->isFixedObjectIndex(FI))
2822     return false;
2823   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2824 }
2825
2826 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2827 /// for tail call optimization. Targets which want to do tail call
2828 /// optimization should implement this function.
2829 bool
2830 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2831                                                      CallingConv::ID CalleeCC,
2832                                                      bool isVarArg,
2833                                                      bool isCalleeStructRet,
2834                                                      bool isCallerStructRet,
2835                                                      Type *RetTy,
2836                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2837                                     const SmallVectorImpl<SDValue> &OutVals,
2838                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2839                                                      SelectionDAG &DAG) const {
2840   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2841     return false;
2842
2843   // If -tailcallopt is specified, make fastcc functions tail-callable.
2844   const MachineFunction &MF = DAG.getMachineFunction();
2845   const Function *CallerF = MF.getFunction();
2846
2847   // If the function return type is x86_fp80 and the callee return type is not,
2848   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2849   // perform a tailcall optimization here.
2850   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2851     return false;
2852
2853   CallingConv::ID CallerCC = CallerF->getCallingConv();
2854   bool CCMatch = CallerCC == CalleeCC;
2855   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
2856   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
2857
2858   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2859     if (IsTailCallConvention(CalleeCC) && CCMatch)
2860       return true;
2861     return false;
2862   }
2863
2864   // Look for obvious safe cases to perform tail call optimization that do not
2865   // require ABI changes. This is what gcc calls sibcall.
2866
2867   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2868   // emit a special epilogue.
2869   const X86RegisterInfo *RegInfo =
2870     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2871   if (RegInfo->needsStackRealignment(MF))
2872     return false;
2873
2874   // Also avoid sibcall optimization if either caller or callee uses struct
2875   // return semantics.
2876   if (isCalleeStructRet || isCallerStructRet)
2877     return false;
2878
2879   // An stdcall caller is expected to clean up its arguments; the callee
2880   // isn't going to do that.
2881   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2882     return false;
2883
2884   // Do not sibcall optimize vararg calls unless all arguments are passed via
2885   // registers.
2886   if (isVarArg && !Outs.empty()) {
2887
2888     // Optimizing for varargs on Win64 is unlikely to be safe without
2889     // additional testing.
2890     if (IsCalleeWin64 || IsCallerWin64)
2891       return false;
2892
2893     SmallVector<CCValAssign, 16> ArgLocs;
2894     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2895                    getTargetMachine(), ArgLocs, *DAG.getContext());
2896
2897     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2898     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2899       if (!ArgLocs[i].isRegLoc())
2900         return false;
2901   }
2902
2903   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2904   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2905   // this into a sibcall.
2906   bool Unused = false;
2907   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2908     if (!Ins[i].Used) {
2909       Unused = true;
2910       break;
2911     }
2912   }
2913   if (Unused) {
2914     SmallVector<CCValAssign, 16> RVLocs;
2915     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2916                    getTargetMachine(), RVLocs, *DAG.getContext());
2917     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2918     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2919       CCValAssign &VA = RVLocs[i];
2920       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2921         return false;
2922     }
2923   }
2924
2925   // If the calling conventions do not match, then we'd better make sure the
2926   // results are returned in the same way as what the caller expects.
2927   if (!CCMatch) {
2928     SmallVector<CCValAssign, 16> RVLocs1;
2929     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2930                     getTargetMachine(), RVLocs1, *DAG.getContext());
2931     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2932
2933     SmallVector<CCValAssign, 16> RVLocs2;
2934     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2935                     getTargetMachine(), RVLocs2, *DAG.getContext());
2936     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2937
2938     if (RVLocs1.size() != RVLocs2.size())
2939       return false;
2940     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2941       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2942         return false;
2943       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2944         return false;
2945       if (RVLocs1[i].isRegLoc()) {
2946         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2947           return false;
2948       } else {
2949         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2950           return false;
2951       }
2952     }
2953   }
2954
2955   // If the callee takes no arguments then go on to check the results of the
2956   // call.
2957   if (!Outs.empty()) {
2958     // Check if stack adjustment is needed. For now, do not do this if any
2959     // argument is passed on the stack.
2960     SmallVector<CCValAssign, 16> ArgLocs;
2961     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2962                    getTargetMachine(), ArgLocs, *DAG.getContext());
2963
2964     // Allocate shadow area for Win64
2965     if (IsCalleeWin64)
2966       CCInfo.AllocateStack(32, 8);
2967
2968     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2969     if (CCInfo.getNextStackOffset()) {
2970       MachineFunction &MF = DAG.getMachineFunction();
2971       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2972         return false;
2973
2974       // Check if the arguments are already laid out in the right way as
2975       // the caller's fixed stack objects.
2976       MachineFrameInfo *MFI = MF.getFrameInfo();
2977       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2978       const X86InstrInfo *TII =
2979         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2980       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2981         CCValAssign &VA = ArgLocs[i];
2982         SDValue Arg = OutVals[i];
2983         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2984         if (VA.getLocInfo() == CCValAssign::Indirect)
2985           return false;
2986         if (!VA.isRegLoc()) {
2987           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2988                                    MFI, MRI, TII))
2989             return false;
2990         }
2991       }
2992     }
2993
2994     // If the tailcall address may be in a register, then make sure it's
2995     // possible to register allocate for it. In 32-bit, the call address can
2996     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2997     // callee-saved registers are restored. These happen to be the same
2998     // registers used to pass 'inreg' arguments so watch out for those.
2999     if (!Subtarget->is64Bit() &&
3000         ((!isa<GlobalAddressSDNode>(Callee) &&
3001           !isa<ExternalSymbolSDNode>(Callee)) ||
3002          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3003       unsigned NumInRegs = 0;
3004       // In PIC we need an extra register to formulate the address computation
3005       // for the callee.
3006       unsigned MaxInRegs =
3007           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3008
3009       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3010         CCValAssign &VA = ArgLocs[i];
3011         if (!VA.isRegLoc())
3012           continue;
3013         unsigned Reg = VA.getLocReg();
3014         switch (Reg) {
3015         default: break;
3016         case X86::EAX: case X86::EDX: case X86::ECX:
3017           if (++NumInRegs == MaxInRegs)
3018             return false;
3019           break;
3020         }
3021       }
3022     }
3023   }
3024
3025   return true;
3026 }
3027
3028 FastISel *
3029 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3030                                   const TargetLibraryInfo *libInfo) const {
3031   return X86::createFastISel(funcInfo, libInfo);
3032 }
3033
3034 //===----------------------------------------------------------------------===//
3035 //                           Other Lowering Hooks
3036 //===----------------------------------------------------------------------===//
3037
3038 static bool MayFoldLoad(SDValue Op) {
3039   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3040 }
3041
3042 static bool MayFoldIntoStore(SDValue Op) {
3043   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3044 }
3045
3046 static bool isTargetShuffle(unsigned Opcode) {
3047   switch(Opcode) {
3048   default: return false;
3049   case X86ISD::PSHUFD:
3050   case X86ISD::PSHUFHW:
3051   case X86ISD::PSHUFLW:
3052   case X86ISD::SHUFP:
3053   case X86ISD::PALIGNR:
3054   case X86ISD::MOVLHPS:
3055   case X86ISD::MOVLHPD:
3056   case X86ISD::MOVHLPS:
3057   case X86ISD::MOVLPS:
3058   case X86ISD::MOVLPD:
3059   case X86ISD::MOVSHDUP:
3060   case X86ISD::MOVSLDUP:
3061   case X86ISD::MOVDDUP:
3062   case X86ISD::MOVSS:
3063   case X86ISD::MOVSD:
3064   case X86ISD::UNPCKL:
3065   case X86ISD::UNPCKH:
3066   case X86ISD::VPERMILP:
3067   case X86ISD::VPERM2X128:
3068   case X86ISD::VPERMI:
3069     return true;
3070   }
3071 }
3072
3073 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3074                                     SDValue V1, SelectionDAG &DAG) {
3075   switch(Opc) {
3076   default: llvm_unreachable("Unknown x86 shuffle node");
3077   case X86ISD::MOVSHDUP:
3078   case X86ISD::MOVSLDUP:
3079   case X86ISD::MOVDDUP:
3080     return DAG.getNode(Opc, dl, VT, V1);
3081   }
3082 }
3083
3084 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3085                                     SDValue V1, unsigned TargetMask,
3086                                     SelectionDAG &DAG) {
3087   switch(Opc) {
3088   default: llvm_unreachable("Unknown x86 shuffle node");
3089   case X86ISD::PSHUFD:
3090   case X86ISD::PSHUFHW:
3091   case X86ISD::PSHUFLW:
3092   case X86ISD::VPERMILP:
3093   case X86ISD::VPERMI:
3094     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3095   }
3096 }
3097
3098 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3099                                     SDValue V1, SDValue V2, unsigned TargetMask,
3100                                     SelectionDAG &DAG) {
3101   switch(Opc) {
3102   default: llvm_unreachable("Unknown x86 shuffle node");
3103   case X86ISD::PALIGNR:
3104   case X86ISD::SHUFP:
3105   case X86ISD::VPERM2X128:
3106     return DAG.getNode(Opc, dl, VT, V1, V2,
3107                        DAG.getConstant(TargetMask, MVT::i8));
3108   }
3109 }
3110
3111 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3112                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3113   switch(Opc) {
3114   default: llvm_unreachable("Unknown x86 shuffle node");
3115   case X86ISD::MOVLHPS:
3116   case X86ISD::MOVLHPD:
3117   case X86ISD::MOVHLPS:
3118   case X86ISD::MOVLPS:
3119   case X86ISD::MOVLPD:
3120   case X86ISD::MOVSS:
3121   case X86ISD::MOVSD:
3122   case X86ISD::UNPCKL:
3123   case X86ISD::UNPCKH:
3124     return DAG.getNode(Opc, dl, VT, V1, V2);
3125   }
3126 }
3127
3128 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3129   MachineFunction &MF = DAG.getMachineFunction();
3130   const X86RegisterInfo *RegInfo =
3131     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3132   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3133   int ReturnAddrIndex = FuncInfo->getRAIndex();
3134
3135   if (ReturnAddrIndex == 0) {
3136     // Set up a frame object for the return address.
3137     unsigned SlotSize = RegInfo->getSlotSize();
3138     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3139                                                            false);
3140     FuncInfo->setRAIndex(ReturnAddrIndex);
3141   }
3142
3143   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3144 }
3145
3146 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3147                                        bool hasSymbolicDisplacement) {
3148   // Offset should fit into 32 bit immediate field.
3149   if (!isInt<32>(Offset))
3150     return false;
3151
3152   // If we don't have a symbolic displacement - we don't have any extra
3153   // restrictions.
3154   if (!hasSymbolicDisplacement)
3155     return true;
3156
3157   // FIXME: Some tweaks might be needed for medium code model.
3158   if (M != CodeModel::Small && M != CodeModel::Kernel)
3159     return false;
3160
3161   // For small code model we assume that latest object is 16MB before end of 31
3162   // bits boundary. We may also accept pretty large negative constants knowing
3163   // that all objects are in the positive half of address space.
3164   if (M == CodeModel::Small && Offset < 16*1024*1024)
3165     return true;
3166
3167   // For kernel code model we know that all object resist in the negative half
3168   // of 32bits address space. We may not accept negative offsets, since they may
3169   // be just off and we may accept pretty large positive ones.
3170   if (M == CodeModel::Kernel && Offset > 0)
3171     return true;
3172
3173   return false;
3174 }
3175
3176 /// isCalleePop - Determines whether the callee is required to pop its
3177 /// own arguments. Callee pop is necessary to support tail calls.
3178 bool X86::isCalleePop(CallingConv::ID CallingConv,
3179                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3180   if (IsVarArg)
3181     return false;
3182
3183   switch (CallingConv) {
3184   default:
3185     return false;
3186   case CallingConv::X86_StdCall:
3187     return !is64Bit;
3188   case CallingConv::X86_FastCall:
3189     return !is64Bit;
3190   case CallingConv::X86_ThisCall:
3191     return !is64Bit;
3192   case CallingConv::Fast:
3193     return TailCallOpt;
3194   case CallingConv::GHC:
3195     return TailCallOpt;
3196   case CallingConv::HiPE:
3197     return TailCallOpt;
3198   }
3199 }
3200
3201 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3202 /// specific condition code, returning the condition code and the LHS/RHS of the
3203 /// comparison to make.
3204 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3205                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3206   if (!isFP) {
3207     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3208       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3209         // X > -1   -> X == 0, jump !sign.
3210         RHS = DAG.getConstant(0, RHS.getValueType());
3211         return X86::COND_NS;
3212       }
3213       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3214         // X < 0   -> X == 0, jump on sign.
3215         return X86::COND_S;
3216       }
3217       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3218         // X < 1   -> X <= 0
3219         RHS = DAG.getConstant(0, RHS.getValueType());
3220         return X86::COND_LE;
3221       }
3222     }
3223
3224     switch (SetCCOpcode) {
3225     default: llvm_unreachable("Invalid integer condition!");
3226     case ISD::SETEQ:  return X86::COND_E;
3227     case ISD::SETGT:  return X86::COND_G;
3228     case ISD::SETGE:  return X86::COND_GE;
3229     case ISD::SETLT:  return X86::COND_L;
3230     case ISD::SETLE:  return X86::COND_LE;
3231     case ISD::SETNE:  return X86::COND_NE;
3232     case ISD::SETULT: return X86::COND_B;
3233     case ISD::SETUGT: return X86::COND_A;
3234     case ISD::SETULE: return X86::COND_BE;
3235     case ISD::SETUGE: return X86::COND_AE;
3236     }
3237   }
3238
3239   // First determine if it is required or is profitable to flip the operands.
3240
3241   // If LHS is a foldable load, but RHS is not, flip the condition.
3242   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3243       !ISD::isNON_EXTLoad(RHS.getNode())) {
3244     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3245     std::swap(LHS, RHS);
3246   }
3247
3248   switch (SetCCOpcode) {
3249   default: break;
3250   case ISD::SETOLT:
3251   case ISD::SETOLE:
3252   case ISD::SETUGT:
3253   case ISD::SETUGE:
3254     std::swap(LHS, RHS);
3255     break;
3256   }
3257
3258   // On a floating point condition, the flags are set as follows:
3259   // ZF  PF  CF   op
3260   //  0 | 0 | 0 | X > Y
3261   //  0 | 0 | 1 | X < Y
3262   //  1 | 0 | 0 | X == Y
3263   //  1 | 1 | 1 | unordered
3264   switch (SetCCOpcode) {
3265   default: llvm_unreachable("Condcode should be pre-legalized away");
3266   case ISD::SETUEQ:
3267   case ISD::SETEQ:   return X86::COND_E;
3268   case ISD::SETOLT:              // flipped
3269   case ISD::SETOGT:
3270   case ISD::SETGT:   return X86::COND_A;
3271   case ISD::SETOLE:              // flipped
3272   case ISD::SETOGE:
3273   case ISD::SETGE:   return X86::COND_AE;
3274   case ISD::SETUGT:              // flipped
3275   case ISD::SETULT:
3276   case ISD::SETLT:   return X86::COND_B;
3277   case ISD::SETUGE:              // flipped
3278   case ISD::SETULE:
3279   case ISD::SETLE:   return X86::COND_BE;
3280   case ISD::SETONE:
3281   case ISD::SETNE:   return X86::COND_NE;
3282   case ISD::SETUO:   return X86::COND_P;
3283   case ISD::SETO:    return X86::COND_NP;
3284   case ISD::SETOEQ:
3285   case ISD::SETUNE:  return X86::COND_INVALID;
3286   }
3287 }
3288
3289 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3290 /// code. Current x86 isa includes the following FP cmov instructions:
3291 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3292 static bool hasFPCMov(unsigned X86CC) {
3293   switch (X86CC) {
3294   default:
3295     return false;
3296   case X86::COND_B:
3297   case X86::COND_BE:
3298   case X86::COND_E:
3299   case X86::COND_P:
3300   case X86::COND_A:
3301   case X86::COND_AE:
3302   case X86::COND_NE:
3303   case X86::COND_NP:
3304     return true;
3305   }
3306 }
3307
3308 /// isFPImmLegal - Returns true if the target can instruction select the
3309 /// specified FP immediate natively. If false, the legalizer will
3310 /// materialize the FP immediate as a load from a constant pool.
3311 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3312   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3313     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3314       return true;
3315   }
3316   return false;
3317 }
3318
3319 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3320 /// the specified range (L, H].
3321 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3322   return (Val < 0) || (Val >= Low && Val < Hi);
3323 }
3324
3325 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3326 /// specified value.
3327 static bool isUndefOrEqual(int Val, int CmpVal) {
3328   return (Val < 0 || Val == CmpVal);
3329 }
3330
3331 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3332 /// from position Pos and ending in Pos+Size, falls within the specified
3333 /// sequential range (L, L+Pos]. or is undef.
3334 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3335                                        unsigned Pos, unsigned Size, int Low) {
3336   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3337     if (!isUndefOrEqual(Mask[i], Low))
3338       return false;
3339   return true;
3340 }
3341
3342 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3343 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3344 /// the second operand.
3345 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3346   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3347     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3348   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3349     return (Mask[0] < 2 && Mask[1] < 2);
3350   return false;
3351 }
3352
3353 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3354 /// is suitable for input to PSHUFHW.
3355 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3356   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3357     return false;
3358
3359   // Lower quadword copied in order or undef.
3360   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3361     return false;
3362
3363   // Upper quadword shuffled.
3364   for (unsigned i = 4; i != 8; ++i)
3365     if (!isUndefOrInRange(Mask[i], 4, 8))
3366       return false;
3367
3368   if (VT == MVT::v16i16) {
3369     // Lower quadword copied in order or undef.
3370     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3371       return false;
3372
3373     // Upper quadword shuffled.
3374     for (unsigned i = 12; i != 16; ++i)
3375       if (!isUndefOrInRange(Mask[i], 12, 16))
3376         return false;
3377   }
3378
3379   return true;
3380 }
3381
3382 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3383 /// is suitable for input to PSHUFLW.
3384 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3385   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3386     return false;
3387
3388   // Upper quadword copied in order.
3389   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3390     return false;
3391
3392   // Lower quadword shuffled.
3393   for (unsigned i = 0; i != 4; ++i)
3394     if (!isUndefOrInRange(Mask[i], 0, 4))
3395       return false;
3396
3397   if (VT == MVT::v16i16) {
3398     // Upper quadword copied in order.
3399     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3400       return false;
3401
3402     // Lower quadword shuffled.
3403     for (unsigned i = 8; i != 12; ++i)
3404       if (!isUndefOrInRange(Mask[i], 8, 12))
3405         return false;
3406   }
3407
3408   return true;
3409 }
3410
3411 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3412 /// is suitable for input to PALIGNR.
3413 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3414                           const X86Subtarget *Subtarget) {
3415   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3416       (VT.is256BitVector() && !Subtarget->hasInt256()))
3417     return false;
3418
3419   unsigned NumElts = VT.getVectorNumElements();
3420   unsigned NumLanes = VT.getSizeInBits()/128;
3421   unsigned NumLaneElts = NumElts/NumLanes;
3422
3423   // Do not handle 64-bit element shuffles with palignr.
3424   if (NumLaneElts == 2)
3425     return false;
3426
3427   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3428     unsigned i;
3429     for (i = 0; i != NumLaneElts; ++i) {
3430       if (Mask[i+l] >= 0)
3431         break;
3432     }
3433
3434     // Lane is all undef, go to next lane
3435     if (i == NumLaneElts)
3436       continue;
3437
3438     int Start = Mask[i+l];
3439
3440     // Make sure its in this lane in one of the sources
3441     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3442         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3443       return false;
3444
3445     // If not lane 0, then we must match lane 0
3446     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3447       return false;
3448
3449     // Correct second source to be contiguous with first source
3450     if (Start >= (int)NumElts)
3451       Start -= NumElts - NumLaneElts;
3452
3453     // Make sure we're shifting in the right direction.
3454     if (Start <= (int)(i+l))
3455       return false;
3456
3457     Start -= i;
3458
3459     // Check the rest of the elements to see if they are consecutive.
3460     for (++i; i != NumLaneElts; ++i) {
3461       int Idx = Mask[i+l];
3462
3463       // Make sure its in this lane
3464       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3465           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3466         return false;
3467
3468       // If not lane 0, then we must match lane 0
3469       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3470         return false;
3471
3472       if (Idx >= (int)NumElts)
3473         Idx -= NumElts - NumLaneElts;
3474
3475       if (!isUndefOrEqual(Idx, Start+i))
3476         return false;
3477
3478     }
3479   }
3480
3481   return true;
3482 }
3483
3484 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3485 /// the two vector operands have swapped position.
3486 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3487                                      unsigned NumElems) {
3488   for (unsigned i = 0; i != NumElems; ++i) {
3489     int idx = Mask[i];
3490     if (idx < 0)
3491       continue;
3492     else if (idx < (int)NumElems)
3493       Mask[i] = idx + NumElems;
3494     else
3495       Mask[i] = idx - NumElems;
3496   }
3497 }
3498
3499 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3500 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3501 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3502 /// reverse of what x86 shuffles want.
3503 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3504                         bool Commuted = false) {
3505   if (!HasFp256 && VT.is256BitVector())
3506     return false;
3507
3508   unsigned NumElems = VT.getVectorNumElements();
3509   unsigned NumLanes = VT.getSizeInBits()/128;
3510   unsigned NumLaneElems = NumElems/NumLanes;
3511
3512   if (NumLaneElems != 2 && NumLaneElems != 4)
3513     return false;
3514
3515   // VSHUFPSY divides the resulting vector into 4 chunks.
3516   // The sources are also splitted into 4 chunks, and each destination
3517   // chunk must come from a different source chunk.
3518   //
3519   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3520   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3521   //
3522   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3523   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3524   //
3525   // VSHUFPDY divides the resulting vector into 4 chunks.
3526   // The sources are also splitted into 4 chunks, and each destination
3527   // chunk must come from a different source chunk.
3528   //
3529   //  SRC1 =>      X3       X2       X1       X0
3530   //  SRC2 =>      Y3       Y2       Y1       Y0
3531   //
3532   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3533   //
3534   unsigned HalfLaneElems = NumLaneElems/2;
3535   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3536     for (unsigned i = 0; i != NumLaneElems; ++i) {
3537       int Idx = Mask[i+l];
3538       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3539       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3540         return false;
3541       // For VSHUFPSY, the mask of the second half must be the same as the
3542       // first but with the appropriate offsets. This works in the same way as
3543       // VPERMILPS works with masks.
3544       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3545         continue;
3546       if (!isUndefOrEqual(Idx, Mask[i]+l))
3547         return false;
3548     }
3549   }
3550
3551   return true;
3552 }
3553
3554 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3555 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3556 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3557   if (!VT.is128BitVector())
3558     return false;
3559
3560   unsigned NumElems = VT.getVectorNumElements();
3561
3562   if (NumElems != 4)
3563     return false;
3564
3565   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3566   return isUndefOrEqual(Mask[0], 6) &&
3567          isUndefOrEqual(Mask[1], 7) &&
3568          isUndefOrEqual(Mask[2], 2) &&
3569          isUndefOrEqual(Mask[3], 3);
3570 }
3571
3572 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3573 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3574 /// <2, 3, 2, 3>
3575 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3576   if (!VT.is128BitVector())
3577     return false;
3578
3579   unsigned NumElems = VT.getVectorNumElements();
3580
3581   if (NumElems != 4)
3582     return false;
3583
3584   return isUndefOrEqual(Mask[0], 2) &&
3585          isUndefOrEqual(Mask[1], 3) &&
3586          isUndefOrEqual(Mask[2], 2) &&
3587          isUndefOrEqual(Mask[3], 3);
3588 }
3589
3590 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3591 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3592 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3593   if (!VT.is128BitVector())
3594     return false;
3595
3596   unsigned NumElems = VT.getVectorNumElements();
3597
3598   if (NumElems != 2 && NumElems != 4)
3599     return false;
3600
3601   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3602     if (!isUndefOrEqual(Mask[i], i + NumElems))
3603       return false;
3604
3605   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3606     if (!isUndefOrEqual(Mask[i], i))
3607       return false;
3608
3609   return true;
3610 }
3611
3612 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3613 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3614 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3615   if (!VT.is128BitVector())
3616     return false;
3617
3618   unsigned NumElems = VT.getVectorNumElements();
3619
3620   if (NumElems != 2 && NumElems != 4)
3621     return false;
3622
3623   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3624     if (!isUndefOrEqual(Mask[i], i))
3625       return false;
3626
3627   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3628     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3629       return false;
3630
3631   return true;
3632 }
3633
3634 //
3635 // Some special combinations that can be optimized.
3636 //
3637 static
3638 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3639                                SelectionDAG &DAG) {
3640   MVT VT = SVOp->getValueType(0).getSimpleVT();
3641   SDLoc dl(SVOp);
3642
3643   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3644     return SDValue();
3645
3646   ArrayRef<int> Mask = SVOp->getMask();
3647
3648   // These are the special masks that may be optimized.
3649   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3650   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3651   bool MatchEvenMask = true;
3652   bool MatchOddMask  = true;
3653   for (int i=0; i<8; ++i) {
3654     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3655       MatchEvenMask = false;
3656     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3657       MatchOddMask = false;
3658   }
3659
3660   if (!MatchEvenMask && !MatchOddMask)
3661     return SDValue();
3662
3663   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3664
3665   SDValue Op0 = SVOp->getOperand(0);
3666   SDValue Op1 = SVOp->getOperand(1);
3667
3668   if (MatchEvenMask) {
3669     // Shift the second operand right to 32 bits.
3670     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3671     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3672   } else {
3673     // Shift the first operand left to 32 bits.
3674     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3675     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3676   }
3677   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3678   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3679 }
3680
3681 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3682 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3683 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3684                          bool HasInt256, bool V2IsSplat = false) {
3685   unsigned NumElts = VT.getVectorNumElements();
3686
3687   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3688          "Unsupported vector type for unpckh");
3689
3690   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3691       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3692     return false;
3693
3694   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3695   // independently on 128-bit lanes.
3696   unsigned NumLanes = VT.getSizeInBits()/128;
3697   unsigned NumLaneElts = NumElts/NumLanes;
3698
3699   for (unsigned l = 0; l != NumLanes; ++l) {
3700     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3701          i != (l+1)*NumLaneElts;
3702          i += 2, ++j) {
3703       int BitI  = Mask[i];
3704       int BitI1 = Mask[i+1];
3705       if (!isUndefOrEqual(BitI, j))
3706         return false;
3707       if (V2IsSplat) {
3708         if (!isUndefOrEqual(BitI1, NumElts))
3709           return false;
3710       } else {
3711         if (!isUndefOrEqual(BitI1, j + NumElts))
3712           return false;
3713       }
3714     }
3715   }
3716
3717   return true;
3718 }
3719
3720 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3721 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3722 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3723                          bool HasInt256, bool V2IsSplat = false) {
3724   unsigned NumElts = VT.getVectorNumElements();
3725
3726   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3727          "Unsupported vector type for unpckh");
3728
3729   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3730       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3731     return false;
3732
3733   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3734   // independently on 128-bit lanes.
3735   unsigned NumLanes = VT.getSizeInBits()/128;
3736   unsigned NumLaneElts = NumElts/NumLanes;
3737
3738   for (unsigned l = 0; l != NumLanes; ++l) {
3739     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3740          i != (l+1)*NumLaneElts; i += 2, ++j) {
3741       int BitI  = Mask[i];
3742       int BitI1 = Mask[i+1];
3743       if (!isUndefOrEqual(BitI, j))
3744         return false;
3745       if (V2IsSplat) {
3746         if (isUndefOrEqual(BitI1, NumElts))
3747           return false;
3748       } else {
3749         if (!isUndefOrEqual(BitI1, j+NumElts))
3750           return false;
3751       }
3752     }
3753   }
3754   return true;
3755 }
3756
3757 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3758 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3759 /// <0, 0, 1, 1>
3760 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3761   unsigned NumElts = VT.getVectorNumElements();
3762   bool Is256BitVec = VT.is256BitVector();
3763
3764   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3765          "Unsupported vector type for unpckh");
3766
3767   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3768       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3769     return false;
3770
3771   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3772   // FIXME: Need a better way to get rid of this, there's no latency difference
3773   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3774   // the former later. We should also remove the "_undef" special mask.
3775   if (NumElts == 4 && Is256BitVec)
3776     return false;
3777
3778   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3779   // independently on 128-bit lanes.
3780   unsigned NumLanes = VT.getSizeInBits()/128;
3781   unsigned NumLaneElts = NumElts/NumLanes;
3782
3783   for (unsigned l = 0; l != NumLanes; ++l) {
3784     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3785          i != (l+1)*NumLaneElts;
3786          i += 2, ++j) {
3787       int BitI  = Mask[i];
3788       int BitI1 = Mask[i+1];
3789
3790       if (!isUndefOrEqual(BitI, j))
3791         return false;
3792       if (!isUndefOrEqual(BitI1, j))
3793         return false;
3794     }
3795   }
3796
3797   return true;
3798 }
3799
3800 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3801 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3802 /// <2, 2, 3, 3>
3803 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3804   unsigned NumElts = VT.getVectorNumElements();
3805
3806   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3807          "Unsupported vector type for unpckh");
3808
3809   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3810       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3811     return false;
3812
3813   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3814   // independently on 128-bit lanes.
3815   unsigned NumLanes = VT.getSizeInBits()/128;
3816   unsigned NumLaneElts = NumElts/NumLanes;
3817
3818   for (unsigned l = 0; l != NumLanes; ++l) {
3819     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3820          i != (l+1)*NumLaneElts; i += 2, ++j) {
3821       int BitI  = Mask[i];
3822       int BitI1 = Mask[i+1];
3823       if (!isUndefOrEqual(BitI, j))
3824         return false;
3825       if (!isUndefOrEqual(BitI1, j))
3826         return false;
3827     }
3828   }
3829   return true;
3830 }
3831
3832 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3833 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3834 /// MOVSD, and MOVD, i.e. setting the lowest element.
3835 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3836   if (VT.getVectorElementType().getSizeInBits() < 32)
3837     return false;
3838   if (!VT.is128BitVector())
3839     return false;
3840
3841   unsigned NumElts = VT.getVectorNumElements();
3842
3843   if (!isUndefOrEqual(Mask[0], NumElts))
3844     return false;
3845
3846   for (unsigned i = 1; i != NumElts; ++i)
3847     if (!isUndefOrEqual(Mask[i], i))
3848       return false;
3849
3850   return true;
3851 }
3852
3853 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3854 /// as permutations between 128-bit chunks or halves. As an example: this
3855 /// shuffle bellow:
3856 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3857 /// The first half comes from the second half of V1 and the second half from the
3858 /// the second half of V2.
3859 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3860   if (!HasFp256 || !VT.is256BitVector())
3861     return false;
3862
3863   // The shuffle result is divided into half A and half B. In total the two
3864   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3865   // B must come from C, D, E or F.
3866   unsigned HalfSize = VT.getVectorNumElements()/2;
3867   bool MatchA = false, MatchB = false;
3868
3869   // Check if A comes from one of C, D, E, F.
3870   for (unsigned Half = 0; Half != 4; ++Half) {
3871     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3872       MatchA = true;
3873       break;
3874     }
3875   }
3876
3877   // Check if B comes from one of C, D, E, F.
3878   for (unsigned Half = 0; Half != 4; ++Half) {
3879     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3880       MatchB = true;
3881       break;
3882     }
3883   }
3884
3885   return MatchA && MatchB;
3886 }
3887
3888 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3889 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3890 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3891   MVT VT = SVOp->getValueType(0).getSimpleVT();
3892
3893   unsigned HalfSize = VT.getVectorNumElements()/2;
3894
3895   unsigned FstHalf = 0, SndHalf = 0;
3896   for (unsigned i = 0; i < HalfSize; ++i) {
3897     if (SVOp->getMaskElt(i) > 0) {
3898       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3899       break;
3900     }
3901   }
3902   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3903     if (SVOp->getMaskElt(i) > 0) {
3904       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3905       break;
3906     }
3907   }
3908
3909   return (FstHalf | (SndHalf << 4));
3910 }
3911
3912 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3913 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3914 /// Note that VPERMIL mask matching is different depending whether theunderlying
3915 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3916 /// to the same elements of the low, but to the higher half of the source.
3917 /// In VPERMILPD the two lanes could be shuffled independently of each other
3918 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3919 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3920   if (!HasFp256)
3921     return false;
3922
3923   unsigned NumElts = VT.getVectorNumElements();
3924   // Only match 256-bit with 32/64-bit types
3925   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3926     return false;
3927
3928   unsigned NumLanes = VT.getSizeInBits()/128;
3929   unsigned LaneSize = NumElts/NumLanes;
3930   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3931     for (unsigned i = 0; i != LaneSize; ++i) {
3932       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3933         return false;
3934       if (NumElts != 8 || l == 0)
3935         continue;
3936       // VPERMILPS handling
3937       if (Mask[i] < 0)
3938         continue;
3939       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3940         return false;
3941     }
3942   }
3943
3944   return true;
3945 }
3946
3947 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3948 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3949 /// element of vector 2 and the other elements to come from vector 1 in order.
3950 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3951                                bool V2IsSplat = false, bool V2IsUndef = false) {
3952   if (!VT.is128BitVector())
3953     return false;
3954
3955   unsigned NumOps = VT.getVectorNumElements();
3956   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3957     return false;
3958
3959   if (!isUndefOrEqual(Mask[0], 0))
3960     return false;
3961
3962   for (unsigned i = 1; i != NumOps; ++i)
3963     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3964           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3965           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3966       return false;
3967
3968   return true;
3969 }
3970
3971 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3972 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3973 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3974 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3975                            const X86Subtarget *Subtarget) {
3976   if (!Subtarget->hasSSE3())
3977     return false;
3978
3979   unsigned NumElems = VT.getVectorNumElements();
3980
3981   if ((VT.is128BitVector() && NumElems != 4) ||
3982       (VT.is256BitVector() && NumElems != 8))
3983     return false;
3984
3985   // "i+1" is the value the indexed mask element must have
3986   for (unsigned i = 0; i != NumElems; i += 2)
3987     if (!isUndefOrEqual(Mask[i], i+1) ||
3988         !isUndefOrEqual(Mask[i+1], i+1))
3989       return false;
3990
3991   return true;
3992 }
3993
3994 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3995 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3996 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3997 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3998                            const X86Subtarget *Subtarget) {
3999   if (!Subtarget->hasSSE3())
4000     return false;
4001
4002   unsigned NumElems = VT.getVectorNumElements();
4003
4004   if ((VT.is128BitVector() && NumElems != 4) ||
4005       (VT.is256BitVector() && NumElems != 8))
4006     return false;
4007
4008   // "i" is the value the indexed mask element must have
4009   for (unsigned i = 0; i != NumElems; i += 2)
4010     if (!isUndefOrEqual(Mask[i], i) ||
4011         !isUndefOrEqual(Mask[i+1], i))
4012       return false;
4013
4014   return true;
4015 }
4016
4017 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4018 /// specifies a shuffle of elements that is suitable for input to 256-bit
4019 /// version of MOVDDUP.
4020 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4021   if (!HasFp256 || !VT.is256BitVector())
4022     return false;
4023
4024   unsigned NumElts = VT.getVectorNumElements();
4025   if (NumElts != 4)
4026     return false;
4027
4028   for (unsigned i = 0; i != NumElts/2; ++i)
4029     if (!isUndefOrEqual(Mask[i], 0))
4030       return false;
4031   for (unsigned i = NumElts/2; i != NumElts; ++i)
4032     if (!isUndefOrEqual(Mask[i], NumElts/2))
4033       return false;
4034   return true;
4035 }
4036
4037 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4038 /// specifies a shuffle of elements that is suitable for input to 128-bit
4039 /// version of MOVDDUP.
4040 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4041   if (!VT.is128BitVector())
4042     return false;
4043
4044   unsigned e = VT.getVectorNumElements() / 2;
4045   for (unsigned i = 0; i != e; ++i)
4046     if (!isUndefOrEqual(Mask[i], i))
4047       return false;
4048   for (unsigned i = 0; i != e; ++i)
4049     if (!isUndefOrEqual(Mask[e+i], i))
4050       return false;
4051   return true;
4052 }
4053
4054 /// isVEXTRACTF128Index - Return true if the specified
4055 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4056 /// suitable for input to VEXTRACTF128.
4057 bool X86::isVEXTRACTF128Index(SDNode *N) {
4058   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4059     return false;
4060
4061   // The index should be aligned on a 128-bit boundary.
4062   uint64_t Index =
4063     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4064
4065   MVT VT = N->getValueType(0).getSimpleVT();
4066   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4067   bool Result = (Index * ElSize) % 128 == 0;
4068
4069   return Result;
4070 }
4071
4072 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4073 /// operand specifies a subvector insert that is suitable for input to
4074 /// VINSERTF128.
4075 bool X86::isVINSERTF128Index(SDNode *N) {
4076   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4077     return false;
4078
4079   // The index should be aligned on a 128-bit boundary.
4080   uint64_t Index =
4081     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4082
4083   MVT VT = N->getValueType(0).getSimpleVT();
4084   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4085   bool Result = (Index * ElSize) % 128 == 0;
4086
4087   return Result;
4088 }
4089
4090 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4091 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4092 /// Handles 128-bit and 256-bit.
4093 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4094   MVT VT = N->getValueType(0).getSimpleVT();
4095
4096   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4097          "Unsupported vector type for PSHUF/SHUFP");
4098
4099   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4100   // independently on 128-bit lanes.
4101   unsigned NumElts = VT.getVectorNumElements();
4102   unsigned NumLanes = VT.getSizeInBits()/128;
4103   unsigned NumLaneElts = NumElts/NumLanes;
4104
4105   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4106          "Only supports 2 or 4 elements per lane");
4107
4108   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4109   unsigned Mask = 0;
4110   for (unsigned i = 0; i != NumElts; ++i) {
4111     int Elt = N->getMaskElt(i);
4112     if (Elt < 0) continue;
4113     Elt &= NumLaneElts - 1;
4114     unsigned ShAmt = (i << Shift) % 8;
4115     Mask |= Elt << ShAmt;
4116   }
4117
4118   return Mask;
4119 }
4120
4121 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4122 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4123 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4124   MVT VT = N->getValueType(0).getSimpleVT();
4125
4126   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4127          "Unsupported vector type for PSHUFHW");
4128
4129   unsigned NumElts = VT.getVectorNumElements();
4130
4131   unsigned Mask = 0;
4132   for (unsigned l = 0; l != NumElts; l += 8) {
4133     // 8 nodes per lane, but we only care about the last 4.
4134     for (unsigned i = 0; i < 4; ++i) {
4135       int Elt = N->getMaskElt(l+i+4);
4136       if (Elt < 0) continue;
4137       Elt &= 0x3; // only 2-bits.
4138       Mask |= Elt << (i * 2);
4139     }
4140   }
4141
4142   return Mask;
4143 }
4144
4145 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4146 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4147 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4148   MVT VT = N->getValueType(0).getSimpleVT();
4149
4150   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4151          "Unsupported vector type for PSHUFHW");
4152
4153   unsigned NumElts = VT.getVectorNumElements();
4154
4155   unsigned Mask = 0;
4156   for (unsigned l = 0; l != NumElts; l += 8) {
4157     // 8 nodes per lane, but we only care about the first 4.
4158     for (unsigned i = 0; i < 4; ++i) {
4159       int Elt = N->getMaskElt(l+i);
4160       if (Elt < 0) continue;
4161       Elt &= 0x3; // only 2-bits
4162       Mask |= Elt << (i * 2);
4163     }
4164   }
4165
4166   return Mask;
4167 }
4168
4169 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4170 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4171 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4172   MVT VT = SVOp->getValueType(0).getSimpleVT();
4173   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4174
4175   unsigned NumElts = VT.getVectorNumElements();
4176   unsigned NumLanes = VT.getSizeInBits()/128;
4177   unsigned NumLaneElts = NumElts/NumLanes;
4178
4179   int Val = 0;
4180   unsigned i;
4181   for (i = 0; i != NumElts; ++i) {
4182     Val = SVOp->getMaskElt(i);
4183     if (Val >= 0)
4184       break;
4185   }
4186   if (Val >= (int)NumElts)
4187     Val -= NumElts - NumLaneElts;
4188
4189   assert(Val - i > 0 && "PALIGNR imm should be positive");
4190   return (Val - i) * EltSize;
4191 }
4192
4193 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4194 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4195 /// instructions.
4196 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4197   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4198     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4199
4200   uint64_t Index =
4201     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4202
4203   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4204   MVT ElVT = VecVT.getVectorElementType();
4205
4206   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4207   return Index / NumElemsPerChunk;
4208 }
4209
4210 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4211 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4212 /// instructions.
4213 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4214   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4215     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4216
4217   uint64_t Index =
4218     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4219
4220   MVT VecVT = N->getValueType(0).getSimpleVT();
4221   MVT ElVT = VecVT.getVectorElementType();
4222
4223   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4224   return Index / NumElemsPerChunk;
4225 }
4226
4227 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4228 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4229 /// Handles 256-bit.
4230 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4231   MVT VT = N->getValueType(0).getSimpleVT();
4232
4233   unsigned NumElts = VT.getVectorNumElements();
4234
4235   assert((VT.is256BitVector() && NumElts == 4) &&
4236          "Unsupported vector type for VPERMQ/VPERMPD");
4237
4238   unsigned Mask = 0;
4239   for (unsigned i = 0; i != NumElts; ++i) {
4240     int Elt = N->getMaskElt(i);
4241     if (Elt < 0)
4242       continue;
4243     Mask |= Elt << (i*2);
4244   }
4245
4246   return Mask;
4247 }
4248 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4249 /// constant +0.0.
4250 bool X86::isZeroNode(SDValue Elt) {
4251   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4252     return CN->isNullValue();
4253   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4254     return CFP->getValueAPF().isPosZero();
4255   return false;
4256 }
4257
4258 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4259 /// their permute mask.
4260 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4261                                     SelectionDAG &DAG) {
4262   MVT VT = SVOp->getValueType(0).getSimpleVT();
4263   unsigned NumElems = VT.getVectorNumElements();
4264   SmallVector<int, 8> MaskVec;
4265
4266   for (unsigned i = 0; i != NumElems; ++i) {
4267     int Idx = SVOp->getMaskElt(i);
4268     if (Idx >= 0) {
4269       if (Idx < (int)NumElems)
4270         Idx += NumElems;
4271       else
4272         Idx -= NumElems;
4273     }
4274     MaskVec.push_back(Idx);
4275   }
4276   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4277                               SVOp->getOperand(0), &MaskVec[0]);
4278 }
4279
4280 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4281 /// match movhlps. The lower half elements should come from upper half of
4282 /// V1 (and in order), and the upper half elements should come from the upper
4283 /// half of V2 (and in order).
4284 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4285   if (!VT.is128BitVector())
4286     return false;
4287   if (VT.getVectorNumElements() != 4)
4288     return false;
4289   for (unsigned i = 0, e = 2; i != e; ++i)
4290     if (!isUndefOrEqual(Mask[i], i+2))
4291       return false;
4292   for (unsigned i = 2; i != 4; ++i)
4293     if (!isUndefOrEqual(Mask[i], i+4))
4294       return false;
4295   return true;
4296 }
4297
4298 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4299 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4300 /// required.
4301 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4302   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4303     return false;
4304   N = N->getOperand(0).getNode();
4305   if (!ISD::isNON_EXTLoad(N))
4306     return false;
4307   if (LD)
4308     *LD = cast<LoadSDNode>(N);
4309   return true;
4310 }
4311
4312 // Test whether the given value is a vector value which will be legalized
4313 // into a load.
4314 static bool WillBeConstantPoolLoad(SDNode *N) {
4315   if (N->getOpcode() != ISD::BUILD_VECTOR)
4316     return false;
4317
4318   // Check for any non-constant elements.
4319   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4320     switch (N->getOperand(i).getNode()->getOpcode()) {
4321     case ISD::UNDEF:
4322     case ISD::ConstantFP:
4323     case ISD::Constant:
4324       break;
4325     default:
4326       return false;
4327     }
4328
4329   // Vectors of all-zeros and all-ones are materialized with special
4330   // instructions rather than being loaded.
4331   return !ISD::isBuildVectorAllZeros(N) &&
4332          !ISD::isBuildVectorAllOnes(N);
4333 }
4334
4335 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4336 /// match movlp{s|d}. The lower half elements should come from lower half of
4337 /// V1 (and in order), and the upper half elements should come from the upper
4338 /// half of V2 (and in order). And since V1 will become the source of the
4339 /// MOVLP, it must be either a vector load or a scalar load to vector.
4340 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4341                                ArrayRef<int> Mask, EVT VT) {
4342   if (!VT.is128BitVector())
4343     return false;
4344
4345   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4346     return false;
4347   // Is V2 is a vector load, don't do this transformation. We will try to use
4348   // load folding shufps op.
4349   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4350     return false;
4351
4352   unsigned NumElems = VT.getVectorNumElements();
4353
4354   if (NumElems != 2 && NumElems != 4)
4355     return false;
4356   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4357     if (!isUndefOrEqual(Mask[i], i))
4358       return false;
4359   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4360     if (!isUndefOrEqual(Mask[i], i+NumElems))
4361       return false;
4362   return true;
4363 }
4364
4365 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4366 /// all the same.
4367 static bool isSplatVector(SDNode *N) {
4368   if (N->getOpcode() != ISD::BUILD_VECTOR)
4369     return false;
4370
4371   SDValue SplatValue = N->getOperand(0);
4372   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4373     if (N->getOperand(i) != SplatValue)
4374       return false;
4375   return true;
4376 }
4377
4378 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4379 /// to an zero vector.
4380 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4381 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4382   SDValue V1 = N->getOperand(0);
4383   SDValue V2 = N->getOperand(1);
4384   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4385   for (unsigned i = 0; i != NumElems; ++i) {
4386     int Idx = N->getMaskElt(i);
4387     if (Idx >= (int)NumElems) {
4388       unsigned Opc = V2.getOpcode();
4389       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4390         continue;
4391       if (Opc != ISD::BUILD_VECTOR ||
4392           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4393         return false;
4394     } else if (Idx >= 0) {
4395       unsigned Opc = V1.getOpcode();
4396       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4397         continue;
4398       if (Opc != ISD::BUILD_VECTOR ||
4399           !X86::isZeroNode(V1.getOperand(Idx)))
4400         return false;
4401     }
4402   }
4403   return true;
4404 }
4405
4406 /// getZeroVector - Returns a vector of specified type with all zero elements.
4407 ///
4408 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4409                              SelectionDAG &DAG, SDLoc dl) {
4410   assert(VT.isVector() && "Expected a vector type");
4411
4412   // Always build SSE zero vectors as <4 x i32> bitcasted
4413   // to their dest type. This ensures they get CSE'd.
4414   SDValue Vec;
4415   if (VT.is128BitVector()) {  // SSE
4416     if (Subtarget->hasSSE2()) {  // SSE2
4417       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4418       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4419     } else { // SSE1
4420       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4421       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4422     }
4423   } else if (VT.is256BitVector()) { // AVX
4424     if (Subtarget->hasInt256()) { // AVX2
4425       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4426       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4427       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4428                         array_lengthof(Ops));
4429     } else {
4430       // 256-bit logic and arithmetic instructions in AVX are all
4431       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4432       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4433       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4434       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4435                         array_lengthof(Ops));
4436     }
4437   } else
4438     llvm_unreachable("Unexpected vector type");
4439
4440   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4441 }
4442
4443 /// getOnesVector - Returns a vector of specified type with all bits set.
4444 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4445 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4446 /// Then bitcast to their original type, ensuring they get CSE'd.
4447 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4448                              SDLoc dl) {
4449   assert(VT.isVector() && "Expected a vector type");
4450
4451   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4452   SDValue Vec;
4453   if (VT.is256BitVector()) {
4454     if (HasInt256) { // AVX2
4455       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4456       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4457                         array_lengthof(Ops));
4458     } else { // AVX
4459       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4460       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4461     }
4462   } else if (VT.is128BitVector()) {
4463     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4464   } else
4465     llvm_unreachable("Unexpected vector type");
4466
4467   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4468 }
4469
4470 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4471 /// that point to V2 points to its first element.
4472 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4473   for (unsigned i = 0; i != NumElems; ++i) {
4474     if (Mask[i] > (int)NumElems) {
4475       Mask[i] = NumElems;
4476     }
4477   }
4478 }
4479
4480 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4481 /// operation of specified width.
4482 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4483                        SDValue V2) {
4484   unsigned NumElems = VT.getVectorNumElements();
4485   SmallVector<int, 8> Mask;
4486   Mask.push_back(NumElems);
4487   for (unsigned i = 1; i != NumElems; ++i)
4488     Mask.push_back(i);
4489   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4490 }
4491
4492 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4493 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4494                           SDValue V2) {
4495   unsigned NumElems = VT.getVectorNumElements();
4496   SmallVector<int, 8> Mask;
4497   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4498     Mask.push_back(i);
4499     Mask.push_back(i + NumElems);
4500   }
4501   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4502 }
4503
4504 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4505 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4506                           SDValue V2) {
4507   unsigned NumElems = VT.getVectorNumElements();
4508   SmallVector<int, 8> Mask;
4509   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4510     Mask.push_back(i + Half);
4511     Mask.push_back(i + NumElems + Half);
4512   }
4513   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4514 }
4515
4516 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4517 // a generic shuffle instruction because the target has no such instructions.
4518 // Generate shuffles which repeat i16 and i8 several times until they can be
4519 // represented by v4f32 and then be manipulated by target suported shuffles.
4520 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4521   EVT VT = V.getValueType();
4522   int NumElems = VT.getVectorNumElements();
4523   SDLoc dl(V);
4524
4525   while (NumElems > 4) {
4526     if (EltNo < NumElems/2) {
4527       V = getUnpackl(DAG, dl, VT, V, V);
4528     } else {
4529       V = getUnpackh(DAG, dl, VT, V, V);
4530       EltNo -= NumElems/2;
4531     }
4532     NumElems >>= 1;
4533   }
4534   return V;
4535 }
4536
4537 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4538 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4539   EVT VT = V.getValueType();
4540   SDLoc dl(V);
4541
4542   if (VT.is128BitVector()) {
4543     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4544     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4545     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4546                              &SplatMask[0]);
4547   } else if (VT.is256BitVector()) {
4548     // To use VPERMILPS to splat scalars, the second half of indicies must
4549     // refer to the higher part, which is a duplication of the lower one,
4550     // because VPERMILPS can only handle in-lane permutations.
4551     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4552                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4553
4554     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4555     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4556                              &SplatMask[0]);
4557   } else
4558     llvm_unreachable("Vector size not supported");
4559
4560   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4561 }
4562
4563 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4564 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4565   EVT SrcVT = SV->getValueType(0);
4566   SDValue V1 = SV->getOperand(0);
4567   SDLoc dl(SV);
4568
4569   int EltNo = SV->getSplatIndex();
4570   int NumElems = SrcVT.getVectorNumElements();
4571   bool Is256BitVec = SrcVT.is256BitVector();
4572
4573   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4574          "Unknown how to promote splat for type");
4575
4576   // Extract the 128-bit part containing the splat element and update
4577   // the splat element index when it refers to the higher register.
4578   if (Is256BitVec) {
4579     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4580     if (EltNo >= NumElems/2)
4581       EltNo -= NumElems/2;
4582   }
4583
4584   // All i16 and i8 vector types can't be used directly by a generic shuffle
4585   // instruction because the target has no such instruction. Generate shuffles
4586   // which repeat i16 and i8 several times until they fit in i32, and then can
4587   // be manipulated by target suported shuffles.
4588   EVT EltVT = SrcVT.getVectorElementType();
4589   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4590     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4591
4592   // Recreate the 256-bit vector and place the same 128-bit vector
4593   // into the low and high part. This is necessary because we want
4594   // to use VPERM* to shuffle the vectors
4595   if (Is256BitVec) {
4596     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4597   }
4598
4599   return getLegalSplat(DAG, V1, EltNo);
4600 }
4601
4602 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4603 /// vector of zero or undef vector.  This produces a shuffle where the low
4604 /// element of V2 is swizzled into the zero/undef vector, landing at element
4605 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4606 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4607                                            bool IsZero,
4608                                            const X86Subtarget *Subtarget,
4609                                            SelectionDAG &DAG) {
4610   EVT VT = V2.getValueType();
4611   SDValue V1 = IsZero
4612     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4613   unsigned NumElems = VT.getVectorNumElements();
4614   SmallVector<int, 16> MaskVec;
4615   for (unsigned i = 0; i != NumElems; ++i)
4616     // If this is the insertion idx, put the low elt of V2 here.
4617     MaskVec.push_back(i == Idx ? NumElems : i);
4618   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4619 }
4620
4621 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4622 /// target specific opcode. Returns true if the Mask could be calculated.
4623 /// Sets IsUnary to true if only uses one source.
4624 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4625                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4626   unsigned NumElems = VT.getVectorNumElements();
4627   SDValue ImmN;
4628
4629   IsUnary = false;
4630   switch(N->getOpcode()) {
4631   case X86ISD::SHUFP:
4632     ImmN = N->getOperand(N->getNumOperands()-1);
4633     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4634     break;
4635   case X86ISD::UNPCKH:
4636     DecodeUNPCKHMask(VT, Mask);
4637     break;
4638   case X86ISD::UNPCKL:
4639     DecodeUNPCKLMask(VT, Mask);
4640     break;
4641   case X86ISD::MOVHLPS:
4642     DecodeMOVHLPSMask(NumElems, Mask);
4643     break;
4644   case X86ISD::MOVLHPS:
4645     DecodeMOVLHPSMask(NumElems, Mask);
4646     break;
4647   case X86ISD::PALIGNR:
4648     ImmN = N->getOperand(N->getNumOperands()-1);
4649     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4650     break;
4651   case X86ISD::PSHUFD:
4652   case X86ISD::VPERMILP:
4653     ImmN = N->getOperand(N->getNumOperands()-1);
4654     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4655     IsUnary = true;
4656     break;
4657   case X86ISD::PSHUFHW:
4658     ImmN = N->getOperand(N->getNumOperands()-1);
4659     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4660     IsUnary = true;
4661     break;
4662   case X86ISD::PSHUFLW:
4663     ImmN = N->getOperand(N->getNumOperands()-1);
4664     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4665     IsUnary = true;
4666     break;
4667   case X86ISD::VPERMI:
4668     ImmN = N->getOperand(N->getNumOperands()-1);
4669     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4670     IsUnary = true;
4671     break;
4672   case X86ISD::MOVSS:
4673   case X86ISD::MOVSD: {
4674     // The index 0 always comes from the first element of the second source,
4675     // this is why MOVSS and MOVSD are used in the first place. The other
4676     // elements come from the other positions of the first source vector
4677     Mask.push_back(NumElems);
4678     for (unsigned i = 1; i != NumElems; ++i) {
4679       Mask.push_back(i);
4680     }
4681     break;
4682   }
4683   case X86ISD::VPERM2X128:
4684     ImmN = N->getOperand(N->getNumOperands()-1);
4685     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4686     if (Mask.empty()) return false;
4687     break;
4688   case X86ISD::MOVDDUP:
4689   case X86ISD::MOVLHPD:
4690   case X86ISD::MOVLPD:
4691   case X86ISD::MOVLPS:
4692   case X86ISD::MOVSHDUP:
4693   case X86ISD::MOVSLDUP:
4694     // Not yet implemented
4695     return false;
4696   default: llvm_unreachable("unknown target shuffle node");
4697   }
4698
4699   return true;
4700 }
4701
4702 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4703 /// element of the result of the vector shuffle.
4704 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4705                                    unsigned Depth) {
4706   if (Depth == 6)
4707     return SDValue();  // Limit search depth.
4708
4709   SDValue V = SDValue(N, 0);
4710   EVT VT = V.getValueType();
4711   unsigned Opcode = V.getOpcode();
4712
4713   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4714   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4715     int Elt = SV->getMaskElt(Index);
4716
4717     if (Elt < 0)
4718       return DAG.getUNDEF(VT.getVectorElementType());
4719
4720     unsigned NumElems = VT.getVectorNumElements();
4721     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4722                                          : SV->getOperand(1);
4723     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4724   }
4725
4726   // Recurse into target specific vector shuffles to find scalars.
4727   if (isTargetShuffle(Opcode)) {
4728     MVT ShufVT = V.getValueType().getSimpleVT();
4729     unsigned NumElems = ShufVT.getVectorNumElements();
4730     SmallVector<int, 16> ShuffleMask;
4731     bool IsUnary;
4732
4733     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4734       return SDValue();
4735
4736     int Elt = ShuffleMask[Index];
4737     if (Elt < 0)
4738       return DAG.getUNDEF(ShufVT.getVectorElementType());
4739
4740     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4741                                          : N->getOperand(1);
4742     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4743                                Depth+1);
4744   }
4745
4746   // Actual nodes that may contain scalar elements
4747   if (Opcode == ISD::BITCAST) {
4748     V = V.getOperand(0);
4749     EVT SrcVT = V.getValueType();
4750     unsigned NumElems = VT.getVectorNumElements();
4751
4752     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4753       return SDValue();
4754   }
4755
4756   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4757     return (Index == 0) ? V.getOperand(0)
4758                         : DAG.getUNDEF(VT.getVectorElementType());
4759
4760   if (V.getOpcode() == ISD::BUILD_VECTOR)
4761     return V.getOperand(Index);
4762
4763   return SDValue();
4764 }
4765
4766 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4767 /// shuffle operation which come from a consecutively from a zero. The
4768 /// search can start in two different directions, from left or right.
4769 /// We count undefs as zeros until PreferredNum is reached.
4770 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
4771                                          unsigned NumElems, bool ZerosFromLeft,
4772                                          SelectionDAG &DAG,
4773                                          unsigned PreferredNum = -1U) {
4774   unsigned NumZeros = 0;
4775   for (unsigned i = 0; i != NumElems; ++i) {
4776     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
4777     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4778     if (!Elt.getNode())
4779       break;
4780
4781     if (X86::isZeroNode(Elt))
4782       ++NumZeros;
4783     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
4784       NumZeros = std::min(NumZeros + 1, PreferredNum);
4785     else
4786       break;
4787   }
4788
4789   return NumZeros;
4790 }
4791
4792 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4793 /// correspond consecutively to elements from one of the vector operands,
4794 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4795 static
4796 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4797                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4798                               unsigned NumElems, unsigned &OpNum) {
4799   bool SeenV1 = false;
4800   bool SeenV2 = false;
4801
4802   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4803     int Idx = SVOp->getMaskElt(i);
4804     // Ignore undef indicies
4805     if (Idx < 0)
4806       continue;
4807
4808     if (Idx < (int)NumElems)
4809       SeenV1 = true;
4810     else
4811       SeenV2 = true;
4812
4813     // Only accept consecutive elements from the same vector
4814     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4815       return false;
4816   }
4817
4818   OpNum = SeenV1 ? 0 : 1;
4819   return true;
4820 }
4821
4822 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4823 /// logical left shift of a vector.
4824 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4825                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4826   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4827   unsigned NumZeros = getNumOfConsecutiveZeros(
4828       SVOp, NumElems, false /* check zeros from right */, DAG,
4829       SVOp->getMaskElt(0));
4830   unsigned OpSrc;
4831
4832   if (!NumZeros)
4833     return false;
4834
4835   // Considering the elements in the mask that are not consecutive zeros,
4836   // check if they consecutively come from only one of the source vectors.
4837   //
4838   //               V1 = {X, A, B, C}     0
4839   //                         \  \  \    /
4840   //   vector_shuffle V1, V2 <1, 2, 3, X>
4841   //
4842   if (!isShuffleMaskConsecutive(SVOp,
4843             0,                   // Mask Start Index
4844             NumElems-NumZeros,   // Mask End Index(exclusive)
4845             NumZeros,            // Where to start looking in the src vector
4846             NumElems,            // Number of elements in vector
4847             OpSrc))              // Which source operand ?
4848     return false;
4849
4850   isLeft = false;
4851   ShAmt = NumZeros;
4852   ShVal = SVOp->getOperand(OpSrc);
4853   return true;
4854 }
4855
4856 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4857 /// logical left shift of a vector.
4858 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4859                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4860   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4861   unsigned NumZeros = getNumOfConsecutiveZeros(
4862       SVOp, NumElems, true /* check zeros from left */, DAG,
4863       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
4864   unsigned OpSrc;
4865
4866   if (!NumZeros)
4867     return false;
4868
4869   // Considering the elements in the mask that are not consecutive zeros,
4870   // check if they consecutively come from only one of the source vectors.
4871   //
4872   //                           0    { A, B, X, X } = V2
4873   //                          / \    /  /
4874   //   vector_shuffle V1, V2 <X, X, 4, 5>
4875   //
4876   if (!isShuffleMaskConsecutive(SVOp,
4877             NumZeros,     // Mask Start Index
4878             NumElems,     // Mask End Index(exclusive)
4879             0,            // Where to start looking in the src vector
4880             NumElems,     // Number of elements in vector
4881             OpSrc))       // Which source operand ?
4882     return false;
4883
4884   isLeft = true;
4885   ShAmt = NumZeros;
4886   ShVal = SVOp->getOperand(OpSrc);
4887   return true;
4888 }
4889
4890 /// isVectorShift - Returns true if the shuffle can be implemented as a
4891 /// logical left or right shift of a vector.
4892 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4893                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4894   // Although the logic below support any bitwidth size, there are no
4895   // shift instructions which handle more than 128-bit vectors.
4896   if (!SVOp->getValueType(0).is128BitVector())
4897     return false;
4898
4899   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4900       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4901     return true;
4902
4903   return false;
4904 }
4905
4906 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4907 ///
4908 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4909                                        unsigned NumNonZero, unsigned NumZero,
4910                                        SelectionDAG &DAG,
4911                                        const X86Subtarget* Subtarget,
4912                                        const TargetLowering &TLI) {
4913   if (NumNonZero > 8)
4914     return SDValue();
4915
4916   SDLoc dl(Op);
4917   SDValue V(0, 0);
4918   bool First = true;
4919   for (unsigned i = 0; i < 16; ++i) {
4920     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4921     if (ThisIsNonZero && First) {
4922       if (NumZero)
4923         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4924       else
4925         V = DAG.getUNDEF(MVT::v8i16);
4926       First = false;
4927     }
4928
4929     if ((i & 1) != 0) {
4930       SDValue ThisElt(0, 0), LastElt(0, 0);
4931       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4932       if (LastIsNonZero) {
4933         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4934                               MVT::i16, Op.getOperand(i-1));
4935       }
4936       if (ThisIsNonZero) {
4937         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4938         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4939                               ThisElt, DAG.getConstant(8, MVT::i8));
4940         if (LastIsNonZero)
4941           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4942       } else
4943         ThisElt = LastElt;
4944
4945       if (ThisElt.getNode())
4946         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4947                         DAG.getIntPtrConstant(i/2));
4948     }
4949   }
4950
4951   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4952 }
4953
4954 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4955 ///
4956 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4957                                      unsigned NumNonZero, unsigned NumZero,
4958                                      SelectionDAG &DAG,
4959                                      const X86Subtarget* Subtarget,
4960                                      const TargetLowering &TLI) {
4961   if (NumNonZero > 4)
4962     return SDValue();
4963
4964   SDLoc dl(Op);
4965   SDValue V(0, 0);
4966   bool First = true;
4967   for (unsigned i = 0; i < 8; ++i) {
4968     bool isNonZero = (NonZeros & (1 << i)) != 0;
4969     if (isNonZero) {
4970       if (First) {
4971         if (NumZero)
4972           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4973         else
4974           V = DAG.getUNDEF(MVT::v8i16);
4975         First = false;
4976       }
4977       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4978                       MVT::v8i16, V, Op.getOperand(i),
4979                       DAG.getIntPtrConstant(i));
4980     }
4981   }
4982
4983   return V;
4984 }
4985
4986 /// getVShift - Return a vector logical shift node.
4987 ///
4988 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4989                          unsigned NumBits, SelectionDAG &DAG,
4990                          const TargetLowering &TLI, SDLoc dl) {
4991   assert(VT.is128BitVector() && "Unknown type for VShift");
4992   EVT ShVT = MVT::v2i64;
4993   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4994   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4995   return DAG.getNode(ISD::BITCAST, dl, VT,
4996                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4997                              DAG.getConstant(NumBits,
4998                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4999 }
5000
5001 SDValue
5002 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5003                                           SelectionDAG &DAG) const {
5004
5005   // Check if the scalar load can be widened into a vector load. And if
5006   // the address is "base + cst" see if the cst can be "absorbed" into
5007   // the shuffle mask.
5008   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5009     SDValue Ptr = LD->getBasePtr();
5010     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5011       return SDValue();
5012     EVT PVT = LD->getValueType(0);
5013     if (PVT != MVT::i32 && PVT != MVT::f32)
5014       return SDValue();
5015
5016     int FI = -1;
5017     int64_t Offset = 0;
5018     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5019       FI = FINode->getIndex();
5020       Offset = 0;
5021     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5022                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5023       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5024       Offset = Ptr.getConstantOperandVal(1);
5025       Ptr = Ptr.getOperand(0);
5026     } else {
5027       return SDValue();
5028     }
5029
5030     // FIXME: 256-bit vector instructions don't require a strict alignment,
5031     // improve this code to support it better.
5032     unsigned RequiredAlign = VT.getSizeInBits()/8;
5033     SDValue Chain = LD->getChain();
5034     // Make sure the stack object alignment is at least 16 or 32.
5035     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5036     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5037       if (MFI->isFixedObjectIndex(FI)) {
5038         // Can't change the alignment. FIXME: It's possible to compute
5039         // the exact stack offset and reference FI + adjust offset instead.
5040         // If someone *really* cares about this. That's the way to implement it.
5041         return SDValue();
5042       } else {
5043         MFI->setObjectAlignment(FI, RequiredAlign);
5044       }
5045     }
5046
5047     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5048     // Ptr + (Offset & ~15).
5049     if (Offset < 0)
5050       return SDValue();
5051     if ((Offset % RequiredAlign) & 3)
5052       return SDValue();
5053     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5054     if (StartOffset)
5055       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5056                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5057
5058     int EltNo = (Offset - StartOffset) >> 2;
5059     unsigned NumElems = VT.getVectorNumElements();
5060
5061     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5062     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5063                              LD->getPointerInfo().getWithOffset(StartOffset),
5064                              false, false, false, 0);
5065
5066     SmallVector<int, 8> Mask;
5067     for (unsigned i = 0; i != NumElems; ++i)
5068       Mask.push_back(EltNo);
5069
5070     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5071   }
5072
5073   return SDValue();
5074 }
5075
5076 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5077 /// vector of type 'VT', see if the elements can be replaced by a single large
5078 /// load which has the same value as a build_vector whose operands are 'elts'.
5079 ///
5080 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5081 ///
5082 /// FIXME: we'd also like to handle the case where the last elements are zero
5083 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5084 /// There's even a handy isZeroNode for that purpose.
5085 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5086                                         SDLoc &DL, SelectionDAG &DAG) {
5087   EVT EltVT = VT.getVectorElementType();
5088   unsigned NumElems = Elts.size();
5089
5090   LoadSDNode *LDBase = NULL;
5091   unsigned LastLoadedElt = -1U;
5092
5093   // For each element in the initializer, see if we've found a load or an undef.
5094   // If we don't find an initial load element, or later load elements are
5095   // non-consecutive, bail out.
5096   for (unsigned i = 0; i < NumElems; ++i) {
5097     SDValue Elt = Elts[i];
5098
5099     if (!Elt.getNode() ||
5100         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5101       return SDValue();
5102     if (!LDBase) {
5103       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5104         return SDValue();
5105       LDBase = cast<LoadSDNode>(Elt.getNode());
5106       LastLoadedElt = i;
5107       continue;
5108     }
5109     if (Elt.getOpcode() == ISD::UNDEF)
5110       continue;
5111
5112     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5113     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5114       return SDValue();
5115     LastLoadedElt = i;
5116   }
5117
5118   // If we have found an entire vector of loads and undefs, then return a large
5119   // load of the entire vector width starting at the base pointer.  If we found
5120   // consecutive loads for the low half, generate a vzext_load node.
5121   if (LastLoadedElt == NumElems - 1) {
5122     SDValue NewLd = SDValue();
5123     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5124       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5125                           LDBase->getPointerInfo(),
5126                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5127                           LDBase->isInvariant(), 0);
5128     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5129                         LDBase->getPointerInfo(),
5130                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5131                         LDBase->isInvariant(), LDBase->getAlignment());
5132
5133     if (LDBase->hasAnyUseOfValue(1)) {
5134       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5135                                      SDValue(LDBase, 1),
5136                                      SDValue(NewLd.getNode(), 1));
5137       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5138       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5139                              SDValue(NewLd.getNode(), 1));
5140     }
5141
5142     return NewLd;
5143   }
5144   if (NumElems == 4 && LastLoadedElt == 1 &&
5145       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5146     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5147     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5148     SDValue ResNode =
5149         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5150                                 array_lengthof(Ops), MVT::i64,
5151                                 LDBase->getPointerInfo(),
5152                                 LDBase->getAlignment(),
5153                                 false/*isVolatile*/, true/*ReadMem*/,
5154                                 false/*WriteMem*/);
5155
5156     // Make sure the newly-created LOAD is in the same position as LDBase in
5157     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5158     // update uses of LDBase's output chain to use the TokenFactor.
5159     if (LDBase->hasAnyUseOfValue(1)) {
5160       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5161                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5162       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5163       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5164                              SDValue(ResNode.getNode(), 1));
5165     }
5166
5167     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5168   }
5169   return SDValue();
5170 }
5171
5172 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5173 /// to generate a splat value for the following cases:
5174 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5175 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5176 /// a scalar load, or a constant.
5177 /// The VBROADCAST node is returned when a pattern is found,
5178 /// or SDValue() otherwise.
5179 SDValue
5180 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5181   if (!Subtarget->hasFp256())
5182     return SDValue();
5183
5184   MVT VT = Op.getValueType().getSimpleVT();
5185   SDLoc dl(Op);
5186
5187   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5188          "Unsupported vector type for broadcast.");
5189
5190   SDValue Ld;
5191   bool ConstSplatVal;
5192
5193   switch (Op.getOpcode()) {
5194     default:
5195       // Unknown pattern found.
5196       return SDValue();
5197
5198     case ISD::BUILD_VECTOR: {
5199       // The BUILD_VECTOR node must be a splat.
5200       if (!isSplatVector(Op.getNode()))
5201         return SDValue();
5202
5203       Ld = Op.getOperand(0);
5204       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5205                      Ld.getOpcode() == ISD::ConstantFP);
5206
5207       // The suspected load node has several users. Make sure that all
5208       // of its users are from the BUILD_VECTOR node.
5209       // Constants may have multiple users.
5210       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5211         return SDValue();
5212       break;
5213     }
5214
5215     case ISD::VECTOR_SHUFFLE: {
5216       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5217
5218       // Shuffles must have a splat mask where the first element is
5219       // broadcasted.
5220       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5221         return SDValue();
5222
5223       SDValue Sc = Op.getOperand(0);
5224       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5225           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5226
5227         if (!Subtarget->hasInt256())
5228           return SDValue();
5229
5230         // Use the register form of the broadcast instruction available on AVX2.
5231         if (VT.is256BitVector())
5232           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5233         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5234       }
5235
5236       Ld = Sc.getOperand(0);
5237       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5238                        Ld.getOpcode() == ISD::ConstantFP);
5239
5240       // The scalar_to_vector node and the suspected
5241       // load node must have exactly one user.
5242       // Constants may have multiple users.
5243       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5244         return SDValue();
5245       break;
5246     }
5247   }
5248
5249   bool Is256 = VT.is256BitVector();
5250
5251   // Handle the broadcasting a single constant scalar from the constant pool
5252   // into a vector. On Sandybridge it is still better to load a constant vector
5253   // from the constant pool and not to broadcast it from a scalar.
5254   if (ConstSplatVal && Subtarget->hasInt256()) {
5255     EVT CVT = Ld.getValueType();
5256     assert(!CVT.isVector() && "Must not broadcast a vector type");
5257     unsigned ScalarSize = CVT.getSizeInBits();
5258
5259     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5260       const Constant *C = 0;
5261       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5262         C = CI->getConstantIntValue();
5263       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5264         C = CF->getConstantFPValue();
5265
5266       assert(C && "Invalid constant type");
5267
5268       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5269       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5270       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5271                        MachinePointerInfo::getConstantPool(),
5272                        false, false, false, Alignment);
5273
5274       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5275     }
5276   }
5277
5278   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5279   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5280
5281   // Handle AVX2 in-register broadcasts.
5282   if (!IsLoad && Subtarget->hasInt256() &&
5283       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5284     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5285
5286   // The scalar source must be a normal load.
5287   if (!IsLoad)
5288     return SDValue();
5289
5290   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5291     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5292
5293   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5294   // double since there is no vbroadcastsd xmm
5295   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5296     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5297       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5298   }
5299
5300   // Unsupported broadcast.
5301   return SDValue();
5302 }
5303
5304 SDValue
5305 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5306   EVT VT = Op.getValueType();
5307
5308   // Skip if insert_vec_elt is not supported.
5309   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5310     return SDValue();
5311
5312   SDLoc DL(Op);
5313   unsigned NumElems = Op.getNumOperands();
5314
5315   SDValue VecIn1;
5316   SDValue VecIn2;
5317   SmallVector<unsigned, 4> InsertIndices;
5318   SmallVector<int, 8> Mask(NumElems, -1);
5319
5320   for (unsigned i = 0; i != NumElems; ++i) {
5321     unsigned Opc = Op.getOperand(i).getOpcode();
5322
5323     if (Opc == ISD::UNDEF)
5324       continue;
5325
5326     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5327       // Quit if more than 1 elements need inserting.
5328       if (InsertIndices.size() > 1)
5329         return SDValue();
5330
5331       InsertIndices.push_back(i);
5332       continue;
5333     }
5334
5335     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5336     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5337
5338     // Quit if extracted from vector of different type.
5339     if (ExtractedFromVec.getValueType() != VT)
5340       return SDValue();
5341
5342     // Quit if non-constant index.
5343     if (!isa<ConstantSDNode>(ExtIdx))
5344       return SDValue();
5345
5346     if (VecIn1.getNode() == 0)
5347       VecIn1 = ExtractedFromVec;
5348     else if (VecIn1 != ExtractedFromVec) {
5349       if (VecIn2.getNode() == 0)
5350         VecIn2 = ExtractedFromVec;
5351       else if (VecIn2 != ExtractedFromVec)
5352         // Quit if more than 2 vectors to shuffle
5353         return SDValue();
5354     }
5355
5356     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5357
5358     if (ExtractedFromVec == VecIn1)
5359       Mask[i] = Idx;
5360     else if (ExtractedFromVec == VecIn2)
5361       Mask[i] = Idx + NumElems;
5362   }
5363
5364   if (VecIn1.getNode() == 0)
5365     return SDValue();
5366
5367   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5368   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5369   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5370     unsigned Idx = InsertIndices[i];
5371     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5372                      DAG.getIntPtrConstant(Idx));
5373   }
5374
5375   return NV;
5376 }
5377
5378 SDValue
5379 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5380   SDLoc dl(Op);
5381
5382   MVT VT = Op.getValueType().getSimpleVT();
5383   MVT ExtVT = VT.getVectorElementType();
5384   unsigned NumElems = Op.getNumOperands();
5385
5386   // Vectors containing all zeros can be matched by pxor and xorps later
5387   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5388     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5389     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5390     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5391       return Op;
5392
5393     return getZeroVector(VT, Subtarget, DAG, dl);
5394   }
5395
5396   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5397   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5398   // vpcmpeqd on 256-bit vectors.
5399   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5400     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5401       return Op;
5402
5403     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5404   }
5405
5406   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5407   if (Broadcast.getNode())
5408     return Broadcast;
5409
5410   unsigned EVTBits = ExtVT.getSizeInBits();
5411
5412   unsigned NumZero  = 0;
5413   unsigned NumNonZero = 0;
5414   unsigned NonZeros = 0;
5415   bool IsAllConstants = true;
5416   SmallSet<SDValue, 8> Values;
5417   for (unsigned i = 0; i < NumElems; ++i) {
5418     SDValue Elt = Op.getOperand(i);
5419     if (Elt.getOpcode() == ISD::UNDEF)
5420       continue;
5421     Values.insert(Elt);
5422     if (Elt.getOpcode() != ISD::Constant &&
5423         Elt.getOpcode() != ISD::ConstantFP)
5424       IsAllConstants = false;
5425     if (X86::isZeroNode(Elt))
5426       NumZero++;
5427     else {
5428       NonZeros |= (1 << i);
5429       NumNonZero++;
5430     }
5431   }
5432
5433   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5434   if (NumNonZero == 0)
5435     return DAG.getUNDEF(VT);
5436
5437   // Special case for single non-zero, non-undef, element.
5438   if (NumNonZero == 1) {
5439     unsigned Idx = countTrailingZeros(NonZeros);
5440     SDValue Item = Op.getOperand(Idx);
5441
5442     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5443     // the value are obviously zero, truncate the value to i32 and do the
5444     // insertion that way.  Only do this if the value is non-constant or if the
5445     // value is a constant being inserted into element 0.  It is cheaper to do
5446     // a constant pool load than it is to do a movd + shuffle.
5447     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5448         (!IsAllConstants || Idx == 0)) {
5449       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5450         // Handle SSE only.
5451         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5452         EVT VecVT = MVT::v4i32;
5453         unsigned VecElts = 4;
5454
5455         // Truncate the value (which may itself be a constant) to i32, and
5456         // convert it to a vector with movd (S2V+shuffle to zero extend).
5457         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5458         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5459         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5460
5461         // Now we have our 32-bit value zero extended in the low element of
5462         // a vector.  If Idx != 0, swizzle it into place.
5463         if (Idx != 0) {
5464           SmallVector<int, 4> Mask;
5465           Mask.push_back(Idx);
5466           for (unsigned i = 1; i != VecElts; ++i)
5467             Mask.push_back(i);
5468           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5469                                       &Mask[0]);
5470         }
5471         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5472       }
5473     }
5474
5475     // If we have a constant or non-constant insertion into the low element of
5476     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5477     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5478     // depending on what the source datatype is.
5479     if (Idx == 0) {
5480       if (NumZero == 0)
5481         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5482
5483       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5484           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5485         if (VT.is256BitVector()) {
5486           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5487           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5488                              Item, DAG.getIntPtrConstant(0));
5489         }
5490         assert(VT.is128BitVector() && "Expected an SSE value type!");
5491         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5492         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5493         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5494       }
5495
5496       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5497         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5498         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5499         if (VT.is256BitVector()) {
5500           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5501           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5502         } else {
5503           assert(VT.is128BitVector() && "Expected an SSE value type!");
5504           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5505         }
5506         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5507       }
5508     }
5509
5510     // Is it a vector logical left shift?
5511     if (NumElems == 2 && Idx == 1 &&
5512         X86::isZeroNode(Op.getOperand(0)) &&
5513         !X86::isZeroNode(Op.getOperand(1))) {
5514       unsigned NumBits = VT.getSizeInBits();
5515       return getVShift(true, VT,
5516                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5517                                    VT, Op.getOperand(1)),
5518                        NumBits/2, DAG, *this, dl);
5519     }
5520
5521     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5522       return SDValue();
5523
5524     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5525     // is a non-constant being inserted into an element other than the low one,
5526     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5527     // movd/movss) to move this into the low element, then shuffle it into
5528     // place.
5529     if (EVTBits == 32) {
5530       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5531
5532       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5533       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5534       SmallVector<int, 8> MaskVec;
5535       for (unsigned i = 0; i != NumElems; ++i)
5536         MaskVec.push_back(i == Idx ? 0 : 1);
5537       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5538     }
5539   }
5540
5541   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5542   if (Values.size() == 1) {
5543     if (EVTBits == 32) {
5544       // Instead of a shuffle like this:
5545       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5546       // Check if it's possible to issue this instead.
5547       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5548       unsigned Idx = countTrailingZeros(NonZeros);
5549       SDValue Item = Op.getOperand(Idx);
5550       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5551         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5552     }
5553     return SDValue();
5554   }
5555
5556   // A vector full of immediates; various special cases are already
5557   // handled, so this is best done with a single constant-pool load.
5558   if (IsAllConstants)
5559     return SDValue();
5560
5561   // For AVX-length vectors, build the individual 128-bit pieces and use
5562   // shuffles to put them in place.
5563   if (VT.is256BitVector()) {
5564     SmallVector<SDValue, 32> V;
5565     for (unsigned i = 0; i != NumElems; ++i)
5566       V.push_back(Op.getOperand(i));
5567
5568     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5569
5570     // Build both the lower and upper subvector.
5571     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5572     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5573                                 NumElems/2);
5574
5575     // Recreate the wider vector with the lower and upper part.
5576     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5577   }
5578
5579   // Let legalizer expand 2-wide build_vectors.
5580   if (EVTBits == 64) {
5581     if (NumNonZero == 1) {
5582       // One half is zero or undef.
5583       unsigned Idx = countTrailingZeros(NonZeros);
5584       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5585                                  Op.getOperand(Idx));
5586       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5587     }
5588     return SDValue();
5589   }
5590
5591   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5592   if (EVTBits == 8 && NumElems == 16) {
5593     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5594                                         Subtarget, *this);
5595     if (V.getNode()) return V;
5596   }
5597
5598   if (EVTBits == 16 && NumElems == 8) {
5599     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5600                                       Subtarget, *this);
5601     if (V.getNode()) return V;
5602   }
5603
5604   // If element VT is == 32 bits, turn it into a number of shuffles.
5605   SmallVector<SDValue, 8> V(NumElems);
5606   if (NumElems == 4 && NumZero > 0) {
5607     for (unsigned i = 0; i < 4; ++i) {
5608       bool isZero = !(NonZeros & (1 << i));
5609       if (isZero)
5610         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5611       else
5612         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5613     }
5614
5615     for (unsigned i = 0; i < 2; ++i) {
5616       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5617         default: break;
5618         case 0:
5619           V[i] = V[i*2];  // Must be a zero vector.
5620           break;
5621         case 1:
5622           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5623           break;
5624         case 2:
5625           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5626           break;
5627         case 3:
5628           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5629           break;
5630       }
5631     }
5632
5633     bool Reverse1 = (NonZeros & 0x3) == 2;
5634     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5635     int MaskVec[] = {
5636       Reverse1 ? 1 : 0,
5637       Reverse1 ? 0 : 1,
5638       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5639       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5640     };
5641     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5642   }
5643
5644   if (Values.size() > 1 && VT.is128BitVector()) {
5645     // Check for a build vector of consecutive loads.
5646     for (unsigned i = 0; i < NumElems; ++i)
5647       V[i] = Op.getOperand(i);
5648
5649     // Check for elements which are consecutive loads.
5650     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5651     if (LD.getNode())
5652       return LD;
5653
5654     // Check for a build vector from mostly shuffle plus few inserting.
5655     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5656     if (Sh.getNode())
5657       return Sh;
5658
5659     // For SSE 4.1, use insertps to put the high elements into the low element.
5660     if (getSubtarget()->hasSSE41()) {
5661       SDValue Result;
5662       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5663         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5664       else
5665         Result = DAG.getUNDEF(VT);
5666
5667       for (unsigned i = 1; i < NumElems; ++i) {
5668         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5669         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5670                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5671       }
5672       return Result;
5673     }
5674
5675     // Otherwise, expand into a number of unpckl*, start by extending each of
5676     // our (non-undef) elements to the full vector width with the element in the
5677     // bottom slot of the vector (which generates no code for SSE).
5678     for (unsigned i = 0; i < NumElems; ++i) {
5679       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5680         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5681       else
5682         V[i] = DAG.getUNDEF(VT);
5683     }
5684
5685     // Next, we iteratively mix elements, e.g. for v4f32:
5686     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5687     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5688     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5689     unsigned EltStride = NumElems >> 1;
5690     while (EltStride != 0) {
5691       for (unsigned i = 0; i < EltStride; ++i) {
5692         // If V[i+EltStride] is undef and this is the first round of mixing,
5693         // then it is safe to just drop this shuffle: V[i] is already in the
5694         // right place, the one element (since it's the first round) being
5695         // inserted as undef can be dropped.  This isn't safe for successive
5696         // rounds because they will permute elements within both vectors.
5697         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5698             EltStride == NumElems/2)
5699           continue;
5700
5701         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5702       }
5703       EltStride >>= 1;
5704     }
5705     return V[0];
5706   }
5707   return SDValue();
5708 }
5709
5710 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5711 // to create 256-bit vectors from two other 128-bit ones.
5712 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5713   SDLoc dl(Op);
5714   MVT ResVT = Op.getValueType().getSimpleVT();
5715
5716   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5717
5718   SDValue V1 = Op.getOperand(0);
5719   SDValue V2 = Op.getOperand(1);
5720   unsigned NumElems = ResVT.getVectorNumElements();
5721
5722   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5723 }
5724
5725 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5726   assert(Op.getNumOperands() == 2);
5727
5728   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5729   // from two other 128-bit ones.
5730   return LowerAVXCONCAT_VECTORS(Op, DAG);
5731 }
5732
5733 // Try to lower a shuffle node into a simple blend instruction.
5734 static SDValue
5735 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5736                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5737   SDValue V1 = SVOp->getOperand(0);
5738   SDValue V2 = SVOp->getOperand(1);
5739   SDLoc dl(SVOp);
5740   MVT VT = SVOp->getValueType(0).getSimpleVT();
5741   MVT EltVT = VT.getVectorElementType();
5742   unsigned NumElems = VT.getVectorNumElements();
5743
5744   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5745     return SDValue();
5746   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5747     return SDValue();
5748
5749   // Check the mask for BLEND and build the value.
5750   unsigned MaskValue = 0;
5751   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5752   unsigned NumLanes = (NumElems-1)/8 + 1;
5753   unsigned NumElemsInLane = NumElems / NumLanes;
5754
5755   // Blend for v16i16 should be symetric for the both lanes.
5756   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5757
5758     int SndLaneEltIdx = (NumLanes == 2) ?
5759       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5760     int EltIdx = SVOp->getMaskElt(i);
5761
5762     if ((EltIdx < 0 || EltIdx == (int)i) &&
5763         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5764       continue;
5765
5766     if (((unsigned)EltIdx == (i + NumElems)) &&
5767         (SndLaneEltIdx < 0 ||
5768          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5769       MaskValue |= (1<<i);
5770     else
5771       return SDValue();
5772   }
5773
5774   // Convert i32 vectors to floating point if it is not AVX2.
5775   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5776   MVT BlendVT = VT;
5777   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5778     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5779                                NumElems);
5780     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5781     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5782   }
5783
5784   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5785                             DAG.getConstant(MaskValue, MVT::i32));
5786   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5787 }
5788
5789 // v8i16 shuffles - Prefer shuffles in the following order:
5790 // 1. [all]   pshuflw, pshufhw, optional move
5791 // 2. [ssse3] 1 x pshufb
5792 // 3. [ssse3] 2 x pshufb + 1 x por
5793 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5794 static SDValue
5795 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5796                          SelectionDAG &DAG) {
5797   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5798   SDValue V1 = SVOp->getOperand(0);
5799   SDValue V2 = SVOp->getOperand(1);
5800   SDLoc dl(SVOp);
5801   SmallVector<int, 8> MaskVals;
5802
5803   // Determine if more than 1 of the words in each of the low and high quadwords
5804   // of the result come from the same quadword of one of the two inputs.  Undef
5805   // mask values count as coming from any quadword, for better codegen.
5806   unsigned LoQuad[] = { 0, 0, 0, 0 };
5807   unsigned HiQuad[] = { 0, 0, 0, 0 };
5808   std::bitset<4> InputQuads;
5809   for (unsigned i = 0; i < 8; ++i) {
5810     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5811     int EltIdx = SVOp->getMaskElt(i);
5812     MaskVals.push_back(EltIdx);
5813     if (EltIdx < 0) {
5814       ++Quad[0];
5815       ++Quad[1];
5816       ++Quad[2];
5817       ++Quad[3];
5818       continue;
5819     }
5820     ++Quad[EltIdx / 4];
5821     InputQuads.set(EltIdx / 4);
5822   }
5823
5824   int BestLoQuad = -1;
5825   unsigned MaxQuad = 1;
5826   for (unsigned i = 0; i < 4; ++i) {
5827     if (LoQuad[i] > MaxQuad) {
5828       BestLoQuad = i;
5829       MaxQuad = LoQuad[i];
5830     }
5831   }
5832
5833   int BestHiQuad = -1;
5834   MaxQuad = 1;
5835   for (unsigned i = 0; i < 4; ++i) {
5836     if (HiQuad[i] > MaxQuad) {
5837       BestHiQuad = i;
5838       MaxQuad = HiQuad[i];
5839     }
5840   }
5841
5842   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5843   // of the two input vectors, shuffle them into one input vector so only a
5844   // single pshufb instruction is necessary. If There are more than 2 input
5845   // quads, disable the next transformation since it does not help SSSE3.
5846   bool V1Used = InputQuads[0] || InputQuads[1];
5847   bool V2Used = InputQuads[2] || InputQuads[3];
5848   if (Subtarget->hasSSSE3()) {
5849     if (InputQuads.count() == 2 && V1Used && V2Used) {
5850       BestLoQuad = InputQuads[0] ? 0 : 1;
5851       BestHiQuad = InputQuads[2] ? 2 : 3;
5852     }
5853     if (InputQuads.count() > 2) {
5854       BestLoQuad = -1;
5855       BestHiQuad = -1;
5856     }
5857   }
5858
5859   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5860   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5861   // words from all 4 input quadwords.
5862   SDValue NewV;
5863   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5864     int MaskV[] = {
5865       BestLoQuad < 0 ? 0 : BestLoQuad,
5866       BestHiQuad < 0 ? 1 : BestHiQuad
5867     };
5868     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5869                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5870                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5871     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5872
5873     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5874     // source words for the shuffle, to aid later transformations.
5875     bool AllWordsInNewV = true;
5876     bool InOrder[2] = { true, true };
5877     for (unsigned i = 0; i != 8; ++i) {
5878       int idx = MaskVals[i];
5879       if (idx != (int)i)
5880         InOrder[i/4] = false;
5881       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5882         continue;
5883       AllWordsInNewV = false;
5884       break;
5885     }
5886
5887     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5888     if (AllWordsInNewV) {
5889       for (int i = 0; i != 8; ++i) {
5890         int idx = MaskVals[i];
5891         if (idx < 0)
5892           continue;
5893         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5894         if ((idx != i) && idx < 4)
5895           pshufhw = false;
5896         if ((idx != i) && idx > 3)
5897           pshuflw = false;
5898       }
5899       V1 = NewV;
5900       V2Used = false;
5901       BestLoQuad = 0;
5902       BestHiQuad = 1;
5903     }
5904
5905     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5906     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5907     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5908       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5909       unsigned TargetMask = 0;
5910       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5911                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5912       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5913       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5914                              getShufflePSHUFLWImmediate(SVOp);
5915       V1 = NewV.getOperand(0);
5916       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5917     }
5918   }
5919
5920   // Promote splats to a larger type which usually leads to more efficient code.
5921   // FIXME: Is this true if pshufb is available?
5922   if (SVOp->isSplat())
5923     return PromoteSplat(SVOp, DAG);
5924
5925   // If we have SSSE3, and all words of the result are from 1 input vector,
5926   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5927   // is present, fall back to case 4.
5928   if (Subtarget->hasSSSE3()) {
5929     SmallVector<SDValue,16> pshufbMask;
5930
5931     // If we have elements from both input vectors, set the high bit of the
5932     // shuffle mask element to zero out elements that come from V2 in the V1
5933     // mask, and elements that come from V1 in the V2 mask, so that the two
5934     // results can be OR'd together.
5935     bool TwoInputs = V1Used && V2Used;
5936     for (unsigned i = 0; i != 8; ++i) {
5937       int EltIdx = MaskVals[i] * 2;
5938       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5939       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5940       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5941       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5942     }
5943     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5944     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5945                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5946                                  MVT::v16i8, &pshufbMask[0], 16));
5947     if (!TwoInputs)
5948       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5949
5950     // Calculate the shuffle mask for the second input, shuffle it, and
5951     // OR it with the first shuffled input.
5952     pshufbMask.clear();
5953     for (unsigned i = 0; i != 8; ++i) {
5954       int EltIdx = MaskVals[i] * 2;
5955       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5956       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5957       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5958       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5959     }
5960     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5961     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5962                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5963                                  MVT::v16i8, &pshufbMask[0], 16));
5964     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5965     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5966   }
5967
5968   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5969   // and update MaskVals with new element order.
5970   std::bitset<8> InOrder;
5971   if (BestLoQuad >= 0) {
5972     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5973     for (int i = 0; i != 4; ++i) {
5974       int idx = MaskVals[i];
5975       if (idx < 0) {
5976         InOrder.set(i);
5977       } else if ((idx / 4) == BestLoQuad) {
5978         MaskV[i] = idx & 3;
5979         InOrder.set(i);
5980       }
5981     }
5982     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5983                                 &MaskV[0]);
5984
5985     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5986       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5987       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5988                                   NewV.getOperand(0),
5989                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5990     }
5991   }
5992
5993   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5994   // and update MaskVals with the new element order.
5995   if (BestHiQuad >= 0) {
5996     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5997     for (unsigned i = 4; i != 8; ++i) {
5998       int idx = MaskVals[i];
5999       if (idx < 0) {
6000         InOrder.set(i);
6001       } else if ((idx / 4) == BestHiQuad) {
6002         MaskV[i] = (idx & 3) + 4;
6003         InOrder.set(i);
6004       }
6005     }
6006     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6007                                 &MaskV[0]);
6008
6009     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6010       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6011       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6012                                   NewV.getOperand(0),
6013                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6014     }
6015   }
6016
6017   // In case BestHi & BestLo were both -1, which means each quadword has a word
6018   // from each of the four input quadwords, calculate the InOrder bitvector now
6019   // before falling through to the insert/extract cleanup.
6020   if (BestLoQuad == -1 && BestHiQuad == -1) {
6021     NewV = V1;
6022     for (int i = 0; i != 8; ++i)
6023       if (MaskVals[i] < 0 || MaskVals[i] == i)
6024         InOrder.set(i);
6025   }
6026
6027   // The other elements are put in the right place using pextrw and pinsrw.
6028   for (unsigned i = 0; i != 8; ++i) {
6029     if (InOrder[i])
6030       continue;
6031     int EltIdx = MaskVals[i];
6032     if (EltIdx < 0)
6033       continue;
6034     SDValue ExtOp = (EltIdx < 8) ?
6035       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6036                   DAG.getIntPtrConstant(EltIdx)) :
6037       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6038                   DAG.getIntPtrConstant(EltIdx - 8));
6039     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6040                        DAG.getIntPtrConstant(i));
6041   }
6042   return NewV;
6043 }
6044
6045 // v16i8 shuffles - Prefer shuffles in the following order:
6046 // 1. [ssse3] 1 x pshufb
6047 // 2. [ssse3] 2 x pshufb + 1 x por
6048 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6049 static
6050 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6051                                  SelectionDAG &DAG,
6052                                  const X86TargetLowering &TLI) {
6053   SDValue V1 = SVOp->getOperand(0);
6054   SDValue V2 = SVOp->getOperand(1);
6055   SDLoc dl(SVOp);
6056   ArrayRef<int> MaskVals = SVOp->getMask();
6057
6058   // Promote splats to a larger type which usually leads to more efficient code.
6059   // FIXME: Is this true if pshufb is available?
6060   if (SVOp->isSplat())
6061     return PromoteSplat(SVOp, DAG);
6062
6063   // If we have SSSE3, case 1 is generated when all result bytes come from
6064   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6065   // present, fall back to case 3.
6066
6067   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6068   if (TLI.getSubtarget()->hasSSSE3()) {
6069     SmallVector<SDValue,16> pshufbMask;
6070
6071     // If all result elements are from one input vector, then only translate
6072     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6073     //
6074     // Otherwise, we have elements from both input vectors, and must zero out
6075     // elements that come from V2 in the first mask, and V1 in the second mask
6076     // so that we can OR them together.
6077     for (unsigned i = 0; i != 16; ++i) {
6078       int EltIdx = MaskVals[i];
6079       if (EltIdx < 0 || EltIdx >= 16)
6080         EltIdx = 0x80;
6081       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6082     }
6083     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6084                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6085                                  MVT::v16i8, &pshufbMask[0], 16));
6086
6087     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6088     // the 2nd operand if it's undefined or zero.
6089     if (V2.getOpcode() == ISD::UNDEF ||
6090         ISD::isBuildVectorAllZeros(V2.getNode()))
6091       return V1;
6092
6093     // Calculate the shuffle mask for the second input, shuffle it, and
6094     // OR it with the first shuffled input.
6095     pshufbMask.clear();
6096     for (unsigned i = 0; i != 16; ++i) {
6097       int EltIdx = MaskVals[i];
6098       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6099       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6100     }
6101     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6102                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6103                                  MVT::v16i8, &pshufbMask[0], 16));
6104     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6105   }
6106
6107   // No SSSE3 - Calculate in place words and then fix all out of place words
6108   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6109   // the 16 different words that comprise the two doublequadword input vectors.
6110   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6111   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6112   SDValue NewV = V1;
6113   for (int i = 0; i != 8; ++i) {
6114     int Elt0 = MaskVals[i*2];
6115     int Elt1 = MaskVals[i*2+1];
6116
6117     // This word of the result is all undef, skip it.
6118     if (Elt0 < 0 && Elt1 < 0)
6119       continue;
6120
6121     // This word of the result is already in the correct place, skip it.
6122     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6123       continue;
6124
6125     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6126     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6127     SDValue InsElt;
6128
6129     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6130     // using a single extract together, load it and store it.
6131     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6132       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6133                            DAG.getIntPtrConstant(Elt1 / 2));
6134       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6135                         DAG.getIntPtrConstant(i));
6136       continue;
6137     }
6138
6139     // If Elt1 is defined, extract it from the appropriate source.  If the
6140     // source byte is not also odd, shift the extracted word left 8 bits
6141     // otherwise clear the bottom 8 bits if we need to do an or.
6142     if (Elt1 >= 0) {
6143       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6144                            DAG.getIntPtrConstant(Elt1 / 2));
6145       if ((Elt1 & 1) == 0)
6146         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6147                              DAG.getConstant(8,
6148                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6149       else if (Elt0 >= 0)
6150         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6151                              DAG.getConstant(0xFF00, MVT::i16));
6152     }
6153     // If Elt0 is defined, extract it from the appropriate source.  If the
6154     // source byte is not also even, shift the extracted word right 8 bits. If
6155     // Elt1 was also defined, OR the extracted values together before
6156     // inserting them in the result.
6157     if (Elt0 >= 0) {
6158       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6159                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6160       if ((Elt0 & 1) != 0)
6161         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6162                               DAG.getConstant(8,
6163                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6164       else if (Elt1 >= 0)
6165         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6166                              DAG.getConstant(0x00FF, MVT::i16));
6167       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6168                          : InsElt0;
6169     }
6170     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6171                        DAG.getIntPtrConstant(i));
6172   }
6173   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6174 }
6175
6176 // v32i8 shuffles - Translate to VPSHUFB if possible.
6177 static
6178 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6179                                  const X86Subtarget *Subtarget,
6180                                  SelectionDAG &DAG) {
6181   MVT VT = SVOp->getValueType(0).getSimpleVT();
6182   SDValue V1 = SVOp->getOperand(0);
6183   SDValue V2 = SVOp->getOperand(1);
6184   SDLoc dl(SVOp);
6185   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6186
6187   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6188   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6189   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6190
6191   // VPSHUFB may be generated if
6192   // (1) one of input vector is undefined or zeroinitializer.
6193   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6194   // And (2) the mask indexes don't cross the 128-bit lane.
6195   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6196       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6197     return SDValue();
6198
6199   if (V1IsAllZero && !V2IsAllZero) {
6200     CommuteVectorShuffleMask(MaskVals, 32);
6201     V1 = V2;
6202   }
6203   SmallVector<SDValue, 32> pshufbMask;
6204   for (unsigned i = 0; i != 32; i++) {
6205     int EltIdx = MaskVals[i];
6206     if (EltIdx < 0 || EltIdx >= 32)
6207       EltIdx = 0x80;
6208     else {
6209       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6210         // Cross lane is not allowed.
6211         return SDValue();
6212       EltIdx &= 0xf;
6213     }
6214     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6215   }
6216   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6217                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6218                                   MVT::v32i8, &pshufbMask[0], 32));
6219 }
6220
6221 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6222 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6223 /// done when every pair / quad of shuffle mask elements point to elements in
6224 /// the right sequence. e.g.
6225 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6226 static
6227 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6228                                  SelectionDAG &DAG) {
6229   MVT VT = SVOp->getValueType(0).getSimpleVT();
6230   SDLoc dl(SVOp);
6231   unsigned NumElems = VT.getVectorNumElements();
6232   MVT NewVT;
6233   unsigned Scale;
6234   switch (VT.SimpleTy) {
6235   default: llvm_unreachable("Unexpected!");
6236   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6237   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6238   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6239   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6240   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6241   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6242   }
6243
6244   SmallVector<int, 8> MaskVec;
6245   for (unsigned i = 0; i != NumElems; i += Scale) {
6246     int StartIdx = -1;
6247     for (unsigned j = 0; j != Scale; ++j) {
6248       int EltIdx = SVOp->getMaskElt(i+j);
6249       if (EltIdx < 0)
6250         continue;
6251       if (StartIdx < 0)
6252         StartIdx = (EltIdx / Scale);
6253       if (EltIdx != (int)(StartIdx*Scale + j))
6254         return SDValue();
6255     }
6256     MaskVec.push_back(StartIdx);
6257   }
6258
6259   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6260   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6261   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6262 }
6263
6264 /// getVZextMovL - Return a zero-extending vector move low node.
6265 ///
6266 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6267                             SDValue SrcOp, SelectionDAG &DAG,
6268                             const X86Subtarget *Subtarget, SDLoc dl) {
6269   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6270     LoadSDNode *LD = NULL;
6271     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6272       LD = dyn_cast<LoadSDNode>(SrcOp);
6273     if (!LD) {
6274       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6275       // instead.
6276       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6277       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6278           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6279           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6280           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6281         // PR2108
6282         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6283         return DAG.getNode(ISD::BITCAST, dl, VT,
6284                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6285                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6286                                                    OpVT,
6287                                                    SrcOp.getOperand(0)
6288                                                           .getOperand(0))));
6289       }
6290     }
6291   }
6292
6293   return DAG.getNode(ISD::BITCAST, dl, VT,
6294                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6295                                  DAG.getNode(ISD::BITCAST, dl,
6296                                              OpVT, SrcOp)));
6297 }
6298
6299 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6300 /// which could not be matched by any known target speficic shuffle
6301 static SDValue
6302 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6303
6304   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6305   if (NewOp.getNode())
6306     return NewOp;
6307
6308   MVT VT = SVOp->getValueType(0).getSimpleVT();
6309
6310   unsigned NumElems = VT.getVectorNumElements();
6311   unsigned NumLaneElems = NumElems / 2;
6312
6313   SDLoc dl(SVOp);
6314   MVT EltVT = VT.getVectorElementType();
6315   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6316   SDValue Output[2];
6317
6318   SmallVector<int, 16> Mask;
6319   for (unsigned l = 0; l < 2; ++l) {
6320     // Build a shuffle mask for the output, discovering on the fly which
6321     // input vectors to use as shuffle operands (recorded in InputUsed).
6322     // If building a suitable shuffle vector proves too hard, then bail
6323     // out with UseBuildVector set.
6324     bool UseBuildVector = false;
6325     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6326     unsigned LaneStart = l * NumLaneElems;
6327     for (unsigned i = 0; i != NumLaneElems; ++i) {
6328       // The mask element.  This indexes into the input.
6329       int Idx = SVOp->getMaskElt(i+LaneStart);
6330       if (Idx < 0) {
6331         // the mask element does not index into any input vector.
6332         Mask.push_back(-1);
6333         continue;
6334       }
6335
6336       // The input vector this mask element indexes into.
6337       int Input = Idx / NumLaneElems;
6338
6339       // Turn the index into an offset from the start of the input vector.
6340       Idx -= Input * NumLaneElems;
6341
6342       // Find or create a shuffle vector operand to hold this input.
6343       unsigned OpNo;
6344       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6345         if (InputUsed[OpNo] == Input)
6346           // This input vector is already an operand.
6347           break;
6348         if (InputUsed[OpNo] < 0) {
6349           // Create a new operand for this input vector.
6350           InputUsed[OpNo] = Input;
6351           break;
6352         }
6353       }
6354
6355       if (OpNo >= array_lengthof(InputUsed)) {
6356         // More than two input vectors used!  Give up on trying to create a
6357         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6358         UseBuildVector = true;
6359         break;
6360       }
6361
6362       // Add the mask index for the new shuffle vector.
6363       Mask.push_back(Idx + OpNo * NumLaneElems);
6364     }
6365
6366     if (UseBuildVector) {
6367       SmallVector<SDValue, 16> SVOps;
6368       for (unsigned i = 0; i != NumLaneElems; ++i) {
6369         // The mask element.  This indexes into the input.
6370         int Idx = SVOp->getMaskElt(i+LaneStart);
6371         if (Idx < 0) {
6372           SVOps.push_back(DAG.getUNDEF(EltVT));
6373           continue;
6374         }
6375
6376         // The input vector this mask element indexes into.
6377         int Input = Idx / NumElems;
6378
6379         // Turn the index into an offset from the start of the input vector.
6380         Idx -= Input * NumElems;
6381
6382         // Extract the vector element by hand.
6383         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6384                                     SVOp->getOperand(Input),
6385                                     DAG.getIntPtrConstant(Idx)));
6386       }
6387
6388       // Construct the output using a BUILD_VECTOR.
6389       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6390                               SVOps.size());
6391     } else if (InputUsed[0] < 0) {
6392       // No input vectors were used! The result is undefined.
6393       Output[l] = DAG.getUNDEF(NVT);
6394     } else {
6395       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6396                                         (InputUsed[0] % 2) * NumLaneElems,
6397                                         DAG, dl);
6398       // If only one input was used, use an undefined vector for the other.
6399       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6400         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6401                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6402       // At least one input vector was used. Create a new shuffle vector.
6403       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6404     }
6405
6406     Mask.clear();
6407   }
6408
6409   // Concatenate the result back
6410   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6411 }
6412
6413 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6414 /// 4 elements, and match them with several different shuffle types.
6415 static SDValue
6416 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6417   SDValue V1 = SVOp->getOperand(0);
6418   SDValue V2 = SVOp->getOperand(1);
6419   SDLoc dl(SVOp);
6420   MVT VT = SVOp->getValueType(0).getSimpleVT();
6421
6422   assert(VT.is128BitVector() && "Unsupported vector size");
6423
6424   std::pair<int, int> Locs[4];
6425   int Mask1[] = { -1, -1, -1, -1 };
6426   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6427
6428   unsigned NumHi = 0;
6429   unsigned NumLo = 0;
6430   for (unsigned i = 0; i != 4; ++i) {
6431     int Idx = PermMask[i];
6432     if (Idx < 0) {
6433       Locs[i] = std::make_pair(-1, -1);
6434     } else {
6435       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6436       if (Idx < 4) {
6437         Locs[i] = std::make_pair(0, NumLo);
6438         Mask1[NumLo] = Idx;
6439         NumLo++;
6440       } else {
6441         Locs[i] = std::make_pair(1, NumHi);
6442         if (2+NumHi < 4)
6443           Mask1[2+NumHi] = Idx;
6444         NumHi++;
6445       }
6446     }
6447   }
6448
6449   if (NumLo <= 2 && NumHi <= 2) {
6450     // If no more than two elements come from either vector. This can be
6451     // implemented with two shuffles. First shuffle gather the elements.
6452     // The second shuffle, which takes the first shuffle as both of its
6453     // vector operands, put the elements into the right order.
6454     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6455
6456     int Mask2[] = { -1, -1, -1, -1 };
6457
6458     for (unsigned i = 0; i != 4; ++i)
6459       if (Locs[i].first != -1) {
6460         unsigned Idx = (i < 2) ? 0 : 4;
6461         Idx += Locs[i].first * 2 + Locs[i].second;
6462         Mask2[i] = Idx;
6463       }
6464
6465     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6466   }
6467
6468   if (NumLo == 3 || NumHi == 3) {
6469     // Otherwise, we must have three elements from one vector, call it X, and
6470     // one element from the other, call it Y.  First, use a shufps to build an
6471     // intermediate vector with the one element from Y and the element from X
6472     // that will be in the same half in the final destination (the indexes don't
6473     // matter). Then, use a shufps to build the final vector, taking the half
6474     // containing the element from Y from the intermediate, and the other half
6475     // from X.
6476     if (NumHi == 3) {
6477       // Normalize it so the 3 elements come from V1.
6478       CommuteVectorShuffleMask(PermMask, 4);
6479       std::swap(V1, V2);
6480     }
6481
6482     // Find the element from V2.
6483     unsigned HiIndex;
6484     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6485       int Val = PermMask[HiIndex];
6486       if (Val < 0)
6487         continue;
6488       if (Val >= 4)
6489         break;
6490     }
6491
6492     Mask1[0] = PermMask[HiIndex];
6493     Mask1[1] = -1;
6494     Mask1[2] = PermMask[HiIndex^1];
6495     Mask1[3] = -1;
6496     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6497
6498     if (HiIndex >= 2) {
6499       Mask1[0] = PermMask[0];
6500       Mask1[1] = PermMask[1];
6501       Mask1[2] = HiIndex & 1 ? 6 : 4;
6502       Mask1[3] = HiIndex & 1 ? 4 : 6;
6503       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6504     }
6505
6506     Mask1[0] = HiIndex & 1 ? 2 : 0;
6507     Mask1[1] = HiIndex & 1 ? 0 : 2;
6508     Mask1[2] = PermMask[2];
6509     Mask1[3] = PermMask[3];
6510     if (Mask1[2] >= 0)
6511       Mask1[2] += 4;
6512     if (Mask1[3] >= 0)
6513       Mask1[3] += 4;
6514     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6515   }
6516
6517   // Break it into (shuffle shuffle_hi, shuffle_lo).
6518   int LoMask[] = { -1, -1, -1, -1 };
6519   int HiMask[] = { -1, -1, -1, -1 };
6520
6521   int *MaskPtr = LoMask;
6522   unsigned MaskIdx = 0;
6523   unsigned LoIdx = 0;
6524   unsigned HiIdx = 2;
6525   for (unsigned i = 0; i != 4; ++i) {
6526     if (i == 2) {
6527       MaskPtr = HiMask;
6528       MaskIdx = 1;
6529       LoIdx = 0;
6530       HiIdx = 2;
6531     }
6532     int Idx = PermMask[i];
6533     if (Idx < 0) {
6534       Locs[i] = std::make_pair(-1, -1);
6535     } else if (Idx < 4) {
6536       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6537       MaskPtr[LoIdx] = Idx;
6538       LoIdx++;
6539     } else {
6540       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6541       MaskPtr[HiIdx] = Idx;
6542       HiIdx++;
6543     }
6544   }
6545
6546   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6547   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6548   int MaskOps[] = { -1, -1, -1, -1 };
6549   for (unsigned i = 0; i != 4; ++i)
6550     if (Locs[i].first != -1)
6551       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6552   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6553 }
6554
6555 static bool MayFoldVectorLoad(SDValue V) {
6556   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6557     V = V.getOperand(0);
6558
6559   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6560     V = V.getOperand(0);
6561   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6562       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6563     // BUILD_VECTOR (load), undef
6564     V = V.getOperand(0);
6565
6566   return MayFoldLoad(V);
6567 }
6568
6569 static
6570 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6571   EVT VT = Op.getValueType();
6572
6573   // Canonizalize to v2f64.
6574   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6575   return DAG.getNode(ISD::BITCAST, dl, VT,
6576                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6577                                           V1, DAG));
6578 }
6579
6580 static
6581 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6582                         bool HasSSE2) {
6583   SDValue V1 = Op.getOperand(0);
6584   SDValue V2 = Op.getOperand(1);
6585   EVT VT = Op.getValueType();
6586
6587   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6588
6589   if (HasSSE2 && VT == MVT::v2f64)
6590     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6591
6592   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6593   return DAG.getNode(ISD::BITCAST, dl, VT,
6594                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6595                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6596                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6597 }
6598
6599 static
6600 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6601   SDValue V1 = Op.getOperand(0);
6602   SDValue V2 = Op.getOperand(1);
6603   EVT VT = Op.getValueType();
6604
6605   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6606          "unsupported shuffle type");
6607
6608   if (V2.getOpcode() == ISD::UNDEF)
6609     V2 = V1;
6610
6611   // v4i32 or v4f32
6612   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6613 }
6614
6615 static
6616 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6617   SDValue V1 = Op.getOperand(0);
6618   SDValue V2 = Op.getOperand(1);
6619   EVT VT = Op.getValueType();
6620   unsigned NumElems = VT.getVectorNumElements();
6621
6622   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6623   // operand of these instructions is only memory, so check if there's a
6624   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6625   // same masks.
6626   bool CanFoldLoad = false;
6627
6628   // Trivial case, when V2 comes from a load.
6629   if (MayFoldVectorLoad(V2))
6630     CanFoldLoad = true;
6631
6632   // When V1 is a load, it can be folded later into a store in isel, example:
6633   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6634   //    turns into:
6635   //  (MOVLPSmr addr:$src1, VR128:$src2)
6636   // So, recognize this potential and also use MOVLPS or MOVLPD
6637   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6638     CanFoldLoad = true;
6639
6640   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6641   if (CanFoldLoad) {
6642     if (HasSSE2 && NumElems == 2)
6643       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6644
6645     if (NumElems == 4)
6646       // If we don't care about the second element, proceed to use movss.
6647       if (SVOp->getMaskElt(1) != -1)
6648         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6649   }
6650
6651   // movl and movlp will both match v2i64, but v2i64 is never matched by
6652   // movl earlier because we make it strict to avoid messing with the movlp load
6653   // folding logic (see the code above getMOVLP call). Match it here then,
6654   // this is horrible, but will stay like this until we move all shuffle
6655   // matching to x86 specific nodes. Note that for the 1st condition all
6656   // types are matched with movsd.
6657   if (HasSSE2) {
6658     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6659     // as to remove this logic from here, as much as possible
6660     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6661       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6662     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6663   }
6664
6665   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6666
6667   // Invert the operand order and use SHUFPS to match it.
6668   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6669                               getShuffleSHUFImmediate(SVOp), DAG);
6670 }
6671
6672 // Reduce a vector shuffle to zext.
6673 SDValue
6674 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6675   // PMOVZX is only available from SSE41.
6676   if (!Subtarget->hasSSE41())
6677     return SDValue();
6678
6679   EVT VT = Op.getValueType();
6680
6681   // Only AVX2 support 256-bit vector integer extending.
6682   if (!Subtarget->hasInt256() && VT.is256BitVector())
6683     return SDValue();
6684
6685   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6686   SDLoc DL(Op);
6687   SDValue V1 = Op.getOperand(0);
6688   SDValue V2 = Op.getOperand(1);
6689   unsigned NumElems = VT.getVectorNumElements();
6690
6691   // Extending is an unary operation and the element type of the source vector
6692   // won't be equal to or larger than i64.
6693   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6694       VT.getVectorElementType() == MVT::i64)
6695     return SDValue();
6696
6697   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6698   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6699   while ((1U << Shift) < NumElems) {
6700     if (SVOp->getMaskElt(1U << Shift) == 1)
6701       break;
6702     Shift += 1;
6703     // The maximal ratio is 8, i.e. from i8 to i64.
6704     if (Shift > 3)
6705       return SDValue();
6706   }
6707
6708   // Check the shuffle mask.
6709   unsigned Mask = (1U << Shift) - 1;
6710   for (unsigned i = 0; i != NumElems; ++i) {
6711     int EltIdx = SVOp->getMaskElt(i);
6712     if ((i & Mask) != 0 && EltIdx != -1)
6713       return SDValue();
6714     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6715       return SDValue();
6716   }
6717
6718   LLVMContext *Context = DAG.getContext();
6719   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6720   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6721   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6722
6723   if (!isTypeLegal(NVT))
6724     return SDValue();
6725
6726   // Simplify the operand as it's prepared to be fed into shuffle.
6727   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6728   if (V1.getOpcode() == ISD::BITCAST &&
6729       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6730       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6731       V1.getOperand(0)
6732         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6733     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6734     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6735     ConstantSDNode *CIdx =
6736       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6737     // If it's foldable, i.e. normal load with single use, we will let code
6738     // selection to fold it. Otherwise, we will short the conversion sequence.
6739     if (CIdx && CIdx->getZExtValue() == 0 &&
6740         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6741       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6742         // The "ext_vec_elt" node is wider than the result node.
6743         // In this case we should extract subvector from V.
6744         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6745         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6746         EVT FullVT = V.getValueType();
6747         EVT SubVecVT = EVT::getVectorVT(*Context,
6748                                         FullVT.getVectorElementType(),
6749                                         FullVT.getVectorNumElements()/Ratio);
6750         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6751                         DAG.getIntPtrConstant(0));
6752       }
6753       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6754     }
6755   }
6756
6757   return DAG.getNode(ISD::BITCAST, DL, VT,
6758                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6759 }
6760
6761 SDValue
6762 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6763   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6764   MVT VT = Op.getValueType().getSimpleVT();
6765   SDLoc dl(Op);
6766   SDValue V1 = Op.getOperand(0);
6767   SDValue V2 = Op.getOperand(1);
6768
6769   if (isZeroShuffle(SVOp))
6770     return getZeroVector(VT, Subtarget, DAG, dl);
6771
6772   // Handle splat operations
6773   if (SVOp->isSplat()) {
6774     // Use vbroadcast whenever the splat comes from a foldable load
6775     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6776     if (Broadcast.getNode())
6777       return Broadcast;
6778   }
6779
6780   // Check integer expanding shuffles.
6781   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6782   if (NewOp.getNode())
6783     return NewOp;
6784
6785   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6786   // do it!
6787   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6788       VT == MVT::v16i16 || VT == MVT::v32i8) {
6789     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6790     if (NewOp.getNode())
6791       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6792   } else if ((VT == MVT::v4i32 ||
6793              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6794     // FIXME: Figure out a cleaner way to do this.
6795     // Try to make use of movq to zero out the top part.
6796     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6797       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6798       if (NewOp.getNode()) {
6799         MVT NewVT = NewOp.getValueType().getSimpleVT();
6800         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6801                                NewVT, true, false))
6802           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6803                               DAG, Subtarget, dl);
6804       }
6805     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6806       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6807       if (NewOp.getNode()) {
6808         MVT NewVT = NewOp.getValueType().getSimpleVT();
6809         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6810           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6811                               DAG, Subtarget, dl);
6812       }
6813     }
6814   }
6815   return SDValue();
6816 }
6817
6818 SDValue
6819 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6820   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6821   SDValue V1 = Op.getOperand(0);
6822   SDValue V2 = Op.getOperand(1);
6823   MVT VT = Op.getValueType().getSimpleVT();
6824   SDLoc dl(Op);
6825   unsigned NumElems = VT.getVectorNumElements();
6826   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6827   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6828   bool V1IsSplat = false;
6829   bool V2IsSplat = false;
6830   bool HasSSE2 = Subtarget->hasSSE2();
6831   bool HasFp256    = Subtarget->hasFp256();
6832   bool HasInt256   = Subtarget->hasInt256();
6833   MachineFunction &MF = DAG.getMachineFunction();
6834   bool OptForSize = MF.getFunction()->getAttributes().
6835     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6836
6837   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6838
6839   if (V1IsUndef && V2IsUndef)
6840     return DAG.getUNDEF(VT);
6841
6842   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6843
6844   // Vector shuffle lowering takes 3 steps:
6845   //
6846   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6847   //    narrowing and commutation of operands should be handled.
6848   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6849   //    shuffle nodes.
6850   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6851   //    so the shuffle can be broken into other shuffles and the legalizer can
6852   //    try the lowering again.
6853   //
6854   // The general idea is that no vector_shuffle operation should be left to
6855   // be matched during isel, all of them must be converted to a target specific
6856   // node here.
6857
6858   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6859   // narrowing and commutation of operands should be handled. The actual code
6860   // doesn't include all of those, work in progress...
6861   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6862   if (NewOp.getNode())
6863     return NewOp;
6864
6865   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6866
6867   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6868   // unpckh_undef). Only use pshufd if speed is more important than size.
6869   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6870     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6871   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6872     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6873
6874   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6875       V2IsUndef && MayFoldVectorLoad(V1))
6876     return getMOVDDup(Op, dl, V1, DAG);
6877
6878   if (isMOVHLPS_v_undef_Mask(M, VT))
6879     return getMOVHighToLow(Op, dl, DAG);
6880
6881   // Use to match splats
6882   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6883       (VT == MVT::v2f64 || VT == MVT::v2i64))
6884     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6885
6886   if (isPSHUFDMask(M, VT)) {
6887     // The actual implementation will match the mask in the if above and then
6888     // during isel it can match several different instructions, not only pshufd
6889     // as its name says, sad but true, emulate the behavior for now...
6890     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6891       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6892
6893     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6894
6895     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6896       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6897
6898     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6899       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6900                                   DAG);
6901
6902     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6903                                 TargetMask, DAG);
6904   }
6905
6906   if (isPALIGNRMask(M, VT, Subtarget))
6907     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6908                                 getShufflePALIGNRImmediate(SVOp),
6909                                 DAG);
6910
6911   // Check if this can be converted into a logical shift.
6912   bool isLeft = false;
6913   unsigned ShAmt = 0;
6914   SDValue ShVal;
6915   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6916   if (isShift && ShVal.hasOneUse()) {
6917     // If the shifted value has multiple uses, it may be cheaper to use
6918     // v_set0 + movlhps or movhlps, etc.
6919     MVT EltVT = VT.getVectorElementType();
6920     ShAmt *= EltVT.getSizeInBits();
6921     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6922   }
6923
6924   if (isMOVLMask(M, VT)) {
6925     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6926       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6927     if (!isMOVLPMask(M, VT)) {
6928       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6929         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6930
6931       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6932         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6933     }
6934   }
6935
6936   // FIXME: fold these into legal mask.
6937   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6938     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6939
6940   if (isMOVHLPSMask(M, VT))
6941     return getMOVHighToLow(Op, dl, DAG);
6942
6943   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6944     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6945
6946   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6947     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6948
6949   if (isMOVLPMask(M, VT))
6950     return getMOVLP(Op, dl, DAG, HasSSE2);
6951
6952   if (ShouldXformToMOVHLPS(M, VT) ||
6953       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6954     return CommuteVectorShuffle(SVOp, DAG);
6955
6956   if (isShift) {
6957     // No better options. Use a vshldq / vsrldq.
6958     MVT EltVT = VT.getVectorElementType();
6959     ShAmt *= EltVT.getSizeInBits();
6960     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6961   }
6962
6963   bool Commuted = false;
6964   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6965   // 1,1,1,1 -> v8i16 though.
6966   V1IsSplat = isSplatVector(V1.getNode());
6967   V2IsSplat = isSplatVector(V2.getNode());
6968
6969   // Canonicalize the splat or undef, if present, to be on the RHS.
6970   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6971     CommuteVectorShuffleMask(M, NumElems);
6972     std::swap(V1, V2);
6973     std::swap(V1IsSplat, V2IsSplat);
6974     Commuted = true;
6975   }
6976
6977   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6978     // Shuffling low element of v1 into undef, just return v1.
6979     if (V2IsUndef)
6980       return V1;
6981     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6982     // the instruction selector will not match, so get a canonical MOVL with
6983     // swapped operands to undo the commute.
6984     return getMOVL(DAG, dl, VT, V2, V1);
6985   }
6986
6987   if (isUNPCKLMask(M, VT, HasInt256))
6988     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6989
6990   if (isUNPCKHMask(M, VT, HasInt256))
6991     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6992
6993   if (V2IsSplat) {
6994     // Normalize mask so all entries that point to V2 points to its first
6995     // element then try to match unpck{h|l} again. If match, return a
6996     // new vector_shuffle with the corrected mask.p
6997     SmallVector<int, 8> NewMask(M.begin(), M.end());
6998     NormalizeMask(NewMask, NumElems);
6999     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7000       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7001     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7002       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7003   }
7004
7005   if (Commuted) {
7006     // Commute is back and try unpck* again.
7007     // FIXME: this seems wrong.
7008     CommuteVectorShuffleMask(M, NumElems);
7009     std::swap(V1, V2);
7010     std::swap(V1IsSplat, V2IsSplat);
7011     Commuted = false;
7012
7013     if (isUNPCKLMask(M, VT, HasInt256))
7014       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7015
7016     if (isUNPCKHMask(M, VT, HasInt256))
7017       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7018   }
7019
7020   // Normalize the node to match x86 shuffle ops if needed
7021   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7022     return CommuteVectorShuffle(SVOp, DAG);
7023
7024   // The checks below are all present in isShuffleMaskLegal, but they are
7025   // inlined here right now to enable us to directly emit target specific
7026   // nodes, and remove one by one until they don't return Op anymore.
7027
7028   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7029       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7030     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7031       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7032   }
7033
7034   if (isPSHUFHWMask(M, VT, HasInt256))
7035     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7036                                 getShufflePSHUFHWImmediate(SVOp),
7037                                 DAG);
7038
7039   if (isPSHUFLWMask(M, VT, HasInt256))
7040     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7041                                 getShufflePSHUFLWImmediate(SVOp),
7042                                 DAG);
7043
7044   if (isSHUFPMask(M, VT, HasFp256))
7045     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7046                                 getShuffleSHUFImmediate(SVOp), DAG);
7047
7048   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7049     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7050   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7051     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7052
7053   //===--------------------------------------------------------------------===//
7054   // Generate target specific nodes for 128 or 256-bit shuffles only
7055   // supported in the AVX instruction set.
7056   //
7057
7058   // Handle VMOVDDUPY permutations
7059   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7060     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7061
7062   // Handle VPERMILPS/D* permutations
7063   if (isVPERMILPMask(M, VT, HasFp256)) {
7064     if (HasInt256 && VT == MVT::v8i32)
7065       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7066                                   getShuffleSHUFImmediate(SVOp), DAG);
7067     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7068                                 getShuffleSHUFImmediate(SVOp), DAG);
7069   }
7070
7071   // Handle VPERM2F128/VPERM2I128 permutations
7072   if (isVPERM2X128Mask(M, VT, HasFp256))
7073     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7074                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7075
7076   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7077   if (BlendOp.getNode())
7078     return BlendOp;
7079
7080   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7081     SmallVector<SDValue, 8> permclMask;
7082     for (unsigned i = 0; i != 8; ++i) {
7083       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7084     }
7085     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7086                                &permclMask[0], 8);
7087     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7088     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7089                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7090   }
7091
7092   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7093     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7094                                 getShuffleCLImmediate(SVOp), DAG);
7095
7096   //===--------------------------------------------------------------------===//
7097   // Since no target specific shuffle was selected for this generic one,
7098   // lower it into other known shuffles. FIXME: this isn't true yet, but
7099   // this is the plan.
7100   //
7101
7102   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7103   if (VT == MVT::v8i16) {
7104     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7105     if (NewOp.getNode())
7106       return NewOp;
7107   }
7108
7109   if (VT == MVT::v16i8) {
7110     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7111     if (NewOp.getNode())
7112       return NewOp;
7113   }
7114
7115   if (VT == MVT::v32i8) {
7116     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7117     if (NewOp.getNode())
7118       return NewOp;
7119   }
7120
7121   // Handle all 128-bit wide vectors with 4 elements, and match them with
7122   // several different shuffle types.
7123   if (NumElems == 4 && VT.is128BitVector())
7124     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7125
7126   // Handle general 256-bit shuffles
7127   if (VT.is256BitVector())
7128     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7129
7130   return SDValue();
7131 }
7132
7133 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7134   MVT VT = Op.getValueType().getSimpleVT();
7135   SDLoc dl(Op);
7136
7137   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7138     return SDValue();
7139
7140   if (VT.getSizeInBits() == 8) {
7141     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7142                                   Op.getOperand(0), Op.getOperand(1));
7143     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7144                                   DAG.getValueType(VT));
7145     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7146   }
7147
7148   if (VT.getSizeInBits() == 16) {
7149     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7150     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7151     if (Idx == 0)
7152       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7153                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7154                                      DAG.getNode(ISD::BITCAST, dl,
7155                                                  MVT::v4i32,
7156                                                  Op.getOperand(0)),
7157                                      Op.getOperand(1)));
7158     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7159                                   Op.getOperand(0), Op.getOperand(1));
7160     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7161                                   DAG.getValueType(VT));
7162     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7163   }
7164
7165   if (VT == MVT::f32) {
7166     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7167     // the result back to FR32 register. It's only worth matching if the
7168     // result has a single use which is a store or a bitcast to i32.  And in
7169     // the case of a store, it's not worth it if the index is a constant 0,
7170     // because a MOVSSmr can be used instead, which is smaller and faster.
7171     if (!Op.hasOneUse())
7172       return SDValue();
7173     SDNode *User = *Op.getNode()->use_begin();
7174     if ((User->getOpcode() != ISD::STORE ||
7175          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7176           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7177         (User->getOpcode() != ISD::BITCAST ||
7178          User->getValueType(0) != MVT::i32))
7179       return SDValue();
7180     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7181                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7182                                               Op.getOperand(0)),
7183                                               Op.getOperand(1));
7184     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7185   }
7186
7187   if (VT == MVT::i32 || VT == MVT::i64) {
7188     // ExtractPS/pextrq works with constant index.
7189     if (isa<ConstantSDNode>(Op.getOperand(1)))
7190       return Op;
7191   }
7192   return SDValue();
7193 }
7194
7195 SDValue
7196 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7197                                            SelectionDAG &DAG) const {
7198   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7199     return SDValue();
7200
7201   SDValue Vec = Op.getOperand(0);
7202   MVT VecVT = Vec.getValueType().getSimpleVT();
7203
7204   // If this is a 256-bit vector result, first extract the 128-bit vector and
7205   // then extract the element from the 128-bit vector.
7206   if (VecVT.is256BitVector()) {
7207     SDLoc dl(Op.getNode());
7208     unsigned NumElems = VecVT.getVectorNumElements();
7209     SDValue Idx = Op.getOperand(1);
7210     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7211
7212     // Get the 128-bit vector.
7213     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7214
7215     if (IdxVal >= NumElems/2)
7216       IdxVal -= NumElems/2;
7217     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7218                        DAG.getConstant(IdxVal, MVT::i32));
7219   }
7220
7221   assert(VecVT.is128BitVector() && "Unexpected vector length");
7222
7223   if (Subtarget->hasSSE41()) {
7224     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7225     if (Res.getNode())
7226       return Res;
7227   }
7228
7229   MVT VT = Op.getValueType().getSimpleVT();
7230   SDLoc dl(Op);
7231   // TODO: handle v16i8.
7232   if (VT.getSizeInBits() == 16) {
7233     SDValue Vec = Op.getOperand(0);
7234     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7235     if (Idx == 0)
7236       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7237                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7238                                      DAG.getNode(ISD::BITCAST, dl,
7239                                                  MVT::v4i32, Vec),
7240                                      Op.getOperand(1)));
7241     // Transform it so it match pextrw which produces a 32-bit result.
7242     MVT EltVT = MVT::i32;
7243     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7244                                   Op.getOperand(0), Op.getOperand(1));
7245     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7246                                   DAG.getValueType(VT));
7247     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7248   }
7249
7250   if (VT.getSizeInBits() == 32) {
7251     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7252     if (Idx == 0)
7253       return Op;
7254
7255     // SHUFPS the element to the lowest double word, then movss.
7256     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7257     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7258     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7259                                        DAG.getUNDEF(VVT), Mask);
7260     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7261                        DAG.getIntPtrConstant(0));
7262   }
7263
7264   if (VT.getSizeInBits() == 64) {
7265     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7266     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7267     //        to match extract_elt for f64.
7268     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7269     if (Idx == 0)
7270       return Op;
7271
7272     // UNPCKHPD the element to the lowest double word, then movsd.
7273     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7274     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7275     int Mask[2] = { 1, -1 };
7276     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7277     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7278                                        DAG.getUNDEF(VVT), Mask);
7279     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7280                        DAG.getIntPtrConstant(0));
7281   }
7282
7283   return SDValue();
7284 }
7285
7286 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7287   MVT VT = Op.getValueType().getSimpleVT();
7288   MVT EltVT = VT.getVectorElementType();
7289   SDLoc dl(Op);
7290
7291   SDValue N0 = Op.getOperand(0);
7292   SDValue N1 = Op.getOperand(1);
7293   SDValue N2 = Op.getOperand(2);
7294
7295   if (!VT.is128BitVector())
7296     return SDValue();
7297
7298   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7299       isa<ConstantSDNode>(N2)) {
7300     unsigned Opc;
7301     if (VT == MVT::v8i16)
7302       Opc = X86ISD::PINSRW;
7303     else if (VT == MVT::v16i8)
7304       Opc = X86ISD::PINSRB;
7305     else
7306       Opc = X86ISD::PINSRB;
7307
7308     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7309     // argument.
7310     if (N1.getValueType() != MVT::i32)
7311       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7312     if (N2.getValueType() != MVT::i32)
7313       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7314     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7315   }
7316
7317   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7318     // Bits [7:6] of the constant are the source select.  This will always be
7319     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7320     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7321     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7322     // Bits [5:4] of the constant are the destination select.  This is the
7323     //  value of the incoming immediate.
7324     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7325     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7326     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7327     // Create this as a scalar to vector..
7328     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7329     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7330   }
7331
7332   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7333     // PINSR* works with constant index.
7334     return Op;
7335   }
7336   return SDValue();
7337 }
7338
7339 SDValue
7340 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7341   MVT VT = Op.getValueType().getSimpleVT();
7342   MVT EltVT = VT.getVectorElementType();
7343
7344   SDLoc dl(Op);
7345   SDValue N0 = Op.getOperand(0);
7346   SDValue N1 = Op.getOperand(1);
7347   SDValue N2 = Op.getOperand(2);
7348
7349   // If this is a 256-bit vector result, first extract the 128-bit vector,
7350   // insert the element into the extracted half and then place it back.
7351   if (VT.is256BitVector()) {
7352     if (!isa<ConstantSDNode>(N2))
7353       return SDValue();
7354
7355     // Get the desired 128-bit vector half.
7356     unsigned NumElems = VT.getVectorNumElements();
7357     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7358     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7359
7360     // Insert the element into the desired half.
7361     bool Upper = IdxVal >= NumElems/2;
7362     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7363                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7364
7365     // Insert the changed part back to the 256-bit vector
7366     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7367   }
7368
7369   if (Subtarget->hasSSE41())
7370     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7371
7372   if (EltVT == MVT::i8)
7373     return SDValue();
7374
7375   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7376     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7377     // as its second argument.
7378     if (N1.getValueType() != MVT::i32)
7379       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7380     if (N2.getValueType() != MVT::i32)
7381       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7382     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7383   }
7384   return SDValue();
7385 }
7386
7387 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7388   LLVMContext *Context = DAG.getContext();
7389   SDLoc dl(Op);
7390   MVT OpVT = Op.getValueType().getSimpleVT();
7391
7392   // If this is a 256-bit vector result, first insert into a 128-bit
7393   // vector and then insert into the 256-bit vector.
7394   if (!OpVT.is128BitVector()) {
7395     // Insert into a 128-bit vector.
7396     EVT VT128 = EVT::getVectorVT(*Context,
7397                                  OpVT.getVectorElementType(),
7398                                  OpVT.getVectorNumElements() / 2);
7399
7400     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7401
7402     // Insert the 128-bit vector.
7403     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7404   }
7405
7406   if (OpVT == MVT::v1i64 &&
7407       Op.getOperand(0).getValueType() == MVT::i64)
7408     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7409
7410   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7411   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7412   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7413                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7414 }
7415
7416 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7417 // a simple subregister reference or explicit instructions to grab
7418 // upper bits of a vector.
7419 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7420                                       SelectionDAG &DAG) {
7421   if (Subtarget->hasFp256()) {
7422     SDLoc dl(Op.getNode());
7423     SDValue Vec = Op.getNode()->getOperand(0);
7424     SDValue Idx = Op.getNode()->getOperand(1);
7425
7426     if (Op.getNode()->getValueType(0).is128BitVector() &&
7427         Vec.getNode()->getValueType(0).is256BitVector() &&
7428         isa<ConstantSDNode>(Idx)) {
7429       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7430       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7431     }
7432   }
7433   return SDValue();
7434 }
7435
7436 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7437 // simple superregister reference or explicit instructions to insert
7438 // the upper bits of a vector.
7439 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7440                                      SelectionDAG &DAG) {
7441   if (Subtarget->hasFp256()) {
7442     SDLoc dl(Op.getNode());
7443     SDValue Vec = Op.getNode()->getOperand(0);
7444     SDValue SubVec = Op.getNode()->getOperand(1);
7445     SDValue Idx = Op.getNode()->getOperand(2);
7446
7447     if (Op.getNode()->getValueType(0).is256BitVector() &&
7448         SubVec.getNode()->getValueType(0).is128BitVector() &&
7449         isa<ConstantSDNode>(Idx)) {
7450       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7451       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7452     }
7453   }
7454   return SDValue();
7455 }
7456
7457 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7458 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7459 // one of the above mentioned nodes. It has to be wrapped because otherwise
7460 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7461 // be used to form addressing mode. These wrapped nodes will be selected
7462 // into MOV32ri.
7463 SDValue
7464 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7465   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7466
7467   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7468   // global base reg.
7469   unsigned char OpFlag = 0;
7470   unsigned WrapperKind = X86ISD::Wrapper;
7471   CodeModel::Model M = getTargetMachine().getCodeModel();
7472
7473   if (Subtarget->isPICStyleRIPRel() &&
7474       (M == CodeModel::Small || M == CodeModel::Kernel))
7475     WrapperKind = X86ISD::WrapperRIP;
7476   else if (Subtarget->isPICStyleGOT())
7477     OpFlag = X86II::MO_GOTOFF;
7478   else if (Subtarget->isPICStyleStubPIC())
7479     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7480
7481   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7482                                              CP->getAlignment(),
7483                                              CP->getOffset(), OpFlag);
7484   SDLoc DL(CP);
7485   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7486   // With PIC, the address is actually $g + Offset.
7487   if (OpFlag) {
7488     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7489                          DAG.getNode(X86ISD::GlobalBaseReg,
7490                                      SDLoc(), getPointerTy()),
7491                          Result);
7492   }
7493
7494   return Result;
7495 }
7496
7497 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7498   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7499
7500   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7501   // global base reg.
7502   unsigned char OpFlag = 0;
7503   unsigned WrapperKind = X86ISD::Wrapper;
7504   CodeModel::Model M = getTargetMachine().getCodeModel();
7505
7506   if (Subtarget->isPICStyleRIPRel() &&
7507       (M == CodeModel::Small || M == CodeModel::Kernel))
7508     WrapperKind = X86ISD::WrapperRIP;
7509   else if (Subtarget->isPICStyleGOT())
7510     OpFlag = X86II::MO_GOTOFF;
7511   else if (Subtarget->isPICStyleStubPIC())
7512     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7513
7514   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7515                                           OpFlag);
7516   SDLoc DL(JT);
7517   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7518
7519   // With PIC, the address is actually $g + Offset.
7520   if (OpFlag)
7521     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7522                          DAG.getNode(X86ISD::GlobalBaseReg,
7523                                      SDLoc(), getPointerTy()),
7524                          Result);
7525
7526   return Result;
7527 }
7528
7529 SDValue
7530 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7531   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7532
7533   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7534   // global base reg.
7535   unsigned char OpFlag = 0;
7536   unsigned WrapperKind = X86ISD::Wrapper;
7537   CodeModel::Model M = getTargetMachine().getCodeModel();
7538
7539   if (Subtarget->isPICStyleRIPRel() &&
7540       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7541     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7542       OpFlag = X86II::MO_GOTPCREL;
7543     WrapperKind = X86ISD::WrapperRIP;
7544   } else if (Subtarget->isPICStyleGOT()) {
7545     OpFlag = X86II::MO_GOT;
7546   } else if (Subtarget->isPICStyleStubPIC()) {
7547     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7548   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7549     OpFlag = X86II::MO_DARWIN_NONLAZY;
7550   }
7551
7552   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7553
7554   SDLoc DL(Op);
7555   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7556
7557   // With PIC, the address is actually $g + Offset.
7558   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7559       !Subtarget->is64Bit()) {
7560     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7561                          DAG.getNode(X86ISD::GlobalBaseReg,
7562                                      SDLoc(), getPointerTy()),
7563                          Result);
7564   }
7565
7566   // For symbols that require a load from a stub to get the address, emit the
7567   // load.
7568   if (isGlobalStubReference(OpFlag))
7569     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7570                          MachinePointerInfo::getGOT(), false, false, false, 0);
7571
7572   return Result;
7573 }
7574
7575 SDValue
7576 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7577   // Create the TargetBlockAddressAddress node.
7578   unsigned char OpFlags =
7579     Subtarget->ClassifyBlockAddressReference();
7580   CodeModel::Model M = getTargetMachine().getCodeModel();
7581   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7582   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7583   SDLoc dl(Op);
7584   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7585                                              OpFlags);
7586
7587   if (Subtarget->isPICStyleRIPRel() &&
7588       (M == CodeModel::Small || M == CodeModel::Kernel))
7589     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7590   else
7591     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7592
7593   // With PIC, the address is actually $g + Offset.
7594   if (isGlobalRelativeToPICBase(OpFlags)) {
7595     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7596                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7597                          Result);
7598   }
7599
7600   return Result;
7601 }
7602
7603 SDValue
7604 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7605                                       int64_t Offset, SelectionDAG &DAG) const {
7606   // Create the TargetGlobalAddress node, folding in the constant
7607   // offset if it is legal.
7608   unsigned char OpFlags =
7609     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7610   CodeModel::Model M = getTargetMachine().getCodeModel();
7611   SDValue Result;
7612   if (OpFlags == X86II::MO_NO_FLAG &&
7613       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7614     // A direct static reference to a global.
7615     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7616     Offset = 0;
7617   } else {
7618     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7619   }
7620
7621   if (Subtarget->isPICStyleRIPRel() &&
7622       (M == CodeModel::Small || M == CodeModel::Kernel))
7623     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7624   else
7625     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7626
7627   // With PIC, the address is actually $g + Offset.
7628   if (isGlobalRelativeToPICBase(OpFlags)) {
7629     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7630                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7631                          Result);
7632   }
7633
7634   // For globals that require a load from a stub to get the address, emit the
7635   // load.
7636   if (isGlobalStubReference(OpFlags))
7637     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7638                          MachinePointerInfo::getGOT(), false, false, false, 0);
7639
7640   // If there was a non-zero offset that we didn't fold, create an explicit
7641   // addition for it.
7642   if (Offset != 0)
7643     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7644                          DAG.getConstant(Offset, getPointerTy()));
7645
7646   return Result;
7647 }
7648
7649 SDValue
7650 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7651   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7652   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7653   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
7654 }
7655
7656 static SDValue
7657 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7658            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7659            unsigned char OperandFlags, bool LocalDynamic = false) {
7660   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7661   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7662   SDLoc dl(GA);
7663   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7664                                            GA->getValueType(0),
7665                                            GA->getOffset(),
7666                                            OperandFlags);
7667
7668   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7669                                            : X86ISD::TLSADDR;
7670
7671   if (InFlag) {
7672     SDValue Ops[] = { Chain,  TGA, *InFlag };
7673     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7674   } else {
7675     SDValue Ops[]  = { Chain, TGA };
7676     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7677   }
7678
7679   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7680   MFI->setAdjustsStack(true);
7681
7682   SDValue Flag = Chain.getValue(1);
7683   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7684 }
7685
7686 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7687 static SDValue
7688 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7689                                 const EVT PtrVT) {
7690   SDValue InFlag;
7691   SDLoc dl(GA);  // ? function entry point might be better
7692   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7693                                    DAG.getNode(X86ISD::GlobalBaseReg,
7694                                                SDLoc(), PtrVT), InFlag);
7695   InFlag = Chain.getValue(1);
7696
7697   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7698 }
7699
7700 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7701 static SDValue
7702 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7703                                 const EVT PtrVT) {
7704   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7705                     X86::RAX, X86II::MO_TLSGD);
7706 }
7707
7708 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7709                                            SelectionDAG &DAG,
7710                                            const EVT PtrVT,
7711                                            bool is64Bit) {
7712   SDLoc dl(GA);
7713
7714   // Get the start address of the TLS block for this module.
7715   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7716       .getInfo<X86MachineFunctionInfo>();
7717   MFI->incNumLocalDynamicTLSAccesses();
7718
7719   SDValue Base;
7720   if (is64Bit) {
7721     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7722                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7723   } else {
7724     SDValue InFlag;
7725     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7726         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
7727     InFlag = Chain.getValue(1);
7728     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7729                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7730   }
7731
7732   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7733   // of Base.
7734
7735   // Build x@dtpoff.
7736   unsigned char OperandFlags = X86II::MO_DTPOFF;
7737   unsigned WrapperKind = X86ISD::Wrapper;
7738   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7739                                            GA->getValueType(0),
7740                                            GA->getOffset(), OperandFlags);
7741   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7742
7743   // Add x@dtpoff with the base.
7744   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7745 }
7746
7747 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7748 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7749                                    const EVT PtrVT, TLSModel::Model model,
7750                                    bool is64Bit, bool isPIC) {
7751   SDLoc dl(GA);
7752
7753   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7754   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7755                                                          is64Bit ? 257 : 256));
7756
7757   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7758                                       DAG.getIntPtrConstant(0),
7759                                       MachinePointerInfo(Ptr),
7760                                       false, false, false, 0);
7761
7762   unsigned char OperandFlags = 0;
7763   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7764   // initialexec.
7765   unsigned WrapperKind = X86ISD::Wrapper;
7766   if (model == TLSModel::LocalExec) {
7767     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7768   } else if (model == TLSModel::InitialExec) {
7769     if (is64Bit) {
7770       OperandFlags = X86II::MO_GOTTPOFF;
7771       WrapperKind = X86ISD::WrapperRIP;
7772     } else {
7773       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7774     }
7775   } else {
7776     llvm_unreachable("Unexpected model");
7777   }
7778
7779   // emit "addl x@ntpoff,%eax" (local exec)
7780   // or "addl x@indntpoff,%eax" (initial exec)
7781   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7782   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7783                                            GA->getValueType(0),
7784                                            GA->getOffset(), OperandFlags);
7785   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7786
7787   if (model == TLSModel::InitialExec) {
7788     if (isPIC && !is64Bit) {
7789       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7790                           DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
7791                            Offset);
7792     }
7793
7794     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7795                          MachinePointerInfo::getGOT(), false, false, false,
7796                          0);
7797   }
7798
7799   // The address of the thread local variable is the add of the thread
7800   // pointer with the offset of the variable.
7801   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7802 }
7803
7804 SDValue
7805 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7806
7807   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7808   const GlobalValue *GV = GA->getGlobal();
7809
7810   if (Subtarget->isTargetELF()) {
7811     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7812
7813     switch (model) {
7814       case TLSModel::GeneralDynamic:
7815         if (Subtarget->is64Bit())
7816           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7817         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7818       case TLSModel::LocalDynamic:
7819         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7820                                            Subtarget->is64Bit());
7821       case TLSModel::InitialExec:
7822       case TLSModel::LocalExec:
7823         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7824                                    Subtarget->is64Bit(),
7825                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7826     }
7827     llvm_unreachable("Unknown TLS model.");
7828   }
7829
7830   if (Subtarget->isTargetDarwin()) {
7831     // Darwin only has one model of TLS.  Lower to that.
7832     unsigned char OpFlag = 0;
7833     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7834                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7835
7836     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7837     // global base reg.
7838     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7839                   !Subtarget->is64Bit();
7840     if (PIC32)
7841       OpFlag = X86II::MO_TLVP_PIC_BASE;
7842     else
7843       OpFlag = X86II::MO_TLVP;
7844     SDLoc DL(Op);
7845     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7846                                                 GA->getValueType(0),
7847                                                 GA->getOffset(), OpFlag);
7848     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7849
7850     // With PIC32, the address is actually $g + Offset.
7851     if (PIC32)
7852       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7853                            DAG.getNode(X86ISD::GlobalBaseReg,
7854                                        SDLoc(), getPointerTy()),
7855                            Offset);
7856
7857     // Lowering the machine isd will make sure everything is in the right
7858     // location.
7859     SDValue Chain = DAG.getEntryNode();
7860     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7861     SDValue Args[] = { Chain, Offset };
7862     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7863
7864     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7865     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7866     MFI->setAdjustsStack(true);
7867
7868     // And our return value (tls address) is in the standard call return value
7869     // location.
7870     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7871     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7872                               Chain.getValue(1));
7873   }
7874
7875   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7876     // Just use the implicit TLS architecture
7877     // Need to generate someting similar to:
7878     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7879     //                                  ; from TEB
7880     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7881     //   mov     rcx, qword [rdx+rcx*8]
7882     //   mov     eax, .tls$:tlsvar
7883     //   [rax+rcx] contains the address
7884     // Windows 64bit: gs:0x58
7885     // Windows 32bit: fs:__tls_array
7886
7887     // If GV is an alias then use the aliasee for determining
7888     // thread-localness.
7889     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7890       GV = GA->resolveAliasedGlobal(false);
7891     SDLoc dl(GA);
7892     SDValue Chain = DAG.getEntryNode();
7893
7894     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7895     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7896     // use its literal value of 0x2C.
7897     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7898                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7899                                                              256)
7900                                         : Type::getInt32PtrTy(*DAG.getContext(),
7901                                                               257));
7902
7903     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7904       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7905         DAG.getExternalSymbol("_tls_array", getPointerTy()));
7906
7907     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7908                                         MachinePointerInfo(Ptr),
7909                                         false, false, false, 0);
7910
7911     // Load the _tls_index variable
7912     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7913     if (Subtarget->is64Bit())
7914       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7915                            IDX, MachinePointerInfo(), MVT::i32,
7916                            false, false, 0);
7917     else
7918       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7919                         false, false, false, 0);
7920
7921     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7922                                     getPointerTy());
7923     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7924
7925     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7926     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7927                       false, false, false, 0);
7928
7929     // Get the offset of start of .tls section
7930     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7931                                              GA->getValueType(0),
7932                                              GA->getOffset(), X86II::MO_SECREL);
7933     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7934
7935     // The address of the thread local variable is the add of the thread
7936     // pointer with the offset of the variable.
7937     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7938   }
7939
7940   llvm_unreachable("TLS not implemented for this target.");
7941 }
7942
7943 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7944 /// and take a 2 x i32 value to shift plus a shift amount.
7945 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7946   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7947   EVT VT = Op.getValueType();
7948   unsigned VTBits = VT.getSizeInBits();
7949   SDLoc dl(Op);
7950   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7951   SDValue ShOpLo = Op.getOperand(0);
7952   SDValue ShOpHi = Op.getOperand(1);
7953   SDValue ShAmt  = Op.getOperand(2);
7954   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7955                                      DAG.getConstant(VTBits - 1, MVT::i8))
7956                        : DAG.getConstant(0, VT);
7957
7958   SDValue Tmp2, Tmp3;
7959   if (Op.getOpcode() == ISD::SHL_PARTS) {
7960     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7961     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7962   } else {
7963     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7964     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7965   }
7966
7967   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7968                                 DAG.getConstant(VTBits, MVT::i8));
7969   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7970                              AndNode, DAG.getConstant(0, MVT::i8));
7971
7972   SDValue Hi, Lo;
7973   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7974   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7975   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7976
7977   if (Op.getOpcode() == ISD::SHL_PARTS) {
7978     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7979     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7980   } else {
7981     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7982     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7983   }
7984
7985   SDValue Ops[2] = { Lo, Hi };
7986   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
7987 }
7988
7989 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7990                                            SelectionDAG &DAG) const {
7991   EVT SrcVT = Op.getOperand(0).getValueType();
7992
7993   if (SrcVT.isVector())
7994     return SDValue();
7995
7996   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7997          "Unknown SINT_TO_FP to lower!");
7998
7999   // These are really Legal; return the operand so the caller accepts it as
8000   // Legal.
8001   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8002     return Op;
8003   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8004       Subtarget->is64Bit()) {
8005     return Op;
8006   }
8007
8008   SDLoc dl(Op);
8009   unsigned Size = SrcVT.getSizeInBits()/8;
8010   MachineFunction &MF = DAG.getMachineFunction();
8011   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8012   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8013   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8014                                StackSlot,
8015                                MachinePointerInfo::getFixedStack(SSFI),
8016                                false, false, 0);
8017   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8018 }
8019
8020 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8021                                      SDValue StackSlot,
8022                                      SelectionDAG &DAG) const {
8023   // Build the FILD
8024   SDLoc DL(Op);
8025   SDVTList Tys;
8026   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8027   if (useSSE)
8028     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8029   else
8030     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8031
8032   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8033
8034   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8035   MachineMemOperand *MMO;
8036   if (FI) {
8037     int SSFI = FI->getIndex();
8038     MMO =
8039       DAG.getMachineFunction()
8040       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8041                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8042   } else {
8043     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8044     StackSlot = StackSlot.getOperand(1);
8045   }
8046   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8047   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8048                                            X86ISD::FILD, DL,
8049                                            Tys, Ops, array_lengthof(Ops),
8050                                            SrcVT, MMO);
8051
8052   if (useSSE) {
8053     Chain = Result.getValue(1);
8054     SDValue InFlag = Result.getValue(2);
8055
8056     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8057     // shouldn't be necessary except that RFP cannot be live across
8058     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8059     MachineFunction &MF = DAG.getMachineFunction();
8060     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8061     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8062     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8063     Tys = DAG.getVTList(MVT::Other);
8064     SDValue Ops[] = {
8065       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8066     };
8067     MachineMemOperand *MMO =
8068       DAG.getMachineFunction()
8069       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8070                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8071
8072     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8073                                     Ops, array_lengthof(Ops),
8074                                     Op.getValueType(), MMO);
8075     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8076                          MachinePointerInfo::getFixedStack(SSFI),
8077                          false, false, false, 0);
8078   }
8079
8080   return Result;
8081 }
8082
8083 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8084 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8085                                                SelectionDAG &DAG) const {
8086   // This algorithm is not obvious. Here it is what we're trying to output:
8087   /*
8088      movq       %rax,  %xmm0
8089      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8090      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8091      #ifdef __SSE3__
8092        haddpd   %xmm0, %xmm0
8093      #else
8094        pshufd   $0x4e, %xmm0, %xmm1
8095        addpd    %xmm1, %xmm0
8096      #endif
8097   */
8098
8099   SDLoc dl(Op);
8100   LLVMContext *Context = DAG.getContext();
8101
8102   // Build some magic constants.
8103   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8104   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8105   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8106
8107   SmallVector<Constant*,2> CV1;
8108   CV1.push_back(
8109     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8110                                       APInt(64, 0x4330000000000000ULL))));
8111   CV1.push_back(
8112     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8113                                       APInt(64, 0x4530000000000000ULL))));
8114   Constant *C1 = ConstantVector::get(CV1);
8115   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8116
8117   // Load the 64-bit value into an XMM register.
8118   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8119                             Op.getOperand(0));
8120   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8121                               MachinePointerInfo::getConstantPool(),
8122                               false, false, false, 16);
8123   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8124                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8125                               CLod0);
8126
8127   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8128                               MachinePointerInfo::getConstantPool(),
8129                               false, false, false, 16);
8130   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8131   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8132   SDValue Result;
8133
8134   if (Subtarget->hasSSE3()) {
8135     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8136     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8137   } else {
8138     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8139     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8140                                            S2F, 0x4E, DAG);
8141     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8142                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8143                          Sub);
8144   }
8145
8146   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8147                      DAG.getIntPtrConstant(0));
8148 }
8149
8150 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8151 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8152                                                SelectionDAG &DAG) const {
8153   SDLoc dl(Op);
8154   // FP constant to bias correct the final result.
8155   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8156                                    MVT::f64);
8157
8158   // Load the 32-bit value into an XMM register.
8159   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8160                              Op.getOperand(0));
8161
8162   // Zero out the upper parts of the register.
8163   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8164
8165   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8166                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8167                      DAG.getIntPtrConstant(0));
8168
8169   // Or the load with the bias.
8170   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8171                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8172                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8173                                                    MVT::v2f64, Load)),
8174                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8175                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8176                                                    MVT::v2f64, Bias)));
8177   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8178                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8179                    DAG.getIntPtrConstant(0));
8180
8181   // Subtract the bias.
8182   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8183
8184   // Handle final rounding.
8185   EVT DestVT = Op.getValueType();
8186
8187   if (DestVT.bitsLT(MVT::f64))
8188     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8189                        DAG.getIntPtrConstant(0));
8190   if (DestVT.bitsGT(MVT::f64))
8191     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8192
8193   // Handle final rounding.
8194   return Sub;
8195 }
8196
8197 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8198                                                SelectionDAG &DAG) const {
8199   SDValue N0 = Op.getOperand(0);
8200   EVT SVT = N0.getValueType();
8201   SDLoc dl(Op);
8202
8203   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8204           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8205          "Custom UINT_TO_FP is not supported!");
8206
8207   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8208                              SVT.getVectorNumElements());
8209   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8210                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8211 }
8212
8213 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8214                                            SelectionDAG &DAG) const {
8215   SDValue N0 = Op.getOperand(0);
8216   SDLoc dl(Op);
8217
8218   if (Op.getValueType().isVector())
8219     return lowerUINT_TO_FP_vec(Op, DAG);
8220
8221   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8222   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8223   // the optimization here.
8224   if (DAG.SignBitIsZero(N0))
8225     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8226
8227   EVT SrcVT = N0.getValueType();
8228   EVT DstVT = Op.getValueType();
8229   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8230     return LowerUINT_TO_FP_i64(Op, DAG);
8231   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8232     return LowerUINT_TO_FP_i32(Op, DAG);
8233   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8234     return SDValue();
8235
8236   // Make a 64-bit buffer, and use it to build an FILD.
8237   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8238   if (SrcVT == MVT::i32) {
8239     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8240     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8241                                      getPointerTy(), StackSlot, WordOff);
8242     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8243                                   StackSlot, MachinePointerInfo(),
8244                                   false, false, 0);
8245     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8246                                   OffsetSlot, MachinePointerInfo(),
8247                                   false, false, 0);
8248     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8249     return Fild;
8250   }
8251
8252   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8253   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8254                                StackSlot, MachinePointerInfo(),
8255                                false, false, 0);
8256   // For i64 source, we need to add the appropriate power of 2 if the input
8257   // was negative.  This is the same as the optimization in
8258   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8259   // we must be careful to do the computation in x87 extended precision, not
8260   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8261   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8262   MachineMemOperand *MMO =
8263     DAG.getMachineFunction()
8264     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8265                           MachineMemOperand::MOLoad, 8, 8);
8266
8267   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8268   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8269   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8270                                          array_lengthof(Ops), MVT::i64, MMO);
8271
8272   APInt FF(32, 0x5F800000ULL);
8273
8274   // Check whether the sign bit is set.
8275   SDValue SignSet = DAG.getSetCC(dl,
8276                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8277                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8278                                  ISD::SETLT);
8279
8280   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8281   SDValue FudgePtr = DAG.getConstantPool(
8282                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8283                                          getPointerTy());
8284
8285   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8286   SDValue Zero = DAG.getIntPtrConstant(0);
8287   SDValue Four = DAG.getIntPtrConstant(4);
8288   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8289                                Zero, Four);
8290   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8291
8292   // Load the value out, extending it from f32 to f80.
8293   // FIXME: Avoid the extend by constructing the right constant pool?
8294   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8295                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8296                                  MVT::f32, false, false, 4);
8297   // Extend everything to 80 bits to force it to be done on x87.
8298   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8299   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8300 }
8301
8302 std::pair<SDValue,SDValue>
8303 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8304                                     bool IsSigned, bool IsReplace) const {
8305   SDLoc DL(Op);
8306
8307   EVT DstTy = Op.getValueType();
8308
8309   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8310     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8311     DstTy = MVT::i64;
8312   }
8313
8314   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8315          DstTy.getSimpleVT() >= MVT::i16 &&
8316          "Unknown FP_TO_INT to lower!");
8317
8318   // These are really Legal.
8319   if (DstTy == MVT::i32 &&
8320       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8321     return std::make_pair(SDValue(), SDValue());
8322   if (Subtarget->is64Bit() &&
8323       DstTy == MVT::i64 &&
8324       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8325     return std::make_pair(SDValue(), SDValue());
8326
8327   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8328   // stack slot, or into the FTOL runtime function.
8329   MachineFunction &MF = DAG.getMachineFunction();
8330   unsigned MemSize = DstTy.getSizeInBits()/8;
8331   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8332   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8333
8334   unsigned Opc;
8335   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8336     Opc = X86ISD::WIN_FTOL;
8337   else
8338     switch (DstTy.getSimpleVT().SimpleTy) {
8339     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8340     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8341     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8342     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8343     }
8344
8345   SDValue Chain = DAG.getEntryNode();
8346   SDValue Value = Op.getOperand(0);
8347   EVT TheVT = Op.getOperand(0).getValueType();
8348   // FIXME This causes a redundant load/store if the SSE-class value is already
8349   // in memory, such as if it is on the callstack.
8350   if (isScalarFPTypeInSSEReg(TheVT)) {
8351     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8352     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8353                          MachinePointerInfo::getFixedStack(SSFI),
8354                          false, false, 0);
8355     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8356     SDValue Ops[] = {
8357       Chain, StackSlot, DAG.getValueType(TheVT)
8358     };
8359
8360     MachineMemOperand *MMO =
8361       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8362                               MachineMemOperand::MOLoad, MemSize, MemSize);
8363     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8364                                     array_lengthof(Ops), DstTy, MMO);
8365     Chain = Value.getValue(1);
8366     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8367     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8368   }
8369
8370   MachineMemOperand *MMO =
8371     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8372                             MachineMemOperand::MOStore, MemSize, MemSize);
8373
8374   if (Opc != X86ISD::WIN_FTOL) {
8375     // Build the FP_TO_INT*_IN_MEM
8376     SDValue Ops[] = { Chain, Value, StackSlot };
8377     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8378                                            Ops, array_lengthof(Ops), DstTy,
8379                                            MMO);
8380     return std::make_pair(FIST, StackSlot);
8381   } else {
8382     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8383       DAG.getVTList(MVT::Other, MVT::Glue),
8384       Chain, Value);
8385     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8386       MVT::i32, ftol.getValue(1));
8387     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8388       MVT::i32, eax.getValue(2));
8389     SDValue Ops[] = { eax, edx };
8390     SDValue pair = IsReplace
8391       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8392       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8393     return std::make_pair(pair, SDValue());
8394   }
8395 }
8396
8397 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8398                               const X86Subtarget *Subtarget) {
8399   MVT VT = Op->getValueType(0).getSimpleVT();
8400   SDValue In = Op->getOperand(0);
8401   MVT InVT = In.getValueType().getSimpleVT();
8402   SDLoc dl(Op);
8403
8404   // Optimize vectors in AVX mode:
8405   //
8406   //   v8i16 -> v8i32
8407   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8408   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8409   //   Concat upper and lower parts.
8410   //
8411   //   v4i32 -> v4i64
8412   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8413   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8414   //   Concat upper and lower parts.
8415   //
8416
8417   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8418       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8419     return SDValue();
8420
8421   if (Subtarget->hasInt256())
8422     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8423
8424   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8425   SDValue Undef = DAG.getUNDEF(InVT);
8426   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8427   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8428   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8429
8430   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8431                              VT.getVectorNumElements()/2);
8432
8433   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8434   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8435
8436   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8437 }
8438
8439 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8440                                            SelectionDAG &DAG) const {
8441   if (Subtarget->hasFp256()) {
8442     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8443     if (Res.getNode())
8444       return Res;
8445   }
8446
8447   return SDValue();
8448 }
8449 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8450                                             SelectionDAG &DAG) const {
8451   SDLoc DL(Op);
8452   MVT VT = Op.getValueType().getSimpleVT();
8453   SDValue In = Op.getOperand(0);
8454   MVT SVT = In.getValueType().getSimpleVT();
8455
8456   if (Subtarget->hasFp256()) {
8457     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8458     if (Res.getNode())
8459       return Res;
8460   }
8461
8462   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8463       VT.getVectorNumElements() != SVT.getVectorNumElements())
8464     return SDValue();
8465
8466   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8467
8468   // AVX2 has better support of integer extending.
8469   if (Subtarget->hasInt256())
8470     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8471
8472   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8473   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8474   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8475                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8476                                                 DAG.getUNDEF(MVT::v8i16),
8477                                                 &Mask[0]));
8478
8479   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8480 }
8481
8482 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8483   SDLoc DL(Op);
8484   MVT VT = Op.getValueType().getSimpleVT();
8485   SDValue In = Op.getOperand(0);
8486   MVT SVT = In.getValueType().getSimpleVT();
8487
8488   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8489     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8490     if (Subtarget->hasInt256()) {
8491       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8492       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8493       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8494                                 ShufMask);
8495       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8496                          DAG.getIntPtrConstant(0));
8497     }
8498
8499     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8500     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8501                                DAG.getIntPtrConstant(0));
8502     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8503                                DAG.getIntPtrConstant(2));
8504
8505     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8506     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8507
8508     // The PSHUFD mask:
8509     static const int ShufMask1[] = {0, 2, 0, 0};
8510     SDValue Undef = DAG.getUNDEF(VT);
8511     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8512     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8513
8514     // The MOVLHPS mask:
8515     static const int ShufMask2[] = {0, 1, 4, 5};
8516     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8517   }
8518
8519   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8520     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8521     if (Subtarget->hasInt256()) {
8522       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8523
8524       SmallVector<SDValue,32> pshufbMask;
8525       for (unsigned i = 0; i < 2; ++i) {
8526         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8527         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8528         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8529         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8530         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8531         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8532         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8533         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8534         for (unsigned j = 0; j < 8; ++j)
8535           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8536       }
8537       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8538                                &pshufbMask[0], 32);
8539       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8540       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8541
8542       static const int ShufMask[] = {0,  2,  -1,  -1};
8543       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8544                                 &ShufMask[0]);
8545       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8546                        DAG.getIntPtrConstant(0));
8547       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8548     }
8549
8550     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8551                                DAG.getIntPtrConstant(0));
8552
8553     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8554                                DAG.getIntPtrConstant(4));
8555
8556     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8557     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8558
8559     // The PSHUFB mask:
8560     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8561                                    -1, -1, -1, -1, -1, -1, -1, -1};
8562
8563     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8564     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8565     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8566
8567     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8568     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8569
8570     // The MOVLHPS Mask:
8571     static const int ShufMask2[] = {0, 1, 4, 5};
8572     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8573     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8574   }
8575
8576   // Handle truncation of V256 to V128 using shuffles.
8577   if (!VT.is128BitVector() || !SVT.is256BitVector())
8578     return SDValue();
8579
8580   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8581          "Invalid op");
8582   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8583
8584   unsigned NumElems = VT.getVectorNumElements();
8585   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8586                              NumElems * 2);
8587
8588   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8589   // Prepare truncation shuffle mask
8590   for (unsigned i = 0; i != NumElems; ++i)
8591     MaskVec[i] = i * 2;
8592   SDValue V = DAG.getVectorShuffle(NVT, DL,
8593                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8594                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8595   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8596                      DAG.getIntPtrConstant(0));
8597 }
8598
8599 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8600                                            SelectionDAG &DAG) const {
8601   MVT VT = Op.getValueType().getSimpleVT();
8602   if (VT.isVector()) {
8603     if (VT == MVT::v8i16)
8604       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8605                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8606                                      MVT::v8i32, Op.getOperand(0)));
8607     return SDValue();
8608   }
8609
8610   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8611     /*IsSigned=*/ true, /*IsReplace=*/ false);
8612   SDValue FIST = Vals.first, StackSlot = Vals.second;
8613   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8614   if (FIST.getNode() == 0) return Op;
8615
8616   if (StackSlot.getNode())
8617     // Load the result.
8618     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8619                        FIST, StackSlot, MachinePointerInfo(),
8620                        false, false, false, 0);
8621
8622   // The node is the result.
8623   return FIST;
8624 }
8625
8626 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8627                                            SelectionDAG &DAG) const {
8628   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8629     /*IsSigned=*/ false, /*IsReplace=*/ false);
8630   SDValue FIST = Vals.first, StackSlot = Vals.second;
8631   assert(FIST.getNode() && "Unexpected failure");
8632
8633   if (StackSlot.getNode())
8634     // Load the result.
8635     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8636                        FIST, StackSlot, MachinePointerInfo(),
8637                        false, false, false, 0);
8638
8639   // The node is the result.
8640   return FIST;
8641 }
8642
8643 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8644   SDLoc DL(Op);
8645   MVT VT = Op.getValueType().getSimpleVT();
8646   SDValue In = Op.getOperand(0);
8647   MVT SVT = In.getValueType().getSimpleVT();
8648
8649   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8650
8651   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8652                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8653                                  In, DAG.getUNDEF(SVT)));
8654 }
8655
8656 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8657   LLVMContext *Context = DAG.getContext();
8658   SDLoc dl(Op);
8659   MVT VT = Op.getValueType().getSimpleVT();
8660   MVT EltVT = VT;
8661   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8662   if (VT.isVector()) {
8663     EltVT = VT.getVectorElementType();
8664     NumElts = VT.getVectorNumElements();
8665   }
8666   Constant *C;
8667   if (EltVT == MVT::f64)
8668     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8669                                           APInt(64, ~(1ULL << 63))));
8670   else
8671     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8672                                           APInt(32, ~(1U << 31))));
8673   C = ConstantVector::getSplat(NumElts, C);
8674   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8675   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8676   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8677                              MachinePointerInfo::getConstantPool(),
8678                              false, false, false, Alignment);
8679   if (VT.isVector()) {
8680     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8681     return DAG.getNode(ISD::BITCAST, dl, VT,
8682                        DAG.getNode(ISD::AND, dl, ANDVT,
8683                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8684                                                Op.getOperand(0)),
8685                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8686   }
8687   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8688 }
8689
8690 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8691   LLVMContext *Context = DAG.getContext();
8692   SDLoc dl(Op);
8693   MVT VT = Op.getValueType().getSimpleVT();
8694   MVT EltVT = VT;
8695   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8696   if (VT.isVector()) {
8697     EltVT = VT.getVectorElementType();
8698     NumElts = VT.getVectorNumElements();
8699   }
8700   Constant *C;
8701   if (EltVT == MVT::f64)
8702     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8703                                           APInt(64, 1ULL << 63)));
8704   else
8705     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8706                                           APInt(32, 1U << 31)));
8707   C = ConstantVector::getSplat(NumElts, C);
8708   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8709   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8710   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8711                              MachinePointerInfo::getConstantPool(),
8712                              false, false, false, Alignment);
8713   if (VT.isVector()) {
8714     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8715     return DAG.getNode(ISD::BITCAST, dl, VT,
8716                        DAG.getNode(ISD::XOR, dl, XORVT,
8717                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8718                                                Op.getOperand(0)),
8719                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8720   }
8721
8722   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8723 }
8724
8725 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8726   LLVMContext *Context = DAG.getContext();
8727   SDValue Op0 = Op.getOperand(0);
8728   SDValue Op1 = Op.getOperand(1);
8729   SDLoc dl(Op);
8730   MVT VT = Op.getValueType().getSimpleVT();
8731   MVT SrcVT = Op1.getValueType().getSimpleVT();
8732
8733   // If second operand is smaller, extend it first.
8734   if (SrcVT.bitsLT(VT)) {
8735     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8736     SrcVT = VT;
8737   }
8738   // And if it is bigger, shrink it first.
8739   if (SrcVT.bitsGT(VT)) {
8740     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8741     SrcVT = VT;
8742   }
8743
8744   // At this point the operands and the result should have the same
8745   // type, and that won't be f80 since that is not custom lowered.
8746
8747   // First get the sign bit of second operand.
8748   SmallVector<Constant*,4> CV;
8749   if (SrcVT == MVT::f64) {
8750     const fltSemantics &Sem = APFloat::IEEEdouble;
8751     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8752     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8753   } else {
8754     const fltSemantics &Sem = APFloat::IEEEsingle;
8755     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8756     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8757     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8758     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8759   }
8760   Constant *C = ConstantVector::get(CV);
8761   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8762   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8763                               MachinePointerInfo::getConstantPool(),
8764                               false, false, false, 16);
8765   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8766
8767   // Shift sign bit right or left if the two operands have different types.
8768   if (SrcVT.bitsGT(VT)) {
8769     // Op0 is MVT::f32, Op1 is MVT::f64.
8770     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8771     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8772                           DAG.getConstant(32, MVT::i32));
8773     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8774     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8775                           DAG.getIntPtrConstant(0));
8776   }
8777
8778   // Clear first operand sign bit.
8779   CV.clear();
8780   if (VT == MVT::f64) {
8781     const fltSemantics &Sem = APFloat::IEEEdouble;
8782     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8783                                                    APInt(64, ~(1ULL << 63)))));
8784     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8785   } else {
8786     const fltSemantics &Sem = APFloat::IEEEsingle;
8787     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8788                                                    APInt(32, ~(1U << 31)))));
8789     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8790     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8791     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8792   }
8793   C = ConstantVector::get(CV);
8794   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8795   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8796                               MachinePointerInfo::getConstantPool(),
8797                               false, false, false, 16);
8798   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8799
8800   // Or the value with the sign bit.
8801   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8802 }
8803
8804 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8805   SDValue N0 = Op.getOperand(0);
8806   SDLoc dl(Op);
8807   MVT VT = Op.getValueType().getSimpleVT();
8808
8809   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8810   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8811                                   DAG.getConstant(1, VT));
8812   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8813 }
8814
8815 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8816 //
8817 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8818                                                   SelectionDAG &DAG) const {
8819   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8820
8821   if (!Subtarget->hasSSE41())
8822     return SDValue();
8823
8824   if (!Op->hasOneUse())
8825     return SDValue();
8826
8827   SDNode *N = Op.getNode();
8828   SDLoc DL(N);
8829
8830   SmallVector<SDValue, 8> Opnds;
8831   DenseMap<SDValue, unsigned> VecInMap;
8832   EVT VT = MVT::Other;
8833
8834   // Recognize a special case where a vector is casted into wide integer to
8835   // test all 0s.
8836   Opnds.push_back(N->getOperand(0));
8837   Opnds.push_back(N->getOperand(1));
8838
8839   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8840     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
8841     // BFS traverse all OR'd operands.
8842     if (I->getOpcode() == ISD::OR) {
8843       Opnds.push_back(I->getOperand(0));
8844       Opnds.push_back(I->getOperand(1));
8845       // Re-evaluate the number of nodes to be traversed.
8846       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8847       continue;
8848     }
8849
8850     // Quit if a non-EXTRACT_VECTOR_ELT
8851     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8852       return SDValue();
8853
8854     // Quit if without a constant index.
8855     SDValue Idx = I->getOperand(1);
8856     if (!isa<ConstantSDNode>(Idx))
8857       return SDValue();
8858
8859     SDValue ExtractedFromVec = I->getOperand(0);
8860     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8861     if (M == VecInMap.end()) {
8862       VT = ExtractedFromVec.getValueType();
8863       // Quit if not 128/256-bit vector.
8864       if (!VT.is128BitVector() && !VT.is256BitVector())
8865         return SDValue();
8866       // Quit if not the same type.
8867       if (VecInMap.begin() != VecInMap.end() &&
8868           VT != VecInMap.begin()->first.getValueType())
8869         return SDValue();
8870       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8871     }
8872     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8873   }
8874
8875   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8876          "Not extracted from 128-/256-bit vector.");
8877
8878   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8879   SmallVector<SDValue, 8> VecIns;
8880
8881   for (DenseMap<SDValue, unsigned>::const_iterator
8882         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8883     // Quit if not all elements are used.
8884     if (I->second != FullMask)
8885       return SDValue();
8886     VecIns.push_back(I->first);
8887   }
8888
8889   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8890
8891   // Cast all vectors into TestVT for PTEST.
8892   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8893     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8894
8895   // If more than one full vectors are evaluated, OR them first before PTEST.
8896   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8897     // Each iteration will OR 2 nodes and append the result until there is only
8898     // 1 node left, i.e. the final OR'd value of all vectors.
8899     SDValue LHS = VecIns[Slot];
8900     SDValue RHS = VecIns[Slot + 1];
8901     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8902   }
8903
8904   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8905                      VecIns.back(), VecIns.back());
8906 }
8907
8908 /// Emit nodes that will be selected as "test Op0,Op0", or something
8909 /// equivalent.
8910 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8911                                     SelectionDAG &DAG) const {
8912   SDLoc dl(Op);
8913
8914   // CF and OF aren't always set the way we want. Determine which
8915   // of these we need.
8916   bool NeedCF = false;
8917   bool NeedOF = false;
8918   switch (X86CC) {
8919   default: break;
8920   case X86::COND_A: case X86::COND_AE:
8921   case X86::COND_B: case X86::COND_BE:
8922     NeedCF = true;
8923     break;
8924   case X86::COND_G: case X86::COND_GE:
8925   case X86::COND_L: case X86::COND_LE:
8926   case X86::COND_O: case X86::COND_NO:
8927     NeedOF = true;
8928     break;
8929   }
8930
8931   // See if we can use the EFLAGS value from the operand instead of
8932   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8933   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8934   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8935     // Emit a CMP with 0, which is the TEST pattern.
8936     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8937                        DAG.getConstant(0, Op.getValueType()));
8938
8939   unsigned Opcode = 0;
8940   unsigned NumOperands = 0;
8941
8942   // Truncate operations may prevent the merge of the SETCC instruction
8943   // and the arithmetic intruction before it. Attempt to truncate the operands
8944   // of the arithmetic instruction and use a reduced bit-width instruction.
8945   bool NeedTruncation = false;
8946   SDValue ArithOp = Op;
8947   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8948     SDValue Arith = Op->getOperand(0);
8949     // Both the trunc and the arithmetic op need to have one user each.
8950     if (Arith->hasOneUse())
8951       switch (Arith.getOpcode()) {
8952         default: break;
8953         case ISD::ADD:
8954         case ISD::SUB:
8955         case ISD::AND:
8956         case ISD::OR:
8957         case ISD::XOR: {
8958           NeedTruncation = true;
8959           ArithOp = Arith;
8960         }
8961       }
8962   }
8963
8964   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8965   // which may be the result of a CAST.  We use the variable 'Op', which is the
8966   // non-casted variable when we check for possible users.
8967   switch (ArithOp.getOpcode()) {
8968   case ISD::ADD:
8969     // Due to an isel shortcoming, be conservative if this add is likely to be
8970     // selected as part of a load-modify-store instruction. When the root node
8971     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8972     // uses of other nodes in the match, such as the ADD in this case. This
8973     // leads to the ADD being left around and reselected, with the result being
8974     // two adds in the output.  Alas, even if none our users are stores, that
8975     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8976     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8977     // climbing the DAG back to the root, and it doesn't seem to be worth the
8978     // effort.
8979     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8980          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8981       if (UI->getOpcode() != ISD::CopyToReg &&
8982           UI->getOpcode() != ISD::SETCC &&
8983           UI->getOpcode() != ISD::STORE)
8984         goto default_case;
8985
8986     if (ConstantSDNode *C =
8987         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8988       // An add of one will be selected as an INC.
8989       if (C->getAPIntValue() == 1) {
8990         Opcode = X86ISD::INC;
8991         NumOperands = 1;
8992         break;
8993       }
8994
8995       // An add of negative one (subtract of one) will be selected as a DEC.
8996       if (C->getAPIntValue().isAllOnesValue()) {
8997         Opcode = X86ISD::DEC;
8998         NumOperands = 1;
8999         break;
9000       }
9001     }
9002
9003     // Otherwise use a regular EFLAGS-setting add.
9004     Opcode = X86ISD::ADD;
9005     NumOperands = 2;
9006     break;
9007   case ISD::AND: {
9008     // If the primary and result isn't used, don't bother using X86ISD::AND,
9009     // because a TEST instruction will be better.
9010     bool NonFlagUse = false;
9011     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9012            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9013       SDNode *User = *UI;
9014       unsigned UOpNo = UI.getOperandNo();
9015       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9016         // Look pass truncate.
9017         UOpNo = User->use_begin().getOperandNo();
9018         User = *User->use_begin();
9019       }
9020
9021       if (User->getOpcode() != ISD::BRCOND &&
9022           User->getOpcode() != ISD::SETCC &&
9023           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9024         NonFlagUse = true;
9025         break;
9026       }
9027     }
9028
9029     if (!NonFlagUse)
9030       break;
9031   }
9032     // FALL THROUGH
9033   case ISD::SUB:
9034   case ISD::OR:
9035   case ISD::XOR:
9036     // Due to the ISEL shortcoming noted above, be conservative if this op is
9037     // likely to be selected as part of a load-modify-store instruction.
9038     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9039            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9040       if (UI->getOpcode() == ISD::STORE)
9041         goto default_case;
9042
9043     // Otherwise use a regular EFLAGS-setting instruction.
9044     switch (ArithOp.getOpcode()) {
9045     default: llvm_unreachable("unexpected operator!");
9046     case ISD::SUB: Opcode = X86ISD::SUB; break;
9047     case ISD::XOR: Opcode = X86ISD::XOR; break;
9048     case ISD::AND: Opcode = X86ISD::AND; break;
9049     case ISD::OR: {
9050       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9051         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9052         if (EFLAGS.getNode())
9053           return EFLAGS;
9054       }
9055       Opcode = X86ISD::OR;
9056       break;
9057     }
9058     }
9059
9060     NumOperands = 2;
9061     break;
9062   case X86ISD::ADD:
9063   case X86ISD::SUB:
9064   case X86ISD::INC:
9065   case X86ISD::DEC:
9066   case X86ISD::OR:
9067   case X86ISD::XOR:
9068   case X86ISD::AND:
9069     return SDValue(Op.getNode(), 1);
9070   default:
9071   default_case:
9072     break;
9073   }
9074
9075   // If we found that truncation is beneficial, perform the truncation and
9076   // update 'Op'.
9077   if (NeedTruncation) {
9078     EVT VT = Op.getValueType();
9079     SDValue WideVal = Op->getOperand(0);
9080     EVT WideVT = WideVal.getValueType();
9081     unsigned ConvertedOp = 0;
9082     // Use a target machine opcode to prevent further DAGCombine
9083     // optimizations that may separate the arithmetic operations
9084     // from the setcc node.
9085     switch (WideVal.getOpcode()) {
9086       default: break;
9087       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9088       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9089       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9090       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9091       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9092     }
9093
9094     if (ConvertedOp) {
9095       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9096       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9097         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9098         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9099         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9100       }
9101     }
9102   }
9103
9104   if (Opcode == 0)
9105     // Emit a CMP with 0, which is the TEST pattern.
9106     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9107                        DAG.getConstant(0, Op.getValueType()));
9108
9109   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9110   SmallVector<SDValue, 4> Ops;
9111   for (unsigned i = 0; i != NumOperands; ++i)
9112     Ops.push_back(Op.getOperand(i));
9113
9114   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9115   DAG.ReplaceAllUsesWith(Op, New);
9116   return SDValue(New.getNode(), 1);
9117 }
9118
9119 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9120 /// equivalent.
9121 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9122                                    SelectionDAG &DAG) const {
9123   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9124     if (C->getAPIntValue() == 0)
9125       return EmitTest(Op0, X86CC, DAG);
9126
9127   SDLoc dl(Op0);
9128   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9129        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9130     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9131     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9132     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9133                               Op0, Op1);
9134     return SDValue(Sub.getNode(), 1);
9135   }
9136   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9137 }
9138
9139 /// Convert a comparison if required by the subtarget.
9140 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9141                                                  SelectionDAG &DAG) const {
9142   // If the subtarget does not support the FUCOMI instruction, floating-point
9143   // comparisons have to be converted.
9144   if (Subtarget->hasCMov() ||
9145       Cmp.getOpcode() != X86ISD::CMP ||
9146       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9147       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9148     return Cmp;
9149
9150   // The instruction selector will select an FUCOM instruction instead of
9151   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9152   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9153   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9154   SDLoc dl(Cmp);
9155   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9156   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9157   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9158                             DAG.getConstant(8, MVT::i8));
9159   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9160   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9161 }
9162
9163 static bool isAllOnes(SDValue V) {
9164   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9165   return C && C->isAllOnesValue();
9166 }
9167
9168 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9169 /// if it's possible.
9170 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9171                                      SDLoc dl, SelectionDAG &DAG) const {
9172   SDValue Op0 = And.getOperand(0);
9173   SDValue Op1 = And.getOperand(1);
9174   if (Op0.getOpcode() == ISD::TRUNCATE)
9175     Op0 = Op0.getOperand(0);
9176   if (Op1.getOpcode() == ISD::TRUNCATE)
9177     Op1 = Op1.getOperand(0);
9178
9179   SDValue LHS, RHS;
9180   if (Op1.getOpcode() == ISD::SHL)
9181     std::swap(Op0, Op1);
9182   if (Op0.getOpcode() == ISD::SHL) {
9183     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9184       if (And00C->getZExtValue() == 1) {
9185         // If we looked past a truncate, check that it's only truncating away
9186         // known zeros.
9187         unsigned BitWidth = Op0.getValueSizeInBits();
9188         unsigned AndBitWidth = And.getValueSizeInBits();
9189         if (BitWidth > AndBitWidth) {
9190           APInt Zeros, Ones;
9191           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9192           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9193             return SDValue();
9194         }
9195         LHS = Op1;
9196         RHS = Op0.getOperand(1);
9197       }
9198   } else if (Op1.getOpcode() == ISD::Constant) {
9199     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9200     uint64_t AndRHSVal = AndRHS->getZExtValue();
9201     SDValue AndLHS = Op0;
9202
9203     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9204       LHS = AndLHS.getOperand(0);
9205       RHS = AndLHS.getOperand(1);
9206     }
9207
9208     // Use BT if the immediate can't be encoded in a TEST instruction.
9209     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9210       LHS = AndLHS;
9211       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9212     }
9213   }
9214
9215   if (LHS.getNode()) {
9216     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9217     // instruction.  Since the shift amount is in-range-or-undefined, we know
9218     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9219     // the encoding for the i16 version is larger than the i32 version.
9220     // Also promote i16 to i32 for performance / code size reason.
9221     if (LHS.getValueType() == MVT::i8 ||
9222         LHS.getValueType() == MVT::i16)
9223       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9224
9225     // If the operand types disagree, extend the shift amount to match.  Since
9226     // BT ignores high bits (like shifts) we can use anyextend.
9227     if (LHS.getValueType() != RHS.getValueType())
9228       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9229
9230     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9231     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9232     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9233                        DAG.getConstant(Cond, MVT::i8), BT);
9234   }
9235
9236   return SDValue();
9237 }
9238
9239 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9240 // ones, and then concatenate the result back.
9241 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9242   MVT VT = Op.getValueType().getSimpleVT();
9243
9244   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9245          "Unsupported value type for operation");
9246
9247   unsigned NumElems = VT.getVectorNumElements();
9248   SDLoc dl(Op);
9249   SDValue CC = Op.getOperand(2);
9250
9251   // Extract the LHS vectors
9252   SDValue LHS = Op.getOperand(0);
9253   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9254   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9255
9256   // Extract the RHS vectors
9257   SDValue RHS = Op.getOperand(1);
9258   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9259   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9260
9261   // Issue the operation on the smaller types and concatenate the result back
9262   MVT EltVT = VT.getVectorElementType();
9263   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9264   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9265                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9266                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9267 }
9268
9269 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9270                            SelectionDAG &DAG) {
9271   SDValue Cond;
9272   SDValue Op0 = Op.getOperand(0);
9273   SDValue Op1 = Op.getOperand(1);
9274   SDValue CC = Op.getOperand(2);
9275   MVT VT = Op.getValueType().getSimpleVT();
9276   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9277   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9278   SDLoc dl(Op);
9279
9280   if (isFP) {
9281 #ifndef NDEBUG
9282     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9283     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9284 #endif
9285
9286     unsigned SSECC;
9287     bool Swap = false;
9288
9289     // SSE Condition code mapping:
9290     //  0 - EQ
9291     //  1 - LT
9292     //  2 - LE
9293     //  3 - UNORD
9294     //  4 - NEQ
9295     //  5 - NLT
9296     //  6 - NLE
9297     //  7 - ORD
9298     switch (SetCCOpcode) {
9299     default: llvm_unreachable("Unexpected SETCC condition");
9300     case ISD::SETOEQ:
9301     case ISD::SETEQ:  SSECC = 0; break;
9302     case ISD::SETOGT:
9303     case ISD::SETGT: Swap = true; // Fallthrough
9304     case ISD::SETLT:
9305     case ISD::SETOLT: SSECC = 1; break;
9306     case ISD::SETOGE:
9307     case ISD::SETGE: Swap = true; // Fallthrough
9308     case ISD::SETLE:
9309     case ISD::SETOLE: SSECC = 2; break;
9310     case ISD::SETUO:  SSECC = 3; break;
9311     case ISD::SETUNE:
9312     case ISD::SETNE:  SSECC = 4; break;
9313     case ISD::SETULE: Swap = true; // Fallthrough
9314     case ISD::SETUGE: SSECC = 5; break;
9315     case ISD::SETULT: Swap = true; // Fallthrough
9316     case ISD::SETUGT: SSECC = 6; break;
9317     case ISD::SETO:   SSECC = 7; break;
9318     case ISD::SETUEQ:
9319     case ISD::SETONE: SSECC = 8; break;
9320     }
9321     if (Swap)
9322       std::swap(Op0, Op1);
9323
9324     // In the two special cases we can't handle, emit two comparisons.
9325     if (SSECC == 8) {
9326       unsigned CC0, CC1;
9327       unsigned CombineOpc;
9328       if (SetCCOpcode == ISD::SETUEQ) {
9329         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9330       } else {
9331         assert(SetCCOpcode == ISD::SETONE);
9332         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9333       }
9334
9335       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9336                                  DAG.getConstant(CC0, MVT::i8));
9337       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9338                                  DAG.getConstant(CC1, MVT::i8));
9339       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9340     }
9341     // Handle all other FP comparisons here.
9342     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9343                        DAG.getConstant(SSECC, MVT::i8));
9344   }
9345
9346   // Break 256-bit integer vector compare into smaller ones.
9347   if (VT.is256BitVector() && !Subtarget->hasInt256())
9348     return Lower256IntVSETCC(Op, DAG);
9349
9350   // We are handling one of the integer comparisons here.  Since SSE only has
9351   // GT and EQ comparisons for integer, swapping operands and multiple
9352   // operations may be required for some comparisons.
9353   unsigned Opc;
9354   bool Swap = false, Invert = false, FlipSigns = false;
9355
9356   switch (SetCCOpcode) {
9357   default: llvm_unreachable("Unexpected SETCC condition");
9358   case ISD::SETNE:  Invert = true;
9359   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9360   case ISD::SETLT:  Swap = true;
9361   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9362   case ISD::SETGE:  Swap = true;
9363   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9364   case ISD::SETULT: Swap = true;
9365   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9366   case ISD::SETUGE: Swap = true;
9367   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9368   }
9369   if (Swap)
9370     std::swap(Op0, Op1);
9371
9372   // Check that the operation in question is available (most are plain SSE2,
9373   // but PCMPGTQ and PCMPEQQ have different requirements).
9374   if (VT == MVT::v2i64) {
9375     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9376       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9377
9378       // First cast everything to the right type.
9379       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9380       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9381
9382       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9383       // bits of the inputs before performing those operations. The lower
9384       // compare is always unsigned.
9385       SDValue SB;
9386       if (FlipSigns) {
9387         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9388       } else {
9389         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9390         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9391         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9392                          Sign, Zero, Sign, Zero);
9393       }
9394       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9395       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9396
9397       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9398       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9399       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9400
9401       // Create masks for only the low parts/high parts of the 64 bit integers.
9402       static const int MaskHi[] = { 1, 1, 3, 3 };
9403       static const int MaskLo[] = { 0, 0, 2, 2 };
9404       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9405       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9406       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9407
9408       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9409       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9410
9411       if (Invert)
9412         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9413
9414       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9415     }
9416
9417     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9418       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9419       // pcmpeqd + pshufd + pand.
9420       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9421
9422       // First cast everything to the right type.
9423       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9424       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9425
9426       // Do the compare.
9427       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9428
9429       // Make sure the lower and upper halves are both all-ones.
9430       static const int Mask[] = { 1, 0, 3, 2 };
9431       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9432       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9433
9434       if (Invert)
9435         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9436
9437       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9438     }
9439   }
9440
9441   // Since SSE has no unsigned integer comparisons, we need to flip the sign
9442   // bits of the inputs before performing those operations.
9443   if (FlipSigns) {
9444     EVT EltVT = VT.getVectorElementType();
9445     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9446     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9447     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9448   }
9449
9450   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9451
9452   // If the logical-not of the result is required, perform that now.
9453   if (Invert)
9454     Result = DAG.getNOT(dl, Result, VT);
9455
9456   return Result;
9457 }
9458
9459 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9460
9461   MVT VT = Op.getValueType().getSimpleVT();
9462
9463   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9464
9465   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9466   SDValue Op0 = Op.getOperand(0);
9467   SDValue Op1 = Op.getOperand(1);
9468   SDLoc dl(Op);
9469   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9470
9471   // Optimize to BT if possible.
9472   // Lower (X & (1 << N)) == 0 to BT(X, N).
9473   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9474   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9475   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9476       Op1.getOpcode() == ISD::Constant &&
9477       cast<ConstantSDNode>(Op1)->isNullValue() &&
9478       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9479     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9480     if (NewSetCC.getNode())
9481       return NewSetCC;
9482   }
9483
9484   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9485   // these.
9486   if (Op1.getOpcode() == ISD::Constant &&
9487       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9488        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9489       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9490
9491     // If the input is a setcc, then reuse the input setcc or use a new one with
9492     // the inverted condition.
9493     if (Op0.getOpcode() == X86ISD::SETCC) {
9494       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9495       bool Invert = (CC == ISD::SETNE) ^
9496         cast<ConstantSDNode>(Op1)->isNullValue();
9497       if (!Invert) return Op0;
9498
9499       CCode = X86::GetOppositeBranchCondition(CCode);
9500       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9501                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9502     }
9503   }
9504
9505   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9506   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9507   if (X86CC == X86::COND_INVALID)
9508     return SDValue();
9509
9510   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9511   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9512   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9513                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9514 }
9515
9516 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9517 static bool isX86LogicalCmp(SDValue Op) {
9518   unsigned Opc = Op.getNode()->getOpcode();
9519   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9520       Opc == X86ISD::SAHF)
9521     return true;
9522   if (Op.getResNo() == 1 &&
9523       (Opc == X86ISD::ADD ||
9524        Opc == X86ISD::SUB ||
9525        Opc == X86ISD::ADC ||
9526        Opc == X86ISD::SBB ||
9527        Opc == X86ISD::SMUL ||
9528        Opc == X86ISD::UMUL ||
9529        Opc == X86ISD::INC ||
9530        Opc == X86ISD::DEC ||
9531        Opc == X86ISD::OR ||
9532        Opc == X86ISD::XOR ||
9533        Opc == X86ISD::AND))
9534     return true;
9535
9536   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9537     return true;
9538
9539   return false;
9540 }
9541
9542 static bool isZero(SDValue V) {
9543   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9544   return C && C->isNullValue();
9545 }
9546
9547 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9548   if (V.getOpcode() != ISD::TRUNCATE)
9549     return false;
9550
9551   SDValue VOp0 = V.getOperand(0);
9552   unsigned InBits = VOp0.getValueSizeInBits();
9553   unsigned Bits = V.getValueSizeInBits();
9554   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9555 }
9556
9557 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9558   bool addTest = true;
9559   SDValue Cond  = Op.getOperand(0);
9560   SDValue Op1 = Op.getOperand(1);
9561   SDValue Op2 = Op.getOperand(2);
9562   SDLoc DL(Op);
9563   SDValue CC;
9564
9565   if (Cond.getOpcode() == ISD::SETCC) {
9566     SDValue NewCond = LowerSETCC(Cond, DAG);
9567     if (NewCond.getNode())
9568       Cond = NewCond;
9569   }
9570
9571   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9572   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9573   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9574   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9575   if (Cond.getOpcode() == X86ISD::SETCC &&
9576       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9577       isZero(Cond.getOperand(1).getOperand(1))) {
9578     SDValue Cmp = Cond.getOperand(1);
9579
9580     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9581
9582     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9583         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9584       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9585
9586       SDValue CmpOp0 = Cmp.getOperand(0);
9587       // Apply further optimizations for special cases
9588       // (select (x != 0), -1, 0) -> neg & sbb
9589       // (select (x == 0), 0, -1) -> neg & sbb
9590       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9591         if (YC->isNullValue() &&
9592             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9593           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9594           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9595                                     DAG.getConstant(0, CmpOp0.getValueType()),
9596                                     CmpOp0);
9597           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9598                                     DAG.getConstant(X86::COND_B, MVT::i8),
9599                                     SDValue(Neg.getNode(), 1));
9600           return Res;
9601         }
9602
9603       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9604                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9605       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9606
9607       SDValue Res =   // Res = 0 or -1.
9608         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9609                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9610
9611       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9612         Res = DAG.getNOT(DL, Res, Res.getValueType());
9613
9614       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9615       if (N2C == 0 || !N2C->isNullValue())
9616         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9617       return Res;
9618     }
9619   }
9620
9621   // Look past (and (setcc_carry (cmp ...)), 1).
9622   if (Cond.getOpcode() == ISD::AND &&
9623       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9624     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9625     if (C && C->getAPIntValue() == 1)
9626       Cond = Cond.getOperand(0);
9627   }
9628
9629   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9630   // setting operand in place of the X86ISD::SETCC.
9631   unsigned CondOpcode = Cond.getOpcode();
9632   if (CondOpcode == X86ISD::SETCC ||
9633       CondOpcode == X86ISD::SETCC_CARRY) {
9634     CC = Cond.getOperand(0);
9635
9636     SDValue Cmp = Cond.getOperand(1);
9637     unsigned Opc = Cmp.getOpcode();
9638     MVT VT = Op.getValueType().getSimpleVT();
9639
9640     bool IllegalFPCMov = false;
9641     if (VT.isFloatingPoint() && !VT.isVector() &&
9642         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9643       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9644
9645     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9646         Opc == X86ISD::BT) { // FIXME
9647       Cond = Cmp;
9648       addTest = false;
9649     }
9650   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9651              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9652              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9653               Cond.getOperand(0).getValueType() != MVT::i8)) {
9654     SDValue LHS = Cond.getOperand(0);
9655     SDValue RHS = Cond.getOperand(1);
9656     unsigned X86Opcode;
9657     unsigned X86Cond;
9658     SDVTList VTs;
9659     switch (CondOpcode) {
9660     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9661     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9662     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9663     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9664     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9665     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9666     default: llvm_unreachable("unexpected overflowing operator");
9667     }
9668     if (CondOpcode == ISD::UMULO)
9669       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9670                           MVT::i32);
9671     else
9672       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9673
9674     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9675
9676     if (CondOpcode == ISD::UMULO)
9677       Cond = X86Op.getValue(2);
9678     else
9679       Cond = X86Op.getValue(1);
9680
9681     CC = DAG.getConstant(X86Cond, MVT::i8);
9682     addTest = false;
9683   }
9684
9685   if (addTest) {
9686     // Look pass the truncate if the high bits are known zero.
9687     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9688         Cond = Cond.getOperand(0);
9689
9690     // We know the result of AND is compared against zero. Try to match
9691     // it to BT.
9692     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9693       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9694       if (NewSetCC.getNode()) {
9695         CC = NewSetCC.getOperand(0);
9696         Cond = NewSetCC.getOperand(1);
9697         addTest = false;
9698       }
9699     }
9700   }
9701
9702   if (addTest) {
9703     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9704     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9705   }
9706
9707   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9708   // a <  b ?  0 : -1 -> RES = setcc_carry
9709   // a >= b ? -1 :  0 -> RES = setcc_carry
9710   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9711   if (Cond.getOpcode() == X86ISD::SUB) {
9712     Cond = ConvertCmpIfNecessary(Cond, DAG);
9713     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9714
9715     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9716         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9717       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9718                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9719       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9720         return DAG.getNOT(DL, Res, Res.getValueType());
9721       return Res;
9722     }
9723   }
9724
9725   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9726   // widen the cmov and push the truncate through. This avoids introducing a new
9727   // branch during isel and doesn't add any extensions.
9728   if (Op.getValueType() == MVT::i8 &&
9729       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9730     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9731     if (T1.getValueType() == T2.getValueType() &&
9732         // Blacklist CopyFromReg to avoid partial register stalls.
9733         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9734       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9735       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9736       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9737     }
9738   }
9739
9740   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9741   // condition is true.
9742   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9743   SDValue Ops[] = { Op2, Op1, CC, Cond };
9744   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9745 }
9746
9747 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9748                                             SelectionDAG &DAG) const {
9749   MVT VT = Op->getValueType(0).getSimpleVT();
9750   SDValue In = Op->getOperand(0);
9751   MVT InVT = In.getValueType().getSimpleVT();
9752   SDLoc dl(Op);
9753
9754   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9755       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9756     return SDValue();
9757
9758   if (Subtarget->hasInt256())
9759     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9760
9761   // Optimize vectors in AVX mode
9762   // Sign extend  v8i16 to v8i32 and
9763   //              v4i32 to v4i64
9764   //
9765   // Divide input vector into two parts
9766   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9767   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9768   // concat the vectors to original VT
9769
9770   unsigned NumElems = InVT.getVectorNumElements();
9771   SDValue Undef = DAG.getUNDEF(InVT);
9772
9773   SmallVector<int,8> ShufMask1(NumElems, -1);
9774   for (unsigned i = 0; i != NumElems/2; ++i)
9775     ShufMask1[i] = i;
9776
9777   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9778
9779   SmallVector<int,8> ShufMask2(NumElems, -1);
9780   for (unsigned i = 0; i != NumElems/2; ++i)
9781     ShufMask2[i] = i + NumElems/2;
9782
9783   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9784
9785   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9786                                 VT.getVectorNumElements()/2);
9787
9788   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9789   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9790
9791   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9792 }
9793
9794 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9795 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9796 // from the AND / OR.
9797 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9798   Opc = Op.getOpcode();
9799   if (Opc != ISD::OR && Opc != ISD::AND)
9800     return false;
9801   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9802           Op.getOperand(0).hasOneUse() &&
9803           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9804           Op.getOperand(1).hasOneUse());
9805 }
9806
9807 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9808 // 1 and that the SETCC node has a single use.
9809 static bool isXor1OfSetCC(SDValue Op) {
9810   if (Op.getOpcode() != ISD::XOR)
9811     return false;
9812   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9813   if (N1C && N1C->getAPIntValue() == 1) {
9814     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9815       Op.getOperand(0).hasOneUse();
9816   }
9817   return false;
9818 }
9819
9820 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9821   bool addTest = true;
9822   SDValue Chain = Op.getOperand(0);
9823   SDValue Cond  = Op.getOperand(1);
9824   SDValue Dest  = Op.getOperand(2);
9825   SDLoc dl(Op);
9826   SDValue CC;
9827   bool Inverted = false;
9828
9829   if (Cond.getOpcode() == ISD::SETCC) {
9830     // Check for setcc([su]{add,sub,mul}o == 0).
9831     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9832         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9833         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9834         Cond.getOperand(0).getResNo() == 1 &&
9835         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9836          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9837          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9838          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9839          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9840          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9841       Inverted = true;
9842       Cond = Cond.getOperand(0);
9843     } else {
9844       SDValue NewCond = LowerSETCC(Cond, DAG);
9845       if (NewCond.getNode())
9846         Cond = NewCond;
9847     }
9848   }
9849 #if 0
9850   // FIXME: LowerXALUO doesn't handle these!!
9851   else if (Cond.getOpcode() == X86ISD::ADD  ||
9852            Cond.getOpcode() == X86ISD::SUB  ||
9853            Cond.getOpcode() == X86ISD::SMUL ||
9854            Cond.getOpcode() == X86ISD::UMUL)
9855     Cond = LowerXALUO(Cond, DAG);
9856 #endif
9857
9858   // Look pass (and (setcc_carry (cmp ...)), 1).
9859   if (Cond.getOpcode() == ISD::AND &&
9860       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9861     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9862     if (C && C->getAPIntValue() == 1)
9863       Cond = Cond.getOperand(0);
9864   }
9865
9866   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9867   // setting operand in place of the X86ISD::SETCC.
9868   unsigned CondOpcode = Cond.getOpcode();
9869   if (CondOpcode == X86ISD::SETCC ||
9870       CondOpcode == X86ISD::SETCC_CARRY) {
9871     CC = Cond.getOperand(0);
9872
9873     SDValue Cmp = Cond.getOperand(1);
9874     unsigned Opc = Cmp.getOpcode();
9875     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9876     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9877       Cond = Cmp;
9878       addTest = false;
9879     } else {
9880       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9881       default: break;
9882       case X86::COND_O:
9883       case X86::COND_B:
9884         // These can only come from an arithmetic instruction with overflow,
9885         // e.g. SADDO, UADDO.
9886         Cond = Cond.getNode()->getOperand(1);
9887         addTest = false;
9888         break;
9889       }
9890     }
9891   }
9892   CondOpcode = Cond.getOpcode();
9893   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9894       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9895       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9896        Cond.getOperand(0).getValueType() != MVT::i8)) {
9897     SDValue LHS = Cond.getOperand(0);
9898     SDValue RHS = Cond.getOperand(1);
9899     unsigned X86Opcode;
9900     unsigned X86Cond;
9901     SDVTList VTs;
9902     switch (CondOpcode) {
9903     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9904     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9905     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9906     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9907     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9908     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9909     default: llvm_unreachable("unexpected overflowing operator");
9910     }
9911     if (Inverted)
9912       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9913     if (CondOpcode == ISD::UMULO)
9914       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9915                           MVT::i32);
9916     else
9917       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9918
9919     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9920
9921     if (CondOpcode == ISD::UMULO)
9922       Cond = X86Op.getValue(2);
9923     else
9924       Cond = X86Op.getValue(1);
9925
9926     CC = DAG.getConstant(X86Cond, MVT::i8);
9927     addTest = false;
9928   } else {
9929     unsigned CondOpc;
9930     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9931       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9932       if (CondOpc == ISD::OR) {
9933         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9934         // two branches instead of an explicit OR instruction with a
9935         // separate test.
9936         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9937             isX86LogicalCmp(Cmp)) {
9938           CC = Cond.getOperand(0).getOperand(0);
9939           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9940                               Chain, Dest, CC, Cmp);
9941           CC = Cond.getOperand(1).getOperand(0);
9942           Cond = Cmp;
9943           addTest = false;
9944         }
9945       } else { // ISD::AND
9946         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9947         // two branches instead of an explicit AND instruction with a
9948         // separate test. However, we only do this if this block doesn't
9949         // have a fall-through edge, because this requires an explicit
9950         // jmp when the condition is false.
9951         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9952             isX86LogicalCmp(Cmp) &&
9953             Op.getNode()->hasOneUse()) {
9954           X86::CondCode CCode =
9955             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9956           CCode = X86::GetOppositeBranchCondition(CCode);
9957           CC = DAG.getConstant(CCode, MVT::i8);
9958           SDNode *User = *Op.getNode()->use_begin();
9959           // Look for an unconditional branch following this conditional branch.
9960           // We need this because we need to reverse the successors in order
9961           // to implement FCMP_OEQ.
9962           if (User->getOpcode() == ISD::BR) {
9963             SDValue FalseBB = User->getOperand(1);
9964             SDNode *NewBR =
9965               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9966             assert(NewBR == User);
9967             (void)NewBR;
9968             Dest = FalseBB;
9969
9970             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9971                                 Chain, Dest, CC, Cmp);
9972             X86::CondCode CCode =
9973               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9974             CCode = X86::GetOppositeBranchCondition(CCode);
9975             CC = DAG.getConstant(CCode, MVT::i8);
9976             Cond = Cmp;
9977             addTest = false;
9978           }
9979         }
9980       }
9981     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9982       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9983       // It should be transformed during dag combiner except when the condition
9984       // is set by a arithmetics with overflow node.
9985       X86::CondCode CCode =
9986         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9987       CCode = X86::GetOppositeBranchCondition(CCode);
9988       CC = DAG.getConstant(CCode, MVT::i8);
9989       Cond = Cond.getOperand(0).getOperand(1);
9990       addTest = false;
9991     } else if (Cond.getOpcode() == ISD::SETCC &&
9992                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9993       // For FCMP_OEQ, we can emit
9994       // two branches instead of an explicit AND instruction with a
9995       // separate test. However, we only do this if this block doesn't
9996       // have a fall-through edge, because this requires an explicit
9997       // jmp when the condition is false.
9998       if (Op.getNode()->hasOneUse()) {
9999         SDNode *User = *Op.getNode()->use_begin();
10000         // Look for an unconditional branch following this conditional branch.
10001         // We need this because we need to reverse the successors in order
10002         // to implement FCMP_OEQ.
10003         if (User->getOpcode() == ISD::BR) {
10004           SDValue FalseBB = User->getOperand(1);
10005           SDNode *NewBR =
10006             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10007           assert(NewBR == User);
10008           (void)NewBR;
10009           Dest = FalseBB;
10010
10011           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10012                                     Cond.getOperand(0), Cond.getOperand(1));
10013           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10014           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10015           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10016                               Chain, Dest, CC, Cmp);
10017           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10018           Cond = Cmp;
10019           addTest = false;
10020         }
10021       }
10022     } else if (Cond.getOpcode() == ISD::SETCC &&
10023                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10024       // For FCMP_UNE, we can emit
10025       // two branches instead of an explicit AND instruction with a
10026       // separate test. However, we only do this if this block doesn't
10027       // have a fall-through edge, because this requires an explicit
10028       // jmp when the condition is false.
10029       if (Op.getNode()->hasOneUse()) {
10030         SDNode *User = *Op.getNode()->use_begin();
10031         // Look for an unconditional branch following this conditional branch.
10032         // We need this because we need to reverse the successors in order
10033         // to implement FCMP_UNE.
10034         if (User->getOpcode() == ISD::BR) {
10035           SDValue FalseBB = User->getOperand(1);
10036           SDNode *NewBR =
10037             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10038           assert(NewBR == User);
10039           (void)NewBR;
10040
10041           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10042                                     Cond.getOperand(0), Cond.getOperand(1));
10043           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10044           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10045           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10046                               Chain, Dest, CC, Cmp);
10047           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10048           Cond = Cmp;
10049           addTest = false;
10050           Dest = FalseBB;
10051         }
10052       }
10053     }
10054   }
10055
10056   if (addTest) {
10057     // Look pass the truncate if the high bits are known zero.
10058     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10059         Cond = Cond.getOperand(0);
10060
10061     // We know the result of AND is compared against zero. Try to match
10062     // it to BT.
10063     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10064       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10065       if (NewSetCC.getNode()) {
10066         CC = NewSetCC.getOperand(0);
10067         Cond = NewSetCC.getOperand(1);
10068         addTest = false;
10069       }
10070     }
10071   }
10072
10073   if (addTest) {
10074     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10075     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10076   }
10077   Cond = ConvertCmpIfNecessary(Cond, DAG);
10078   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10079                      Chain, Dest, CC, Cond);
10080 }
10081
10082 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10083 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10084 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10085 // that the guard pages used by the OS virtual memory manager are allocated in
10086 // correct sequence.
10087 SDValue
10088 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10089                                            SelectionDAG &DAG) const {
10090   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10091           getTargetMachine().Options.EnableSegmentedStacks) &&
10092          "This should be used only on Windows targets or when segmented stacks "
10093          "are being used");
10094   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10095   SDLoc dl(Op);
10096
10097   // Get the inputs.
10098   SDValue Chain = Op.getOperand(0);
10099   SDValue Size  = Op.getOperand(1);
10100   // FIXME: Ensure alignment here
10101
10102   bool Is64Bit = Subtarget->is64Bit();
10103   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10104
10105   if (getTargetMachine().Options.EnableSegmentedStacks) {
10106     MachineFunction &MF = DAG.getMachineFunction();
10107     MachineRegisterInfo &MRI = MF.getRegInfo();
10108
10109     if (Is64Bit) {
10110       // The 64 bit implementation of segmented stacks needs to clobber both r10
10111       // r11. This makes it impossible to use it along with nested parameters.
10112       const Function *F = MF.getFunction();
10113
10114       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10115            I != E; ++I)
10116         if (I->hasNestAttr())
10117           report_fatal_error("Cannot use segmented stacks with functions that "
10118                              "have nested arguments.");
10119     }
10120
10121     const TargetRegisterClass *AddrRegClass =
10122       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10123     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10124     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10125     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10126                                 DAG.getRegister(Vreg, SPTy));
10127     SDValue Ops1[2] = { Value, Chain };
10128     return DAG.getMergeValues(Ops1, 2, dl);
10129   } else {
10130     SDValue Flag;
10131     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10132
10133     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10134     Flag = Chain.getValue(1);
10135     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10136
10137     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10138     Flag = Chain.getValue(1);
10139
10140     const X86RegisterInfo *RegInfo =
10141       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10142     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10143                                SPTy).getValue(1);
10144
10145     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10146     return DAG.getMergeValues(Ops1, 2, dl);
10147   }
10148 }
10149
10150 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10151   MachineFunction &MF = DAG.getMachineFunction();
10152   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10153
10154   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10155   SDLoc DL(Op);
10156
10157   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10158     // vastart just stores the address of the VarArgsFrameIndex slot into the
10159     // memory location argument.
10160     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10161                                    getPointerTy());
10162     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10163                         MachinePointerInfo(SV), false, false, 0);
10164   }
10165
10166   // __va_list_tag:
10167   //   gp_offset         (0 - 6 * 8)
10168   //   fp_offset         (48 - 48 + 8 * 16)
10169   //   overflow_arg_area (point to parameters coming in memory).
10170   //   reg_save_area
10171   SmallVector<SDValue, 8> MemOps;
10172   SDValue FIN = Op.getOperand(1);
10173   // Store gp_offset
10174   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10175                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10176                                                MVT::i32),
10177                                FIN, MachinePointerInfo(SV), false, false, 0);
10178   MemOps.push_back(Store);
10179
10180   // Store fp_offset
10181   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10182                     FIN, DAG.getIntPtrConstant(4));
10183   Store = DAG.getStore(Op.getOperand(0), DL,
10184                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10185                                        MVT::i32),
10186                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10187   MemOps.push_back(Store);
10188
10189   // Store ptr to overflow_arg_area
10190   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10191                     FIN, DAG.getIntPtrConstant(4));
10192   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10193                                     getPointerTy());
10194   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10195                        MachinePointerInfo(SV, 8),
10196                        false, false, 0);
10197   MemOps.push_back(Store);
10198
10199   // Store ptr to reg_save_area.
10200   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10201                     FIN, DAG.getIntPtrConstant(8));
10202   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10203                                     getPointerTy());
10204   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10205                        MachinePointerInfo(SV, 16), false, false, 0);
10206   MemOps.push_back(Store);
10207   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10208                      &MemOps[0], MemOps.size());
10209 }
10210
10211 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10212   assert(Subtarget->is64Bit() &&
10213          "LowerVAARG only handles 64-bit va_arg!");
10214   assert((Subtarget->isTargetLinux() ||
10215           Subtarget->isTargetDarwin()) &&
10216           "Unhandled target in LowerVAARG");
10217   assert(Op.getNode()->getNumOperands() == 4);
10218   SDValue Chain = Op.getOperand(0);
10219   SDValue SrcPtr = Op.getOperand(1);
10220   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10221   unsigned Align = Op.getConstantOperandVal(3);
10222   SDLoc dl(Op);
10223
10224   EVT ArgVT = Op.getNode()->getValueType(0);
10225   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10226   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10227   uint8_t ArgMode;
10228
10229   // Decide which area this value should be read from.
10230   // TODO: Implement the AMD64 ABI in its entirety. This simple
10231   // selection mechanism works only for the basic types.
10232   if (ArgVT == MVT::f80) {
10233     llvm_unreachable("va_arg for f80 not yet implemented");
10234   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10235     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10236   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10237     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10238   } else {
10239     llvm_unreachable("Unhandled argument type in LowerVAARG");
10240   }
10241
10242   if (ArgMode == 2) {
10243     // Sanity Check: Make sure using fp_offset makes sense.
10244     assert(!getTargetMachine().Options.UseSoftFloat &&
10245            !(DAG.getMachineFunction()
10246                 .getFunction()->getAttributes()
10247                 .hasAttribute(AttributeSet::FunctionIndex,
10248                               Attribute::NoImplicitFloat)) &&
10249            Subtarget->hasSSE1());
10250   }
10251
10252   // Insert VAARG_64 node into the DAG
10253   // VAARG_64 returns two values: Variable Argument Address, Chain
10254   SmallVector<SDValue, 11> InstOps;
10255   InstOps.push_back(Chain);
10256   InstOps.push_back(SrcPtr);
10257   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10258   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10259   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10260   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10261   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10262                                           VTs, &InstOps[0], InstOps.size(),
10263                                           MVT::i64,
10264                                           MachinePointerInfo(SV),
10265                                           /*Align=*/0,
10266                                           /*Volatile=*/false,
10267                                           /*ReadMem=*/true,
10268                                           /*WriteMem=*/true);
10269   Chain = VAARG.getValue(1);
10270
10271   // Load the next argument and return it
10272   return DAG.getLoad(ArgVT, dl,
10273                      Chain,
10274                      VAARG,
10275                      MachinePointerInfo(),
10276                      false, false, false, 0);
10277 }
10278
10279 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10280                            SelectionDAG &DAG) {
10281   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10282   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10283   SDValue Chain = Op.getOperand(0);
10284   SDValue DstPtr = Op.getOperand(1);
10285   SDValue SrcPtr = Op.getOperand(2);
10286   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10287   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10288   SDLoc DL(Op);
10289
10290   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10291                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10292                        false,
10293                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10294 }
10295
10296 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10297 // may or may not be a constant. Takes immediate version of shift as input.
10298 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10299                                    SDValue SrcOp, SDValue ShAmt,
10300                                    SelectionDAG &DAG) {
10301   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10302
10303   if (isa<ConstantSDNode>(ShAmt)) {
10304     // Constant may be a TargetConstant. Use a regular constant.
10305     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10306     switch (Opc) {
10307       default: llvm_unreachable("Unknown target vector shift node");
10308       case X86ISD::VSHLI:
10309       case X86ISD::VSRLI:
10310       case X86ISD::VSRAI:
10311         return DAG.getNode(Opc, dl, VT, SrcOp,
10312                            DAG.getConstant(ShiftAmt, MVT::i32));
10313     }
10314   }
10315
10316   // Change opcode to non-immediate version
10317   switch (Opc) {
10318     default: llvm_unreachable("Unknown target vector shift node");
10319     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10320     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10321     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10322   }
10323
10324   // Need to build a vector containing shift amount
10325   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10326   SDValue ShOps[4];
10327   ShOps[0] = ShAmt;
10328   ShOps[1] = DAG.getConstant(0, MVT::i32);
10329   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10330   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10331
10332   // The return type has to be a 128-bit type with the same element
10333   // type as the input type.
10334   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10335   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10336
10337   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10338   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10339 }
10340
10341 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10342   SDLoc dl(Op);
10343   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10344   switch (IntNo) {
10345   default: return SDValue();    // Don't custom lower most intrinsics.
10346   // Comparison intrinsics.
10347   case Intrinsic::x86_sse_comieq_ss:
10348   case Intrinsic::x86_sse_comilt_ss:
10349   case Intrinsic::x86_sse_comile_ss:
10350   case Intrinsic::x86_sse_comigt_ss:
10351   case Intrinsic::x86_sse_comige_ss:
10352   case Intrinsic::x86_sse_comineq_ss:
10353   case Intrinsic::x86_sse_ucomieq_ss:
10354   case Intrinsic::x86_sse_ucomilt_ss:
10355   case Intrinsic::x86_sse_ucomile_ss:
10356   case Intrinsic::x86_sse_ucomigt_ss:
10357   case Intrinsic::x86_sse_ucomige_ss:
10358   case Intrinsic::x86_sse_ucomineq_ss:
10359   case Intrinsic::x86_sse2_comieq_sd:
10360   case Intrinsic::x86_sse2_comilt_sd:
10361   case Intrinsic::x86_sse2_comile_sd:
10362   case Intrinsic::x86_sse2_comigt_sd:
10363   case Intrinsic::x86_sse2_comige_sd:
10364   case Intrinsic::x86_sse2_comineq_sd:
10365   case Intrinsic::x86_sse2_ucomieq_sd:
10366   case Intrinsic::x86_sse2_ucomilt_sd:
10367   case Intrinsic::x86_sse2_ucomile_sd:
10368   case Intrinsic::x86_sse2_ucomigt_sd:
10369   case Intrinsic::x86_sse2_ucomige_sd:
10370   case Intrinsic::x86_sse2_ucomineq_sd: {
10371     unsigned Opc;
10372     ISD::CondCode CC;
10373     switch (IntNo) {
10374     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10375     case Intrinsic::x86_sse_comieq_ss:
10376     case Intrinsic::x86_sse2_comieq_sd:
10377       Opc = X86ISD::COMI;
10378       CC = ISD::SETEQ;
10379       break;
10380     case Intrinsic::x86_sse_comilt_ss:
10381     case Intrinsic::x86_sse2_comilt_sd:
10382       Opc = X86ISD::COMI;
10383       CC = ISD::SETLT;
10384       break;
10385     case Intrinsic::x86_sse_comile_ss:
10386     case Intrinsic::x86_sse2_comile_sd:
10387       Opc = X86ISD::COMI;
10388       CC = ISD::SETLE;
10389       break;
10390     case Intrinsic::x86_sse_comigt_ss:
10391     case Intrinsic::x86_sse2_comigt_sd:
10392       Opc = X86ISD::COMI;
10393       CC = ISD::SETGT;
10394       break;
10395     case Intrinsic::x86_sse_comige_ss:
10396     case Intrinsic::x86_sse2_comige_sd:
10397       Opc = X86ISD::COMI;
10398       CC = ISD::SETGE;
10399       break;
10400     case Intrinsic::x86_sse_comineq_ss:
10401     case Intrinsic::x86_sse2_comineq_sd:
10402       Opc = X86ISD::COMI;
10403       CC = ISD::SETNE;
10404       break;
10405     case Intrinsic::x86_sse_ucomieq_ss:
10406     case Intrinsic::x86_sse2_ucomieq_sd:
10407       Opc = X86ISD::UCOMI;
10408       CC = ISD::SETEQ;
10409       break;
10410     case Intrinsic::x86_sse_ucomilt_ss:
10411     case Intrinsic::x86_sse2_ucomilt_sd:
10412       Opc = X86ISD::UCOMI;
10413       CC = ISD::SETLT;
10414       break;
10415     case Intrinsic::x86_sse_ucomile_ss:
10416     case Intrinsic::x86_sse2_ucomile_sd:
10417       Opc = X86ISD::UCOMI;
10418       CC = ISD::SETLE;
10419       break;
10420     case Intrinsic::x86_sse_ucomigt_ss:
10421     case Intrinsic::x86_sse2_ucomigt_sd:
10422       Opc = X86ISD::UCOMI;
10423       CC = ISD::SETGT;
10424       break;
10425     case Intrinsic::x86_sse_ucomige_ss:
10426     case Intrinsic::x86_sse2_ucomige_sd:
10427       Opc = X86ISD::UCOMI;
10428       CC = ISD::SETGE;
10429       break;
10430     case Intrinsic::x86_sse_ucomineq_ss:
10431     case Intrinsic::x86_sse2_ucomineq_sd:
10432       Opc = X86ISD::UCOMI;
10433       CC = ISD::SETNE;
10434       break;
10435     }
10436
10437     SDValue LHS = Op.getOperand(1);
10438     SDValue RHS = Op.getOperand(2);
10439     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10440     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10441     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10442     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10443                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10444     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10445   }
10446
10447   // Arithmetic intrinsics.
10448   case Intrinsic::x86_sse2_pmulu_dq:
10449   case Intrinsic::x86_avx2_pmulu_dq:
10450     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10451                        Op.getOperand(1), Op.getOperand(2));
10452
10453   // SSE2/AVX2 sub with unsigned saturation intrinsics
10454   case Intrinsic::x86_sse2_psubus_b:
10455   case Intrinsic::x86_sse2_psubus_w:
10456   case Intrinsic::x86_avx2_psubus_b:
10457   case Intrinsic::x86_avx2_psubus_w:
10458     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10459                        Op.getOperand(1), Op.getOperand(2));
10460
10461   // SSE3/AVX horizontal add/sub intrinsics
10462   case Intrinsic::x86_sse3_hadd_ps:
10463   case Intrinsic::x86_sse3_hadd_pd:
10464   case Intrinsic::x86_avx_hadd_ps_256:
10465   case Intrinsic::x86_avx_hadd_pd_256:
10466   case Intrinsic::x86_sse3_hsub_ps:
10467   case Intrinsic::x86_sse3_hsub_pd:
10468   case Intrinsic::x86_avx_hsub_ps_256:
10469   case Intrinsic::x86_avx_hsub_pd_256:
10470   case Intrinsic::x86_ssse3_phadd_w_128:
10471   case Intrinsic::x86_ssse3_phadd_d_128:
10472   case Intrinsic::x86_avx2_phadd_w:
10473   case Intrinsic::x86_avx2_phadd_d:
10474   case Intrinsic::x86_ssse3_phsub_w_128:
10475   case Intrinsic::x86_ssse3_phsub_d_128:
10476   case Intrinsic::x86_avx2_phsub_w:
10477   case Intrinsic::x86_avx2_phsub_d: {
10478     unsigned Opcode;
10479     switch (IntNo) {
10480     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10481     case Intrinsic::x86_sse3_hadd_ps:
10482     case Intrinsic::x86_sse3_hadd_pd:
10483     case Intrinsic::x86_avx_hadd_ps_256:
10484     case Intrinsic::x86_avx_hadd_pd_256:
10485       Opcode = X86ISD::FHADD;
10486       break;
10487     case Intrinsic::x86_sse3_hsub_ps:
10488     case Intrinsic::x86_sse3_hsub_pd:
10489     case Intrinsic::x86_avx_hsub_ps_256:
10490     case Intrinsic::x86_avx_hsub_pd_256:
10491       Opcode = X86ISD::FHSUB;
10492       break;
10493     case Intrinsic::x86_ssse3_phadd_w_128:
10494     case Intrinsic::x86_ssse3_phadd_d_128:
10495     case Intrinsic::x86_avx2_phadd_w:
10496     case Intrinsic::x86_avx2_phadd_d:
10497       Opcode = X86ISD::HADD;
10498       break;
10499     case Intrinsic::x86_ssse3_phsub_w_128:
10500     case Intrinsic::x86_ssse3_phsub_d_128:
10501     case Intrinsic::x86_avx2_phsub_w:
10502     case Intrinsic::x86_avx2_phsub_d:
10503       Opcode = X86ISD::HSUB;
10504       break;
10505     }
10506     return DAG.getNode(Opcode, dl, Op.getValueType(),
10507                        Op.getOperand(1), Op.getOperand(2));
10508   }
10509
10510   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10511   case Intrinsic::x86_sse2_pmaxu_b:
10512   case Intrinsic::x86_sse41_pmaxuw:
10513   case Intrinsic::x86_sse41_pmaxud:
10514   case Intrinsic::x86_avx2_pmaxu_b:
10515   case Intrinsic::x86_avx2_pmaxu_w:
10516   case Intrinsic::x86_avx2_pmaxu_d:
10517   case Intrinsic::x86_sse2_pminu_b:
10518   case Intrinsic::x86_sse41_pminuw:
10519   case Intrinsic::x86_sse41_pminud:
10520   case Intrinsic::x86_avx2_pminu_b:
10521   case Intrinsic::x86_avx2_pminu_w:
10522   case Intrinsic::x86_avx2_pminu_d:
10523   case Intrinsic::x86_sse41_pmaxsb:
10524   case Intrinsic::x86_sse2_pmaxs_w:
10525   case Intrinsic::x86_sse41_pmaxsd:
10526   case Intrinsic::x86_avx2_pmaxs_b:
10527   case Intrinsic::x86_avx2_pmaxs_w:
10528   case Intrinsic::x86_avx2_pmaxs_d:
10529   case Intrinsic::x86_sse41_pminsb:
10530   case Intrinsic::x86_sse2_pmins_w:
10531   case Intrinsic::x86_sse41_pminsd:
10532   case Intrinsic::x86_avx2_pmins_b:
10533   case Intrinsic::x86_avx2_pmins_w:
10534   case Intrinsic::x86_avx2_pmins_d: {
10535     unsigned Opcode;
10536     switch (IntNo) {
10537     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10538     case Intrinsic::x86_sse2_pmaxu_b:
10539     case Intrinsic::x86_sse41_pmaxuw:
10540     case Intrinsic::x86_sse41_pmaxud:
10541     case Intrinsic::x86_avx2_pmaxu_b:
10542     case Intrinsic::x86_avx2_pmaxu_w:
10543     case Intrinsic::x86_avx2_pmaxu_d:
10544       Opcode = X86ISD::UMAX;
10545       break;
10546     case Intrinsic::x86_sse2_pminu_b:
10547     case Intrinsic::x86_sse41_pminuw:
10548     case Intrinsic::x86_sse41_pminud:
10549     case Intrinsic::x86_avx2_pminu_b:
10550     case Intrinsic::x86_avx2_pminu_w:
10551     case Intrinsic::x86_avx2_pminu_d:
10552       Opcode = X86ISD::UMIN;
10553       break;
10554     case Intrinsic::x86_sse41_pmaxsb:
10555     case Intrinsic::x86_sse2_pmaxs_w:
10556     case Intrinsic::x86_sse41_pmaxsd:
10557     case Intrinsic::x86_avx2_pmaxs_b:
10558     case Intrinsic::x86_avx2_pmaxs_w:
10559     case Intrinsic::x86_avx2_pmaxs_d:
10560       Opcode = X86ISD::SMAX;
10561       break;
10562     case Intrinsic::x86_sse41_pminsb:
10563     case Intrinsic::x86_sse2_pmins_w:
10564     case Intrinsic::x86_sse41_pminsd:
10565     case Intrinsic::x86_avx2_pmins_b:
10566     case Intrinsic::x86_avx2_pmins_w:
10567     case Intrinsic::x86_avx2_pmins_d:
10568       Opcode = X86ISD::SMIN;
10569       break;
10570     }
10571     return DAG.getNode(Opcode, dl, Op.getValueType(),
10572                        Op.getOperand(1), Op.getOperand(2));
10573   }
10574
10575   // SSE/SSE2/AVX floating point max/min intrinsics.
10576   case Intrinsic::x86_sse_max_ps:
10577   case Intrinsic::x86_sse2_max_pd:
10578   case Intrinsic::x86_avx_max_ps_256:
10579   case Intrinsic::x86_avx_max_pd_256:
10580   case Intrinsic::x86_sse_min_ps:
10581   case Intrinsic::x86_sse2_min_pd:
10582   case Intrinsic::x86_avx_min_ps_256:
10583   case Intrinsic::x86_avx_min_pd_256: {
10584     unsigned Opcode;
10585     switch (IntNo) {
10586     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10587     case Intrinsic::x86_sse_max_ps:
10588     case Intrinsic::x86_sse2_max_pd:
10589     case Intrinsic::x86_avx_max_ps_256:
10590     case Intrinsic::x86_avx_max_pd_256:
10591       Opcode = X86ISD::FMAX;
10592       break;
10593     case Intrinsic::x86_sse_min_ps:
10594     case Intrinsic::x86_sse2_min_pd:
10595     case Intrinsic::x86_avx_min_ps_256:
10596     case Intrinsic::x86_avx_min_pd_256:
10597       Opcode = X86ISD::FMIN;
10598       break;
10599     }
10600     return DAG.getNode(Opcode, dl, Op.getValueType(),
10601                        Op.getOperand(1), Op.getOperand(2));
10602   }
10603
10604   // AVX2 variable shift intrinsics
10605   case Intrinsic::x86_avx2_psllv_d:
10606   case Intrinsic::x86_avx2_psllv_q:
10607   case Intrinsic::x86_avx2_psllv_d_256:
10608   case Intrinsic::x86_avx2_psllv_q_256:
10609   case Intrinsic::x86_avx2_psrlv_d:
10610   case Intrinsic::x86_avx2_psrlv_q:
10611   case Intrinsic::x86_avx2_psrlv_d_256:
10612   case Intrinsic::x86_avx2_psrlv_q_256:
10613   case Intrinsic::x86_avx2_psrav_d:
10614   case Intrinsic::x86_avx2_psrav_d_256: {
10615     unsigned Opcode;
10616     switch (IntNo) {
10617     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10618     case Intrinsic::x86_avx2_psllv_d:
10619     case Intrinsic::x86_avx2_psllv_q:
10620     case Intrinsic::x86_avx2_psllv_d_256:
10621     case Intrinsic::x86_avx2_psllv_q_256:
10622       Opcode = ISD::SHL;
10623       break;
10624     case Intrinsic::x86_avx2_psrlv_d:
10625     case Intrinsic::x86_avx2_psrlv_q:
10626     case Intrinsic::x86_avx2_psrlv_d_256:
10627     case Intrinsic::x86_avx2_psrlv_q_256:
10628       Opcode = ISD::SRL;
10629       break;
10630     case Intrinsic::x86_avx2_psrav_d:
10631     case Intrinsic::x86_avx2_psrav_d_256:
10632       Opcode = ISD::SRA;
10633       break;
10634     }
10635     return DAG.getNode(Opcode, dl, Op.getValueType(),
10636                        Op.getOperand(1), Op.getOperand(2));
10637   }
10638
10639   case Intrinsic::x86_ssse3_pshuf_b_128:
10640   case Intrinsic::x86_avx2_pshuf_b:
10641     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10642                        Op.getOperand(1), Op.getOperand(2));
10643
10644   case Intrinsic::x86_ssse3_psign_b_128:
10645   case Intrinsic::x86_ssse3_psign_w_128:
10646   case Intrinsic::x86_ssse3_psign_d_128:
10647   case Intrinsic::x86_avx2_psign_b:
10648   case Intrinsic::x86_avx2_psign_w:
10649   case Intrinsic::x86_avx2_psign_d:
10650     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10651                        Op.getOperand(1), Op.getOperand(2));
10652
10653   case Intrinsic::x86_sse41_insertps:
10654     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10655                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10656
10657   case Intrinsic::x86_avx_vperm2f128_ps_256:
10658   case Intrinsic::x86_avx_vperm2f128_pd_256:
10659   case Intrinsic::x86_avx_vperm2f128_si_256:
10660   case Intrinsic::x86_avx2_vperm2i128:
10661     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10662                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10663
10664   case Intrinsic::x86_avx2_permd:
10665   case Intrinsic::x86_avx2_permps:
10666     // Operands intentionally swapped. Mask is last operand to intrinsic,
10667     // but second operand for node/intruction.
10668     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10669                        Op.getOperand(2), Op.getOperand(1));
10670
10671   case Intrinsic::x86_sse_sqrt_ps:
10672   case Intrinsic::x86_sse2_sqrt_pd:
10673   case Intrinsic::x86_avx_sqrt_ps_256:
10674   case Intrinsic::x86_avx_sqrt_pd_256:
10675     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10676
10677   // ptest and testp intrinsics. The intrinsic these come from are designed to
10678   // return an integer value, not just an instruction so lower it to the ptest
10679   // or testp pattern and a setcc for the result.
10680   case Intrinsic::x86_sse41_ptestz:
10681   case Intrinsic::x86_sse41_ptestc:
10682   case Intrinsic::x86_sse41_ptestnzc:
10683   case Intrinsic::x86_avx_ptestz_256:
10684   case Intrinsic::x86_avx_ptestc_256:
10685   case Intrinsic::x86_avx_ptestnzc_256:
10686   case Intrinsic::x86_avx_vtestz_ps:
10687   case Intrinsic::x86_avx_vtestc_ps:
10688   case Intrinsic::x86_avx_vtestnzc_ps:
10689   case Intrinsic::x86_avx_vtestz_pd:
10690   case Intrinsic::x86_avx_vtestc_pd:
10691   case Intrinsic::x86_avx_vtestnzc_pd:
10692   case Intrinsic::x86_avx_vtestz_ps_256:
10693   case Intrinsic::x86_avx_vtestc_ps_256:
10694   case Intrinsic::x86_avx_vtestnzc_ps_256:
10695   case Intrinsic::x86_avx_vtestz_pd_256:
10696   case Intrinsic::x86_avx_vtestc_pd_256:
10697   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10698     bool IsTestPacked = false;
10699     unsigned X86CC;
10700     switch (IntNo) {
10701     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10702     case Intrinsic::x86_avx_vtestz_ps:
10703     case Intrinsic::x86_avx_vtestz_pd:
10704     case Intrinsic::x86_avx_vtestz_ps_256:
10705     case Intrinsic::x86_avx_vtestz_pd_256:
10706       IsTestPacked = true; // Fallthrough
10707     case Intrinsic::x86_sse41_ptestz:
10708     case Intrinsic::x86_avx_ptestz_256:
10709       // ZF = 1
10710       X86CC = X86::COND_E;
10711       break;
10712     case Intrinsic::x86_avx_vtestc_ps:
10713     case Intrinsic::x86_avx_vtestc_pd:
10714     case Intrinsic::x86_avx_vtestc_ps_256:
10715     case Intrinsic::x86_avx_vtestc_pd_256:
10716       IsTestPacked = true; // Fallthrough
10717     case Intrinsic::x86_sse41_ptestc:
10718     case Intrinsic::x86_avx_ptestc_256:
10719       // CF = 1
10720       X86CC = X86::COND_B;
10721       break;
10722     case Intrinsic::x86_avx_vtestnzc_ps:
10723     case Intrinsic::x86_avx_vtestnzc_pd:
10724     case Intrinsic::x86_avx_vtestnzc_ps_256:
10725     case Intrinsic::x86_avx_vtestnzc_pd_256:
10726       IsTestPacked = true; // Fallthrough
10727     case Intrinsic::x86_sse41_ptestnzc:
10728     case Intrinsic::x86_avx_ptestnzc_256:
10729       // ZF and CF = 0
10730       X86CC = X86::COND_A;
10731       break;
10732     }
10733
10734     SDValue LHS = Op.getOperand(1);
10735     SDValue RHS = Op.getOperand(2);
10736     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10737     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10738     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10739     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10740     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10741   }
10742
10743   // SSE/AVX shift intrinsics
10744   case Intrinsic::x86_sse2_psll_w:
10745   case Intrinsic::x86_sse2_psll_d:
10746   case Intrinsic::x86_sse2_psll_q:
10747   case Intrinsic::x86_avx2_psll_w:
10748   case Intrinsic::x86_avx2_psll_d:
10749   case Intrinsic::x86_avx2_psll_q:
10750   case Intrinsic::x86_sse2_psrl_w:
10751   case Intrinsic::x86_sse2_psrl_d:
10752   case Intrinsic::x86_sse2_psrl_q:
10753   case Intrinsic::x86_avx2_psrl_w:
10754   case Intrinsic::x86_avx2_psrl_d:
10755   case Intrinsic::x86_avx2_psrl_q:
10756   case Intrinsic::x86_sse2_psra_w:
10757   case Intrinsic::x86_sse2_psra_d:
10758   case Intrinsic::x86_avx2_psra_w:
10759   case Intrinsic::x86_avx2_psra_d: {
10760     unsigned Opcode;
10761     switch (IntNo) {
10762     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10763     case Intrinsic::x86_sse2_psll_w:
10764     case Intrinsic::x86_sse2_psll_d:
10765     case Intrinsic::x86_sse2_psll_q:
10766     case Intrinsic::x86_avx2_psll_w:
10767     case Intrinsic::x86_avx2_psll_d:
10768     case Intrinsic::x86_avx2_psll_q:
10769       Opcode = X86ISD::VSHL;
10770       break;
10771     case Intrinsic::x86_sse2_psrl_w:
10772     case Intrinsic::x86_sse2_psrl_d:
10773     case Intrinsic::x86_sse2_psrl_q:
10774     case Intrinsic::x86_avx2_psrl_w:
10775     case Intrinsic::x86_avx2_psrl_d:
10776     case Intrinsic::x86_avx2_psrl_q:
10777       Opcode = X86ISD::VSRL;
10778       break;
10779     case Intrinsic::x86_sse2_psra_w:
10780     case Intrinsic::x86_sse2_psra_d:
10781     case Intrinsic::x86_avx2_psra_w:
10782     case Intrinsic::x86_avx2_psra_d:
10783       Opcode = X86ISD::VSRA;
10784       break;
10785     }
10786     return DAG.getNode(Opcode, dl, Op.getValueType(),
10787                        Op.getOperand(1), Op.getOperand(2));
10788   }
10789
10790   // SSE/AVX immediate shift intrinsics
10791   case Intrinsic::x86_sse2_pslli_w:
10792   case Intrinsic::x86_sse2_pslli_d:
10793   case Intrinsic::x86_sse2_pslli_q:
10794   case Intrinsic::x86_avx2_pslli_w:
10795   case Intrinsic::x86_avx2_pslli_d:
10796   case Intrinsic::x86_avx2_pslli_q:
10797   case Intrinsic::x86_sse2_psrli_w:
10798   case Intrinsic::x86_sse2_psrli_d:
10799   case Intrinsic::x86_sse2_psrli_q:
10800   case Intrinsic::x86_avx2_psrli_w:
10801   case Intrinsic::x86_avx2_psrli_d:
10802   case Intrinsic::x86_avx2_psrli_q:
10803   case Intrinsic::x86_sse2_psrai_w:
10804   case Intrinsic::x86_sse2_psrai_d:
10805   case Intrinsic::x86_avx2_psrai_w:
10806   case Intrinsic::x86_avx2_psrai_d: {
10807     unsigned Opcode;
10808     switch (IntNo) {
10809     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10810     case Intrinsic::x86_sse2_pslli_w:
10811     case Intrinsic::x86_sse2_pslli_d:
10812     case Intrinsic::x86_sse2_pslli_q:
10813     case Intrinsic::x86_avx2_pslli_w:
10814     case Intrinsic::x86_avx2_pslli_d:
10815     case Intrinsic::x86_avx2_pslli_q:
10816       Opcode = X86ISD::VSHLI;
10817       break;
10818     case Intrinsic::x86_sse2_psrli_w:
10819     case Intrinsic::x86_sse2_psrli_d:
10820     case Intrinsic::x86_sse2_psrli_q:
10821     case Intrinsic::x86_avx2_psrli_w:
10822     case Intrinsic::x86_avx2_psrli_d:
10823     case Intrinsic::x86_avx2_psrli_q:
10824       Opcode = X86ISD::VSRLI;
10825       break;
10826     case Intrinsic::x86_sse2_psrai_w:
10827     case Intrinsic::x86_sse2_psrai_d:
10828     case Intrinsic::x86_avx2_psrai_w:
10829     case Intrinsic::x86_avx2_psrai_d:
10830       Opcode = X86ISD::VSRAI;
10831       break;
10832     }
10833     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10834                                Op.getOperand(1), Op.getOperand(2), DAG);
10835   }
10836
10837   case Intrinsic::x86_sse42_pcmpistria128:
10838   case Intrinsic::x86_sse42_pcmpestria128:
10839   case Intrinsic::x86_sse42_pcmpistric128:
10840   case Intrinsic::x86_sse42_pcmpestric128:
10841   case Intrinsic::x86_sse42_pcmpistrio128:
10842   case Intrinsic::x86_sse42_pcmpestrio128:
10843   case Intrinsic::x86_sse42_pcmpistris128:
10844   case Intrinsic::x86_sse42_pcmpestris128:
10845   case Intrinsic::x86_sse42_pcmpistriz128:
10846   case Intrinsic::x86_sse42_pcmpestriz128: {
10847     unsigned Opcode;
10848     unsigned X86CC;
10849     switch (IntNo) {
10850     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10851     case Intrinsic::x86_sse42_pcmpistria128:
10852       Opcode = X86ISD::PCMPISTRI;
10853       X86CC = X86::COND_A;
10854       break;
10855     case Intrinsic::x86_sse42_pcmpestria128:
10856       Opcode = X86ISD::PCMPESTRI;
10857       X86CC = X86::COND_A;
10858       break;
10859     case Intrinsic::x86_sse42_pcmpistric128:
10860       Opcode = X86ISD::PCMPISTRI;
10861       X86CC = X86::COND_B;
10862       break;
10863     case Intrinsic::x86_sse42_pcmpestric128:
10864       Opcode = X86ISD::PCMPESTRI;
10865       X86CC = X86::COND_B;
10866       break;
10867     case Intrinsic::x86_sse42_pcmpistrio128:
10868       Opcode = X86ISD::PCMPISTRI;
10869       X86CC = X86::COND_O;
10870       break;
10871     case Intrinsic::x86_sse42_pcmpestrio128:
10872       Opcode = X86ISD::PCMPESTRI;
10873       X86CC = X86::COND_O;
10874       break;
10875     case Intrinsic::x86_sse42_pcmpistris128:
10876       Opcode = X86ISD::PCMPISTRI;
10877       X86CC = X86::COND_S;
10878       break;
10879     case Intrinsic::x86_sse42_pcmpestris128:
10880       Opcode = X86ISD::PCMPESTRI;
10881       X86CC = X86::COND_S;
10882       break;
10883     case Intrinsic::x86_sse42_pcmpistriz128:
10884       Opcode = X86ISD::PCMPISTRI;
10885       X86CC = X86::COND_E;
10886       break;
10887     case Intrinsic::x86_sse42_pcmpestriz128:
10888       Opcode = X86ISD::PCMPESTRI;
10889       X86CC = X86::COND_E;
10890       break;
10891     }
10892     SmallVector<SDValue, 5> NewOps;
10893     NewOps.append(Op->op_begin()+1, Op->op_end());
10894     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10895     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10896     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10897                                 DAG.getConstant(X86CC, MVT::i8),
10898                                 SDValue(PCMP.getNode(), 1));
10899     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10900   }
10901
10902   case Intrinsic::x86_sse42_pcmpistri128:
10903   case Intrinsic::x86_sse42_pcmpestri128: {
10904     unsigned Opcode;
10905     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10906       Opcode = X86ISD::PCMPISTRI;
10907     else
10908       Opcode = X86ISD::PCMPESTRI;
10909
10910     SmallVector<SDValue, 5> NewOps;
10911     NewOps.append(Op->op_begin()+1, Op->op_end());
10912     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10913     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10914   }
10915   case Intrinsic::x86_fma_vfmadd_ps:
10916   case Intrinsic::x86_fma_vfmadd_pd:
10917   case Intrinsic::x86_fma_vfmsub_ps:
10918   case Intrinsic::x86_fma_vfmsub_pd:
10919   case Intrinsic::x86_fma_vfnmadd_ps:
10920   case Intrinsic::x86_fma_vfnmadd_pd:
10921   case Intrinsic::x86_fma_vfnmsub_ps:
10922   case Intrinsic::x86_fma_vfnmsub_pd:
10923   case Intrinsic::x86_fma_vfmaddsub_ps:
10924   case Intrinsic::x86_fma_vfmaddsub_pd:
10925   case Intrinsic::x86_fma_vfmsubadd_ps:
10926   case Intrinsic::x86_fma_vfmsubadd_pd:
10927   case Intrinsic::x86_fma_vfmadd_ps_256:
10928   case Intrinsic::x86_fma_vfmadd_pd_256:
10929   case Intrinsic::x86_fma_vfmsub_ps_256:
10930   case Intrinsic::x86_fma_vfmsub_pd_256:
10931   case Intrinsic::x86_fma_vfnmadd_ps_256:
10932   case Intrinsic::x86_fma_vfnmadd_pd_256:
10933   case Intrinsic::x86_fma_vfnmsub_ps_256:
10934   case Intrinsic::x86_fma_vfnmsub_pd_256:
10935   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10936   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10937   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10938   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10939     unsigned Opc;
10940     switch (IntNo) {
10941     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10942     case Intrinsic::x86_fma_vfmadd_ps:
10943     case Intrinsic::x86_fma_vfmadd_pd:
10944     case Intrinsic::x86_fma_vfmadd_ps_256:
10945     case Intrinsic::x86_fma_vfmadd_pd_256:
10946       Opc = X86ISD::FMADD;
10947       break;
10948     case Intrinsic::x86_fma_vfmsub_ps:
10949     case Intrinsic::x86_fma_vfmsub_pd:
10950     case Intrinsic::x86_fma_vfmsub_ps_256:
10951     case Intrinsic::x86_fma_vfmsub_pd_256:
10952       Opc = X86ISD::FMSUB;
10953       break;
10954     case Intrinsic::x86_fma_vfnmadd_ps:
10955     case Intrinsic::x86_fma_vfnmadd_pd:
10956     case Intrinsic::x86_fma_vfnmadd_ps_256:
10957     case Intrinsic::x86_fma_vfnmadd_pd_256:
10958       Opc = X86ISD::FNMADD;
10959       break;
10960     case Intrinsic::x86_fma_vfnmsub_ps:
10961     case Intrinsic::x86_fma_vfnmsub_pd:
10962     case Intrinsic::x86_fma_vfnmsub_ps_256:
10963     case Intrinsic::x86_fma_vfnmsub_pd_256:
10964       Opc = X86ISD::FNMSUB;
10965       break;
10966     case Intrinsic::x86_fma_vfmaddsub_ps:
10967     case Intrinsic::x86_fma_vfmaddsub_pd:
10968     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10969     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10970       Opc = X86ISD::FMADDSUB;
10971       break;
10972     case Intrinsic::x86_fma_vfmsubadd_ps:
10973     case Intrinsic::x86_fma_vfmsubadd_pd:
10974     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10975     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10976       Opc = X86ISD::FMSUBADD;
10977       break;
10978     }
10979
10980     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10981                        Op.getOperand(2), Op.getOperand(3));
10982   }
10983   }
10984 }
10985
10986 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10987   SDLoc dl(Op);
10988   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10989   switch (IntNo) {
10990   default: return SDValue();    // Don't custom lower most intrinsics.
10991
10992   // RDRAND/RDSEED intrinsics.
10993   case Intrinsic::x86_rdrand_16:
10994   case Intrinsic::x86_rdrand_32:
10995   case Intrinsic::x86_rdrand_64:
10996   case Intrinsic::x86_rdseed_16:
10997   case Intrinsic::x86_rdseed_32:
10998   case Intrinsic::x86_rdseed_64: {
10999     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
11000                        IntNo == Intrinsic::x86_rdseed_32 ||
11001                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11002                                                             X86ISD::RDRAND;
11003     // Emit the node with the right value type.
11004     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11005     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11006
11007     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11008     // Otherwise return the value from Rand, which is always 0, casted to i32.
11009     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11010                       DAG.getConstant(1, Op->getValueType(1)),
11011                       DAG.getConstant(X86::COND_B, MVT::i32),
11012                       SDValue(Result.getNode(), 1) };
11013     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11014                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11015                                   Ops, array_lengthof(Ops));
11016
11017     // Return { result, isValid, chain }.
11018     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11019                        SDValue(Result.getNode(), 2));
11020   }
11021
11022   // XTEST intrinsics.
11023   case Intrinsic::x86_xtest: {
11024     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11025     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11026     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11027                                 DAG.getConstant(X86::COND_NE, MVT::i8),
11028                                 InTrans);
11029     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11030     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11031                        Ret, SDValue(InTrans.getNode(), 1));
11032   }
11033   }
11034 }
11035
11036 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11037                                            SelectionDAG &DAG) const {
11038   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11039   MFI->setReturnAddressIsTaken(true);
11040
11041   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11042   SDLoc dl(Op);
11043   EVT PtrVT = getPointerTy();
11044
11045   if (Depth > 0) {
11046     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11047     const X86RegisterInfo *RegInfo =
11048       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11049     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11050     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11051                        DAG.getNode(ISD::ADD, dl, PtrVT,
11052                                    FrameAddr, Offset),
11053                        MachinePointerInfo(), false, false, false, 0);
11054   }
11055
11056   // Just load the return address.
11057   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11058   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11059                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11060 }
11061
11062 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11063   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11064   MFI->setFrameAddressIsTaken(true);
11065
11066   EVT VT = Op.getValueType();
11067   SDLoc dl(Op);  // FIXME probably not meaningful
11068   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11069   const X86RegisterInfo *RegInfo =
11070     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11071   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11072   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11073           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11074          "Invalid Frame Register!");
11075   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11076   while (Depth--)
11077     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11078                             MachinePointerInfo(),
11079                             false, false, false, 0);
11080   return FrameAddr;
11081 }
11082
11083 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11084                                                      SelectionDAG &DAG) const {
11085   const X86RegisterInfo *RegInfo =
11086     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11087   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11088 }
11089
11090 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11091   SDValue Chain     = Op.getOperand(0);
11092   SDValue Offset    = Op.getOperand(1);
11093   SDValue Handler   = Op.getOperand(2);
11094   SDLoc dl      (Op);
11095
11096   EVT PtrVT = getPointerTy();
11097   const X86RegisterInfo *RegInfo =
11098     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11099   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11100   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11101           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11102          "Invalid Frame Register!");
11103   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11104   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11105
11106   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11107                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11108   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11109   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11110                        false, false, 0);
11111   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11112
11113   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11114                      DAG.getRegister(StoreAddrReg, PtrVT));
11115 }
11116
11117 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11118                                                SelectionDAG &DAG) const {
11119   SDLoc DL(Op);
11120   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11121                      DAG.getVTList(MVT::i32, MVT::Other),
11122                      Op.getOperand(0), Op.getOperand(1));
11123 }
11124
11125 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11126                                                 SelectionDAG &DAG) const {
11127   SDLoc DL(Op);
11128   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11129                      Op.getOperand(0), Op.getOperand(1));
11130 }
11131
11132 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11133   return Op.getOperand(0);
11134 }
11135
11136 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11137                                                 SelectionDAG &DAG) const {
11138   SDValue Root = Op.getOperand(0);
11139   SDValue Trmp = Op.getOperand(1); // trampoline
11140   SDValue FPtr = Op.getOperand(2); // nested function
11141   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11142   SDLoc dl (Op);
11143
11144   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11145   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11146
11147   if (Subtarget->is64Bit()) {
11148     SDValue OutChains[6];
11149
11150     // Large code-model.
11151     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11152     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11153
11154     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11155     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11156
11157     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11158
11159     // Load the pointer to the nested function into R11.
11160     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11161     SDValue Addr = Trmp;
11162     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11163                                 Addr, MachinePointerInfo(TrmpAddr),
11164                                 false, false, 0);
11165
11166     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11167                        DAG.getConstant(2, MVT::i64));
11168     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11169                                 MachinePointerInfo(TrmpAddr, 2),
11170                                 false, false, 2);
11171
11172     // Load the 'nest' parameter value into R10.
11173     // R10 is specified in X86CallingConv.td
11174     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11175     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11176                        DAG.getConstant(10, MVT::i64));
11177     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11178                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11179                                 false, false, 0);
11180
11181     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11182                        DAG.getConstant(12, MVT::i64));
11183     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11184                                 MachinePointerInfo(TrmpAddr, 12),
11185                                 false, false, 2);
11186
11187     // Jump to the nested function.
11188     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11189     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11190                        DAG.getConstant(20, MVT::i64));
11191     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11192                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11193                                 false, false, 0);
11194
11195     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11196     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11197                        DAG.getConstant(22, MVT::i64));
11198     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11199                                 MachinePointerInfo(TrmpAddr, 22),
11200                                 false, false, 0);
11201
11202     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11203   } else {
11204     const Function *Func =
11205       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11206     CallingConv::ID CC = Func->getCallingConv();
11207     unsigned NestReg;
11208
11209     switch (CC) {
11210     default:
11211       llvm_unreachable("Unsupported calling convention");
11212     case CallingConv::C:
11213     case CallingConv::X86_StdCall: {
11214       // Pass 'nest' parameter in ECX.
11215       // Must be kept in sync with X86CallingConv.td
11216       NestReg = X86::ECX;
11217
11218       // Check that ECX wasn't needed by an 'inreg' parameter.
11219       FunctionType *FTy = Func->getFunctionType();
11220       const AttributeSet &Attrs = Func->getAttributes();
11221
11222       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11223         unsigned InRegCount = 0;
11224         unsigned Idx = 1;
11225
11226         for (FunctionType::param_iterator I = FTy->param_begin(),
11227              E = FTy->param_end(); I != E; ++I, ++Idx)
11228           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11229             // FIXME: should only count parameters that are lowered to integers.
11230             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11231
11232         if (InRegCount > 2) {
11233           report_fatal_error("Nest register in use - reduce number of inreg"
11234                              " parameters!");
11235         }
11236       }
11237       break;
11238     }
11239     case CallingConv::X86_FastCall:
11240     case CallingConv::X86_ThisCall:
11241     case CallingConv::Fast:
11242       // Pass 'nest' parameter in EAX.
11243       // Must be kept in sync with X86CallingConv.td
11244       NestReg = X86::EAX;
11245       break;
11246     }
11247
11248     SDValue OutChains[4];
11249     SDValue Addr, Disp;
11250
11251     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11252                        DAG.getConstant(10, MVT::i32));
11253     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11254
11255     // This is storing the opcode for MOV32ri.
11256     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11257     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11258     OutChains[0] = DAG.getStore(Root, dl,
11259                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11260                                 Trmp, MachinePointerInfo(TrmpAddr),
11261                                 false, false, 0);
11262
11263     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11264                        DAG.getConstant(1, MVT::i32));
11265     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11266                                 MachinePointerInfo(TrmpAddr, 1),
11267                                 false, false, 1);
11268
11269     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11270     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11271                        DAG.getConstant(5, MVT::i32));
11272     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11273                                 MachinePointerInfo(TrmpAddr, 5),
11274                                 false, false, 1);
11275
11276     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11277                        DAG.getConstant(6, MVT::i32));
11278     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11279                                 MachinePointerInfo(TrmpAddr, 6),
11280                                 false, false, 1);
11281
11282     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11283   }
11284 }
11285
11286 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11287                                             SelectionDAG &DAG) const {
11288   /*
11289    The rounding mode is in bits 11:10 of FPSR, and has the following
11290    settings:
11291      00 Round to nearest
11292      01 Round to -inf
11293      10 Round to +inf
11294      11 Round to 0
11295
11296   FLT_ROUNDS, on the other hand, expects the following:
11297     -1 Undefined
11298      0 Round to 0
11299      1 Round to nearest
11300      2 Round to +inf
11301      3 Round to -inf
11302
11303   To perform the conversion, we do:
11304     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11305   */
11306
11307   MachineFunction &MF = DAG.getMachineFunction();
11308   const TargetMachine &TM = MF.getTarget();
11309   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11310   unsigned StackAlignment = TFI.getStackAlignment();
11311   EVT VT = Op.getValueType();
11312   SDLoc DL(Op);
11313
11314   // Save FP Control Word to stack slot
11315   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11316   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11317
11318   MachineMemOperand *MMO =
11319    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11320                            MachineMemOperand::MOStore, 2, 2);
11321
11322   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11323   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11324                                           DAG.getVTList(MVT::Other),
11325                                           Ops, array_lengthof(Ops), MVT::i16,
11326                                           MMO);
11327
11328   // Load FP Control Word from stack slot
11329   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11330                             MachinePointerInfo(), false, false, false, 0);
11331
11332   // Transform as necessary
11333   SDValue CWD1 =
11334     DAG.getNode(ISD::SRL, DL, MVT::i16,
11335                 DAG.getNode(ISD::AND, DL, MVT::i16,
11336                             CWD, DAG.getConstant(0x800, MVT::i16)),
11337                 DAG.getConstant(11, MVT::i8));
11338   SDValue CWD2 =
11339     DAG.getNode(ISD::SRL, DL, MVT::i16,
11340                 DAG.getNode(ISD::AND, DL, MVT::i16,
11341                             CWD, DAG.getConstant(0x400, MVT::i16)),
11342                 DAG.getConstant(9, MVT::i8));
11343
11344   SDValue RetVal =
11345     DAG.getNode(ISD::AND, DL, MVT::i16,
11346                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11347                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11348                             DAG.getConstant(1, MVT::i16)),
11349                 DAG.getConstant(3, MVT::i16));
11350
11351   return DAG.getNode((VT.getSizeInBits() < 16 ?
11352                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11353 }
11354
11355 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11356   EVT VT = Op.getValueType();
11357   EVT OpVT = VT;
11358   unsigned NumBits = VT.getSizeInBits();
11359   SDLoc dl(Op);
11360
11361   Op = Op.getOperand(0);
11362   if (VT == MVT::i8) {
11363     // Zero extend to i32 since there is not an i8 bsr.
11364     OpVT = MVT::i32;
11365     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11366   }
11367
11368   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11369   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11370   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11371
11372   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11373   SDValue Ops[] = {
11374     Op,
11375     DAG.getConstant(NumBits+NumBits-1, OpVT),
11376     DAG.getConstant(X86::COND_E, MVT::i8),
11377     Op.getValue(1)
11378   };
11379   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11380
11381   // Finally xor with NumBits-1.
11382   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11383
11384   if (VT == MVT::i8)
11385     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11386   return Op;
11387 }
11388
11389 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11390   EVT VT = Op.getValueType();
11391   EVT OpVT = VT;
11392   unsigned NumBits = VT.getSizeInBits();
11393   SDLoc dl(Op);
11394
11395   Op = Op.getOperand(0);
11396   if (VT == MVT::i8) {
11397     // Zero extend to i32 since there is not an i8 bsr.
11398     OpVT = MVT::i32;
11399     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11400   }
11401
11402   // Issue a bsr (scan bits in reverse).
11403   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11404   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11405
11406   // And xor with NumBits-1.
11407   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11408
11409   if (VT == MVT::i8)
11410     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11411   return Op;
11412 }
11413
11414 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11415   EVT VT = Op.getValueType();
11416   unsigned NumBits = VT.getSizeInBits();
11417   SDLoc dl(Op);
11418   Op = Op.getOperand(0);
11419
11420   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11421   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11422   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11423
11424   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11425   SDValue Ops[] = {
11426     Op,
11427     DAG.getConstant(NumBits, VT),
11428     DAG.getConstant(X86::COND_E, MVT::i8),
11429     Op.getValue(1)
11430   };
11431   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11432 }
11433
11434 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11435 // ones, and then concatenate the result back.
11436 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11437   EVT VT = Op.getValueType();
11438
11439   assert(VT.is256BitVector() && VT.isInteger() &&
11440          "Unsupported value type for operation");
11441
11442   unsigned NumElems = VT.getVectorNumElements();
11443   SDLoc dl(Op);
11444
11445   // Extract the LHS vectors
11446   SDValue LHS = Op.getOperand(0);
11447   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11448   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11449
11450   // Extract the RHS vectors
11451   SDValue RHS = Op.getOperand(1);
11452   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11453   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11454
11455   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11456   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11457
11458   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11459                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11460                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11461 }
11462
11463 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11464   assert(Op.getValueType().is256BitVector() &&
11465          Op.getValueType().isInteger() &&
11466          "Only handle AVX 256-bit vector integer operation");
11467   return Lower256IntArith(Op, DAG);
11468 }
11469
11470 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11471   assert(Op.getValueType().is256BitVector() &&
11472          Op.getValueType().isInteger() &&
11473          "Only handle AVX 256-bit vector integer operation");
11474   return Lower256IntArith(Op, DAG);
11475 }
11476
11477 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11478                         SelectionDAG &DAG) {
11479   SDLoc dl(Op);
11480   EVT VT = Op.getValueType();
11481
11482   // Decompose 256-bit ops into smaller 128-bit ops.
11483   if (VT.is256BitVector() && !Subtarget->hasInt256())
11484     return Lower256IntArith(Op, DAG);
11485
11486   SDValue A = Op.getOperand(0);
11487   SDValue B = Op.getOperand(1);
11488
11489   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11490   if (VT == MVT::v4i32) {
11491     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11492            "Should not custom lower when pmuldq is available!");
11493
11494     // Extract the odd parts.
11495     static const int UnpackMask[] = { 1, -1, 3, -1 };
11496     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11497     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11498
11499     // Multiply the even parts.
11500     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11501     // Now multiply odd parts.
11502     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11503
11504     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11505     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11506
11507     // Merge the two vectors back together with a shuffle. This expands into 2
11508     // shuffles.
11509     static const int ShufMask[] = { 0, 4, 2, 6 };
11510     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11511   }
11512
11513   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11514          "Only know how to lower V2I64/V4I64 multiply");
11515
11516   //  Ahi = psrlqi(a, 32);
11517   //  Bhi = psrlqi(b, 32);
11518   //
11519   //  AloBlo = pmuludq(a, b);
11520   //  AloBhi = pmuludq(a, Bhi);
11521   //  AhiBlo = pmuludq(Ahi, b);
11522
11523   //  AloBhi = psllqi(AloBhi, 32);
11524   //  AhiBlo = psllqi(AhiBlo, 32);
11525   //  return AloBlo + AloBhi + AhiBlo;
11526
11527   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11528
11529   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11530   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11531
11532   // Bit cast to 32-bit vectors for MULUDQ
11533   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11534   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11535   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11536   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11537   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11538
11539   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11540   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11541   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11542
11543   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11544   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11545
11546   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11547   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11548 }
11549
11550 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11551   EVT VT = Op.getValueType();
11552   EVT EltTy = VT.getVectorElementType();
11553   unsigned NumElts = VT.getVectorNumElements();
11554   SDValue N0 = Op.getOperand(0);
11555   SDLoc dl(Op);
11556
11557   // Lower sdiv X, pow2-const.
11558   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11559   if (!C)
11560     return SDValue();
11561
11562   APInt SplatValue, SplatUndef;
11563   unsigned SplatBitSize;
11564   bool HasAnyUndefs;
11565   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11566                           HasAnyUndefs) ||
11567       EltTy.getSizeInBits() < SplatBitSize)
11568     return SDValue();
11569
11570   if ((SplatValue != 0) &&
11571       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11572     unsigned lg2 = SplatValue.countTrailingZeros();
11573     // Splat the sign bit.
11574     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11575     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11576     // Add (N0 < 0) ? abs2 - 1 : 0;
11577     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11578     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11579     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11580     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11581     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11582
11583     // If we're dividing by a positive value, we're done.  Otherwise, we must
11584     // negate the result.
11585     if (SplatValue.isNonNegative())
11586       return SRA;
11587
11588     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11589     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11590     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11591   }
11592   return SDValue();
11593 }
11594
11595 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11596                                          const X86Subtarget *Subtarget) {
11597   EVT VT = Op.getValueType();
11598   SDLoc dl(Op);
11599   SDValue R = Op.getOperand(0);
11600   SDValue Amt = Op.getOperand(1);
11601
11602   // Optimize shl/srl/sra with constant shift amount.
11603   if (isSplatVector(Amt.getNode())) {
11604     SDValue SclrAmt = Amt->getOperand(0);
11605     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11606       uint64_t ShiftAmt = C->getZExtValue();
11607
11608       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11609           (Subtarget->hasInt256() &&
11610            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11611         if (Op.getOpcode() == ISD::SHL)
11612           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11613                              DAG.getConstant(ShiftAmt, MVT::i32));
11614         if (Op.getOpcode() == ISD::SRL)
11615           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11616                              DAG.getConstant(ShiftAmt, MVT::i32));
11617         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11618           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11619                              DAG.getConstant(ShiftAmt, MVT::i32));
11620       }
11621
11622       if (VT == MVT::v16i8) {
11623         if (Op.getOpcode() == ISD::SHL) {
11624           // Make a large shift.
11625           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11626                                     DAG.getConstant(ShiftAmt, MVT::i32));
11627           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11628           // Zero out the rightmost bits.
11629           SmallVector<SDValue, 16> V(16,
11630                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11631                                                      MVT::i8));
11632           return DAG.getNode(ISD::AND, dl, VT, SHL,
11633                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11634         }
11635         if (Op.getOpcode() == ISD::SRL) {
11636           // Make a large shift.
11637           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11638                                     DAG.getConstant(ShiftAmt, MVT::i32));
11639           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11640           // Zero out the leftmost bits.
11641           SmallVector<SDValue, 16> V(16,
11642                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11643                                                      MVT::i8));
11644           return DAG.getNode(ISD::AND, dl, VT, SRL,
11645                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11646         }
11647         if (Op.getOpcode() == ISD::SRA) {
11648           if (ShiftAmt == 7) {
11649             // R s>> 7  ===  R s< 0
11650             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11651             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11652           }
11653
11654           // R s>> a === ((R u>> a) ^ m) - m
11655           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11656           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11657                                                          MVT::i8));
11658           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11659           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11660           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11661           return Res;
11662         }
11663         llvm_unreachable("Unknown shift opcode.");
11664       }
11665
11666       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11667         if (Op.getOpcode() == ISD::SHL) {
11668           // Make a large shift.
11669           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11670                                     DAG.getConstant(ShiftAmt, MVT::i32));
11671           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11672           // Zero out the rightmost bits.
11673           SmallVector<SDValue, 32> V(32,
11674                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11675                                                      MVT::i8));
11676           return DAG.getNode(ISD::AND, dl, VT, SHL,
11677                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11678         }
11679         if (Op.getOpcode() == ISD::SRL) {
11680           // Make a large shift.
11681           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11682                                     DAG.getConstant(ShiftAmt, MVT::i32));
11683           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11684           // Zero out the leftmost bits.
11685           SmallVector<SDValue, 32> V(32,
11686                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11687                                                      MVT::i8));
11688           return DAG.getNode(ISD::AND, dl, VT, SRL,
11689                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11690         }
11691         if (Op.getOpcode() == ISD::SRA) {
11692           if (ShiftAmt == 7) {
11693             // R s>> 7  ===  R s< 0
11694             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11695             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11696           }
11697
11698           // R s>> a === ((R u>> a) ^ m) - m
11699           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11700           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11701                                                          MVT::i8));
11702           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11703           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11704           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11705           return Res;
11706         }
11707         llvm_unreachable("Unknown shift opcode.");
11708       }
11709     }
11710   }
11711
11712   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11713   if (!Subtarget->is64Bit() &&
11714       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11715       Amt.getOpcode() == ISD::BITCAST &&
11716       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11717     Amt = Amt.getOperand(0);
11718     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11719                      VT.getVectorNumElements();
11720     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11721     uint64_t ShiftAmt = 0;
11722     for (unsigned i = 0; i != Ratio; ++i) {
11723       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11724       if (C == 0)
11725         return SDValue();
11726       // 6 == Log2(64)
11727       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11728     }
11729     // Check remaining shift amounts.
11730     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11731       uint64_t ShAmt = 0;
11732       for (unsigned j = 0; j != Ratio; ++j) {
11733         ConstantSDNode *C =
11734           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11735         if (C == 0)
11736           return SDValue();
11737         // 6 == Log2(64)
11738         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11739       }
11740       if (ShAmt != ShiftAmt)
11741         return SDValue();
11742     }
11743     switch (Op.getOpcode()) {
11744     default:
11745       llvm_unreachable("Unknown shift opcode!");
11746     case ISD::SHL:
11747       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11748                          DAG.getConstant(ShiftAmt, MVT::i32));
11749     case ISD::SRL:
11750       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11751                          DAG.getConstant(ShiftAmt, MVT::i32));
11752     case ISD::SRA:
11753       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11754                          DAG.getConstant(ShiftAmt, MVT::i32));
11755     }
11756   }
11757
11758   return SDValue();
11759 }
11760
11761 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11762                                         const X86Subtarget* Subtarget) {
11763   EVT VT = Op.getValueType();
11764   SDLoc dl(Op);
11765   SDValue R = Op.getOperand(0);
11766   SDValue Amt = Op.getOperand(1);
11767
11768   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11769       VT == MVT::v4i32 || VT == MVT::v8i16 ||
11770       (Subtarget->hasInt256() &&
11771        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11772         VT == MVT::v8i32 || VT == MVT::v16i16))) {
11773     SDValue BaseShAmt;
11774     EVT EltVT = VT.getVectorElementType();
11775
11776     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11777       unsigned NumElts = VT.getVectorNumElements();
11778       unsigned i, j;
11779       for (i = 0; i != NumElts; ++i) {
11780         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11781           continue;
11782         break;
11783       }
11784       for (j = i; j != NumElts; ++j) {
11785         SDValue Arg = Amt.getOperand(j);
11786         if (Arg.getOpcode() == ISD::UNDEF) continue;
11787         if (Arg != Amt.getOperand(i))
11788           break;
11789       }
11790       if (i != NumElts && j == NumElts)
11791         BaseShAmt = Amt.getOperand(i);
11792     } else {
11793       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11794         Amt = Amt.getOperand(0);
11795       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11796                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11797         SDValue InVec = Amt.getOperand(0);
11798         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11799           unsigned NumElts = InVec.getValueType().getVectorNumElements();
11800           unsigned i = 0;
11801           for (; i != NumElts; ++i) {
11802             SDValue Arg = InVec.getOperand(i);
11803             if (Arg.getOpcode() == ISD::UNDEF) continue;
11804             BaseShAmt = Arg;
11805             break;
11806           }
11807         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11808            if (ConstantSDNode *C =
11809                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11810              unsigned SplatIdx =
11811                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11812              if (C->getZExtValue() == SplatIdx)
11813                BaseShAmt = InVec.getOperand(1);
11814            }
11815         }
11816         if (BaseShAmt.getNode() == 0)
11817           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11818                                   DAG.getIntPtrConstant(0));
11819       }
11820     }
11821
11822     if (BaseShAmt.getNode()) {
11823       if (EltVT.bitsGT(MVT::i32))
11824         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11825       else if (EltVT.bitsLT(MVT::i32))
11826         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11827
11828       switch (Op.getOpcode()) {
11829       default:
11830         llvm_unreachable("Unknown shift opcode!");
11831       case ISD::SHL:
11832         switch (VT.getSimpleVT().SimpleTy) {
11833         default: return SDValue();
11834         case MVT::v2i64:
11835         case MVT::v4i32:
11836         case MVT::v8i16:
11837         case MVT::v4i64:
11838         case MVT::v8i32:
11839         case MVT::v16i16:
11840           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11841         }
11842       case ISD::SRA:
11843         switch (VT.getSimpleVT().SimpleTy) {
11844         default: return SDValue();
11845         case MVT::v4i32:
11846         case MVT::v8i16:
11847         case MVT::v8i32:
11848         case MVT::v16i16:
11849           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11850         }
11851       case ISD::SRL:
11852         switch (VT.getSimpleVT().SimpleTy) {
11853         default: return SDValue();
11854         case MVT::v2i64:
11855         case MVT::v4i32:
11856         case MVT::v8i16:
11857         case MVT::v4i64:
11858         case MVT::v8i32:
11859         case MVT::v16i16:
11860           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11861         }
11862       }
11863     }
11864   }
11865
11866   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11867   if (!Subtarget->is64Bit() &&
11868       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11869       Amt.getOpcode() == ISD::BITCAST &&
11870       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11871     Amt = Amt.getOperand(0);
11872     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11873                      VT.getVectorNumElements();
11874     std::vector<SDValue> Vals(Ratio);
11875     for (unsigned i = 0; i != Ratio; ++i)
11876       Vals[i] = Amt.getOperand(i);
11877     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11878       for (unsigned j = 0; j != Ratio; ++j)
11879         if (Vals[j] != Amt.getOperand(i + j))
11880           return SDValue();
11881     }
11882     switch (Op.getOpcode()) {
11883     default:
11884       llvm_unreachable("Unknown shift opcode!");
11885     case ISD::SHL:
11886       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11887     case ISD::SRL:
11888       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11889     case ISD::SRA:
11890       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11891     }
11892   }
11893
11894   return SDValue();
11895 }
11896
11897 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11898
11899   EVT VT = Op.getValueType();
11900   SDLoc dl(Op);
11901   SDValue R = Op.getOperand(0);
11902   SDValue Amt = Op.getOperand(1);
11903   SDValue V;
11904
11905   if (!Subtarget->hasSSE2())
11906     return SDValue();
11907
11908   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11909   if (V.getNode())
11910     return V;
11911
11912   V = LowerScalarVariableShift(Op, DAG, Subtarget);
11913   if (V.getNode())
11914       return V;
11915
11916   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11917   if (Subtarget->hasInt256()) {
11918     if (Op.getOpcode() == ISD::SRL &&
11919         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11920          VT == MVT::v4i64 || VT == MVT::v8i32))
11921       return Op;
11922     if (Op.getOpcode() == ISD::SHL &&
11923         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11924          VT == MVT::v4i64 || VT == MVT::v8i32))
11925       return Op;
11926     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11927       return Op;
11928   }
11929
11930   // Lower SHL with variable shift amount.
11931   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11932     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11933
11934     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11935     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11936     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11937     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11938   }
11939   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11940     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11941
11942     // a = a << 5;
11943     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11944     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11945
11946     // Turn 'a' into a mask suitable for VSELECT
11947     SDValue VSelM = DAG.getConstant(0x80, VT);
11948     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11949     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11950
11951     SDValue CM1 = DAG.getConstant(0x0f, VT);
11952     SDValue CM2 = DAG.getConstant(0x3f, VT);
11953
11954     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11955     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11956     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11957                             DAG.getConstant(4, MVT::i32), DAG);
11958     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11959     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11960
11961     // a += a
11962     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11963     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11964     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11965
11966     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11967     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11968     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11969                             DAG.getConstant(2, MVT::i32), DAG);
11970     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11971     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11972
11973     // a += a
11974     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11975     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11976     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11977
11978     // return VSELECT(r, r+r, a);
11979     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11980                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11981     return R;
11982   }
11983
11984   // Decompose 256-bit shifts into smaller 128-bit shifts.
11985   if (VT.is256BitVector()) {
11986     unsigned NumElems = VT.getVectorNumElements();
11987     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11988     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11989
11990     // Extract the two vectors
11991     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11992     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11993
11994     // Recreate the shift amount vectors
11995     SDValue Amt1, Amt2;
11996     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11997       // Constant shift amount
11998       SmallVector<SDValue, 4> Amt1Csts;
11999       SmallVector<SDValue, 4> Amt2Csts;
12000       for (unsigned i = 0; i != NumElems/2; ++i)
12001         Amt1Csts.push_back(Amt->getOperand(i));
12002       for (unsigned i = NumElems/2; i != NumElems; ++i)
12003         Amt2Csts.push_back(Amt->getOperand(i));
12004
12005       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12006                                  &Amt1Csts[0], NumElems/2);
12007       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12008                                  &Amt2Csts[0], NumElems/2);
12009     } else {
12010       // Variable shift amount
12011       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12012       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12013     }
12014
12015     // Issue new vector shifts for the smaller types
12016     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12017     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12018
12019     // Concatenate the result back
12020     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12021   }
12022
12023   return SDValue();
12024 }
12025
12026 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12027   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12028   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12029   // looks for this combo and may remove the "setcc" instruction if the "setcc"
12030   // has only one use.
12031   SDNode *N = Op.getNode();
12032   SDValue LHS = N->getOperand(0);
12033   SDValue RHS = N->getOperand(1);
12034   unsigned BaseOp = 0;
12035   unsigned Cond = 0;
12036   SDLoc DL(Op);
12037   switch (Op.getOpcode()) {
12038   default: llvm_unreachable("Unknown ovf instruction!");
12039   case ISD::SADDO:
12040     // A subtract of one will be selected as a INC. Note that INC doesn't
12041     // set CF, so we can't do this for UADDO.
12042     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12043       if (C->isOne()) {
12044         BaseOp = X86ISD::INC;
12045         Cond = X86::COND_O;
12046         break;
12047       }
12048     BaseOp = X86ISD::ADD;
12049     Cond = X86::COND_O;
12050     break;
12051   case ISD::UADDO:
12052     BaseOp = X86ISD::ADD;
12053     Cond = X86::COND_B;
12054     break;
12055   case ISD::SSUBO:
12056     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12057     // set CF, so we can't do this for USUBO.
12058     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12059       if (C->isOne()) {
12060         BaseOp = X86ISD::DEC;
12061         Cond = X86::COND_O;
12062         break;
12063       }
12064     BaseOp = X86ISD::SUB;
12065     Cond = X86::COND_O;
12066     break;
12067   case ISD::USUBO:
12068     BaseOp = X86ISD::SUB;
12069     Cond = X86::COND_B;
12070     break;
12071   case ISD::SMULO:
12072     BaseOp = X86ISD::SMUL;
12073     Cond = X86::COND_O;
12074     break;
12075   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12076     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12077                                  MVT::i32);
12078     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12079
12080     SDValue SetCC =
12081       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12082                   DAG.getConstant(X86::COND_O, MVT::i32),
12083                   SDValue(Sum.getNode(), 2));
12084
12085     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12086   }
12087   }
12088
12089   // Also sets EFLAGS.
12090   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12091   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12092
12093   SDValue SetCC =
12094     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12095                 DAG.getConstant(Cond, MVT::i32),
12096                 SDValue(Sum.getNode(), 1));
12097
12098   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12099 }
12100
12101 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12102                                                   SelectionDAG &DAG) const {
12103   SDLoc dl(Op);
12104   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12105   EVT VT = Op.getValueType();
12106
12107   if (!Subtarget->hasSSE2() || !VT.isVector())
12108     return SDValue();
12109
12110   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12111                       ExtraVT.getScalarType().getSizeInBits();
12112   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12113
12114   switch (VT.getSimpleVT().SimpleTy) {
12115     default: return SDValue();
12116     case MVT::v8i32:
12117     case MVT::v16i16:
12118       if (!Subtarget->hasFp256())
12119         return SDValue();
12120       if (!Subtarget->hasInt256()) {
12121         // needs to be split
12122         unsigned NumElems = VT.getVectorNumElements();
12123
12124         // Extract the LHS vectors
12125         SDValue LHS = Op.getOperand(0);
12126         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12127         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12128
12129         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12130         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12131
12132         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12133         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12134         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12135                                    ExtraNumElems/2);
12136         SDValue Extra = DAG.getValueType(ExtraVT);
12137
12138         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12139         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12140
12141         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12142       }
12143       // fall through
12144     case MVT::v4i32:
12145     case MVT::v8i16: {
12146       // (sext (vzext x)) -> (vsext x)
12147       SDValue Op0 = Op.getOperand(0);
12148       SDValue Op00 = Op0.getOperand(0);
12149       SDValue Tmp1;
12150       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12151       if (Op0.getOpcode() == ISD::BITCAST &&
12152           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12153         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12154       if (Tmp1.getNode()) {
12155         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12156         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12157                "This optimization is invalid without a VZEXT.");
12158         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12159       }
12160
12161       // If the above didn't work, then just use Shift-Left + Shift-Right.
12162       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12163       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12164     }
12165   }
12166 }
12167
12168 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12169                                  SelectionDAG &DAG) {
12170   SDLoc dl(Op);
12171   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12172     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12173   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12174     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12175
12176   // The only fence that needs an instruction is a sequentially-consistent
12177   // cross-thread fence.
12178   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12179     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12180     // no-sse2). There isn't any reason to disable it if the target processor
12181     // supports it.
12182     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12183       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12184
12185     SDValue Chain = Op.getOperand(0);
12186     SDValue Zero = DAG.getConstant(0, MVT::i32);
12187     SDValue Ops[] = {
12188       DAG.getRegister(X86::ESP, MVT::i32), // Base
12189       DAG.getTargetConstant(1, MVT::i8),   // Scale
12190       DAG.getRegister(0, MVT::i32),        // Index
12191       DAG.getTargetConstant(0, MVT::i32),  // Disp
12192       DAG.getRegister(0, MVT::i32),        // Segment.
12193       Zero,
12194       Chain
12195     };
12196     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12197     return SDValue(Res, 0);
12198   }
12199
12200   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12201   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12202 }
12203
12204 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12205                              SelectionDAG &DAG) {
12206   EVT T = Op.getValueType();
12207   SDLoc DL(Op);
12208   unsigned Reg = 0;
12209   unsigned size = 0;
12210   switch(T.getSimpleVT().SimpleTy) {
12211   default: llvm_unreachable("Invalid value type!");
12212   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12213   case MVT::i16: Reg = X86::AX;  size = 2; break;
12214   case MVT::i32: Reg = X86::EAX; size = 4; break;
12215   case MVT::i64:
12216     assert(Subtarget->is64Bit() && "Node not type legal!");
12217     Reg = X86::RAX; size = 8;
12218     break;
12219   }
12220   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12221                                     Op.getOperand(2), SDValue());
12222   SDValue Ops[] = { cpIn.getValue(0),
12223                     Op.getOperand(1),
12224                     Op.getOperand(3),
12225                     DAG.getTargetConstant(size, MVT::i8),
12226                     cpIn.getValue(1) };
12227   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12228   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12229   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12230                                            Ops, array_lengthof(Ops), T, MMO);
12231   SDValue cpOut =
12232     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12233   return cpOut;
12234 }
12235
12236 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12237                                      SelectionDAG &DAG) {
12238   assert(Subtarget->is64Bit() && "Result not type legalized?");
12239   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12240   SDValue TheChain = Op.getOperand(0);
12241   SDLoc dl(Op);
12242   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12243   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12244   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12245                                    rax.getValue(2));
12246   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12247                             DAG.getConstant(32, MVT::i8));
12248   SDValue Ops[] = {
12249     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12250     rdx.getValue(1)
12251   };
12252   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12253 }
12254
12255 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12256   EVT SrcVT = Op.getOperand(0).getValueType();
12257   EVT DstVT = Op.getValueType();
12258   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12259          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12260   assert((DstVT == MVT::i64 ||
12261           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12262          "Unexpected custom BITCAST");
12263   // i64 <=> MMX conversions are Legal.
12264   if (SrcVT==MVT::i64 && DstVT.isVector())
12265     return Op;
12266   if (DstVT==MVT::i64 && SrcVT.isVector())
12267     return Op;
12268   // MMX <=> MMX conversions are Legal.
12269   if (SrcVT.isVector() && DstVT.isVector())
12270     return Op;
12271   // All other conversions need to be expanded.
12272   return SDValue();
12273 }
12274
12275 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12276   SDNode *Node = Op.getNode();
12277   SDLoc dl(Node);
12278   EVT T = Node->getValueType(0);
12279   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12280                               DAG.getConstant(0, T), Node->getOperand(2));
12281   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12282                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12283                        Node->getOperand(0),
12284                        Node->getOperand(1), negOp,
12285                        cast<AtomicSDNode>(Node)->getSrcValue(),
12286                        cast<AtomicSDNode>(Node)->getAlignment(),
12287                        cast<AtomicSDNode>(Node)->getOrdering(),
12288                        cast<AtomicSDNode>(Node)->getSynchScope());
12289 }
12290
12291 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12292   SDNode *Node = Op.getNode();
12293   SDLoc dl(Node);
12294   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12295
12296   // Convert seq_cst store -> xchg
12297   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12298   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12299   //        (The only way to get a 16-byte store is cmpxchg16b)
12300   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12301   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12302       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12303     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12304                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12305                                  Node->getOperand(0),
12306                                  Node->getOperand(1), Node->getOperand(2),
12307                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12308                                  cast<AtomicSDNode>(Node)->getOrdering(),
12309                                  cast<AtomicSDNode>(Node)->getSynchScope());
12310     return Swap.getValue(1);
12311   }
12312   // Other atomic stores have a simple pattern.
12313   return Op;
12314 }
12315
12316 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12317   EVT VT = Op.getNode()->getValueType(0);
12318
12319   // Let legalize expand this if it isn't a legal type yet.
12320   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12321     return SDValue();
12322
12323   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12324
12325   unsigned Opc;
12326   bool ExtraOp = false;
12327   switch (Op.getOpcode()) {
12328   default: llvm_unreachable("Invalid code");
12329   case ISD::ADDC: Opc = X86ISD::ADD; break;
12330   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12331   case ISD::SUBC: Opc = X86ISD::SUB; break;
12332   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12333   }
12334
12335   if (!ExtraOp)
12336     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12337                        Op.getOperand(1));
12338   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12339                      Op.getOperand(1), Op.getOperand(2));
12340 }
12341
12342 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12343   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12344
12345   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12346   // which returns the values as { float, float } (in XMM0) or
12347   // { double, double } (which is returned in XMM0, XMM1).
12348   SDLoc dl(Op);
12349   SDValue Arg = Op.getOperand(0);
12350   EVT ArgVT = Arg.getValueType();
12351   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12352
12353   ArgListTy Args;
12354   ArgListEntry Entry;
12355
12356   Entry.Node = Arg;
12357   Entry.Ty = ArgTy;
12358   Entry.isSExt = false;
12359   Entry.isZExt = false;
12360   Args.push_back(Entry);
12361
12362   bool isF64 = ArgVT == MVT::f64;
12363   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12364   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12365   // the results are returned via SRet in memory.
12366   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12367   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12368
12369   Type *RetTy = isF64
12370     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12371     : (Type*)VectorType::get(ArgTy, 4);
12372   TargetLowering::
12373     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12374                          false, false, false, false, 0,
12375                          CallingConv::C, /*isTaillCall=*/false,
12376                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12377                          Callee, Args, DAG, dl);
12378   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12379
12380   if (isF64)
12381     // Returned in xmm0 and xmm1.
12382     return CallResult.first;
12383
12384   // Returned in bits 0:31 and 32:64 xmm0.
12385   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12386                                CallResult.first, DAG.getIntPtrConstant(0));
12387   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12388                                CallResult.first, DAG.getIntPtrConstant(1));
12389   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12390   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12391 }
12392
12393 /// LowerOperation - Provide custom lowering hooks for some operations.
12394 ///
12395 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12396   switch (Op.getOpcode()) {
12397   default: llvm_unreachable("Should not custom lower this!");
12398   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12399   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12400   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12401   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12402   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12403   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12404   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12405   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12406   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12407   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12408   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12409   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12410   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12411   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12412   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12413   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12414   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12415   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12416   case ISD::SHL_PARTS:
12417   case ISD::SRA_PARTS:
12418   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12419   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12420   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12421   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12422   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12423   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12424   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12425   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12426   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12427   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12428   case ISD::FABS:               return LowerFABS(Op, DAG);
12429   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12430   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12431   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12432   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12433   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12434   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12435   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12436   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12437   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12438   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12439   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12440   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12441   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12442   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12443   case ISD::FRAME_TO_ARGS_OFFSET:
12444                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12445   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12446   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12447   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12448   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12449   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12450   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12451   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12452   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12453   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12454   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12455   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12456   case ISD::SRA:
12457   case ISD::SRL:
12458   case ISD::SHL:                return LowerShift(Op, DAG);
12459   case ISD::SADDO:
12460   case ISD::UADDO:
12461   case ISD::SSUBO:
12462   case ISD::USUBO:
12463   case ISD::SMULO:
12464   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12465   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12466   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12467   case ISD::ADDC:
12468   case ISD::ADDE:
12469   case ISD::SUBC:
12470   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12471   case ISD::ADD:                return LowerADD(Op, DAG);
12472   case ISD::SUB:                return LowerSUB(Op, DAG);
12473   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12474   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12475   }
12476 }
12477
12478 static void ReplaceATOMIC_LOAD(SDNode *Node,
12479                                   SmallVectorImpl<SDValue> &Results,
12480                                   SelectionDAG &DAG) {
12481   SDLoc dl(Node);
12482   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12483
12484   // Convert wide load -> cmpxchg8b/cmpxchg16b
12485   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12486   //        (The only way to get a 16-byte load is cmpxchg16b)
12487   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12488   SDValue Zero = DAG.getConstant(0, VT);
12489   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12490                                Node->getOperand(0),
12491                                Node->getOperand(1), Zero, Zero,
12492                                cast<AtomicSDNode>(Node)->getMemOperand(),
12493                                cast<AtomicSDNode>(Node)->getOrdering(),
12494                                cast<AtomicSDNode>(Node)->getSynchScope());
12495   Results.push_back(Swap.getValue(0));
12496   Results.push_back(Swap.getValue(1));
12497 }
12498
12499 static void
12500 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12501                         SelectionDAG &DAG, unsigned NewOp) {
12502   SDLoc dl(Node);
12503   assert (Node->getValueType(0) == MVT::i64 &&
12504           "Only know how to expand i64 atomics");
12505
12506   SDValue Chain = Node->getOperand(0);
12507   SDValue In1 = Node->getOperand(1);
12508   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12509                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12510   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12511                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12512   SDValue Ops[] = { Chain, In1, In2L, In2H };
12513   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12514   SDValue Result =
12515     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12516                             cast<MemSDNode>(Node)->getMemOperand());
12517   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12518   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12519   Results.push_back(Result.getValue(2));
12520 }
12521
12522 /// ReplaceNodeResults - Replace a node with an illegal result type
12523 /// with a new node built out of custom code.
12524 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12525                                            SmallVectorImpl<SDValue>&Results,
12526                                            SelectionDAG &DAG) const {
12527   SDLoc dl(N);
12528   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12529   switch (N->getOpcode()) {
12530   default:
12531     llvm_unreachable("Do not know how to custom type legalize this operation!");
12532   case ISD::SIGN_EXTEND_INREG:
12533   case ISD::ADDC:
12534   case ISD::ADDE:
12535   case ISD::SUBC:
12536   case ISD::SUBE:
12537     // We don't want to expand or promote these.
12538     return;
12539   case ISD::FP_TO_SINT:
12540   case ISD::FP_TO_UINT: {
12541     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12542
12543     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12544       return;
12545
12546     std::pair<SDValue,SDValue> Vals =
12547         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12548     SDValue FIST = Vals.first, StackSlot = Vals.second;
12549     if (FIST.getNode() != 0) {
12550       EVT VT = N->getValueType(0);
12551       // Return a load from the stack slot.
12552       if (StackSlot.getNode() != 0)
12553         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12554                                       MachinePointerInfo(),
12555                                       false, false, false, 0));
12556       else
12557         Results.push_back(FIST);
12558     }
12559     return;
12560   }
12561   case ISD::UINT_TO_FP: {
12562     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12563     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12564         N->getValueType(0) != MVT::v2f32)
12565       return;
12566     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12567                                  N->getOperand(0));
12568     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12569                                      MVT::f64);
12570     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12571     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12572                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12573     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12574     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12575     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12576     return;
12577   }
12578   case ISD::FP_ROUND: {
12579     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12580         return;
12581     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12582     Results.push_back(V);
12583     return;
12584   }
12585   case ISD::READCYCLECOUNTER: {
12586     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12587     SDValue TheChain = N->getOperand(0);
12588     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12589     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12590                                      rd.getValue(1));
12591     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12592                                      eax.getValue(2));
12593     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12594     SDValue Ops[] = { eax, edx };
12595     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12596                                   array_lengthof(Ops)));
12597     Results.push_back(edx.getValue(1));
12598     return;
12599   }
12600   case ISD::ATOMIC_CMP_SWAP: {
12601     EVT T = N->getValueType(0);
12602     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12603     bool Regs64bit = T == MVT::i128;
12604     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12605     SDValue cpInL, cpInH;
12606     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12607                         DAG.getConstant(0, HalfT));
12608     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12609                         DAG.getConstant(1, HalfT));
12610     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12611                              Regs64bit ? X86::RAX : X86::EAX,
12612                              cpInL, SDValue());
12613     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12614                              Regs64bit ? X86::RDX : X86::EDX,
12615                              cpInH, cpInL.getValue(1));
12616     SDValue swapInL, swapInH;
12617     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12618                           DAG.getConstant(0, HalfT));
12619     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12620                           DAG.getConstant(1, HalfT));
12621     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12622                                Regs64bit ? X86::RBX : X86::EBX,
12623                                swapInL, cpInH.getValue(1));
12624     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12625                                Regs64bit ? X86::RCX : X86::ECX,
12626                                swapInH, swapInL.getValue(1));
12627     SDValue Ops[] = { swapInH.getValue(0),
12628                       N->getOperand(1),
12629                       swapInH.getValue(1) };
12630     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12631     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12632     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12633                                   X86ISD::LCMPXCHG8_DAG;
12634     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12635                                              Ops, array_lengthof(Ops), T, MMO);
12636     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12637                                         Regs64bit ? X86::RAX : X86::EAX,
12638                                         HalfT, Result.getValue(1));
12639     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12640                                         Regs64bit ? X86::RDX : X86::EDX,
12641                                         HalfT, cpOutL.getValue(2));
12642     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12643     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12644     Results.push_back(cpOutH.getValue(1));
12645     return;
12646   }
12647   case ISD::ATOMIC_LOAD_ADD:
12648   case ISD::ATOMIC_LOAD_AND:
12649   case ISD::ATOMIC_LOAD_NAND:
12650   case ISD::ATOMIC_LOAD_OR:
12651   case ISD::ATOMIC_LOAD_SUB:
12652   case ISD::ATOMIC_LOAD_XOR:
12653   case ISD::ATOMIC_LOAD_MAX:
12654   case ISD::ATOMIC_LOAD_MIN:
12655   case ISD::ATOMIC_LOAD_UMAX:
12656   case ISD::ATOMIC_LOAD_UMIN:
12657   case ISD::ATOMIC_SWAP: {
12658     unsigned Opc;
12659     switch (N->getOpcode()) {
12660     default: llvm_unreachable("Unexpected opcode");
12661     case ISD::ATOMIC_LOAD_ADD:
12662       Opc = X86ISD::ATOMADD64_DAG;
12663       break;
12664     case ISD::ATOMIC_LOAD_AND:
12665       Opc = X86ISD::ATOMAND64_DAG;
12666       break;
12667     case ISD::ATOMIC_LOAD_NAND:
12668       Opc = X86ISD::ATOMNAND64_DAG;
12669       break;
12670     case ISD::ATOMIC_LOAD_OR:
12671       Opc = X86ISD::ATOMOR64_DAG;
12672       break;
12673     case ISD::ATOMIC_LOAD_SUB:
12674       Opc = X86ISD::ATOMSUB64_DAG;
12675       break;
12676     case ISD::ATOMIC_LOAD_XOR:
12677       Opc = X86ISD::ATOMXOR64_DAG;
12678       break;
12679     case ISD::ATOMIC_LOAD_MAX:
12680       Opc = X86ISD::ATOMMAX64_DAG;
12681       break;
12682     case ISD::ATOMIC_LOAD_MIN:
12683       Opc = X86ISD::ATOMMIN64_DAG;
12684       break;
12685     case ISD::ATOMIC_LOAD_UMAX:
12686       Opc = X86ISD::ATOMUMAX64_DAG;
12687       break;
12688     case ISD::ATOMIC_LOAD_UMIN:
12689       Opc = X86ISD::ATOMUMIN64_DAG;
12690       break;
12691     case ISD::ATOMIC_SWAP:
12692       Opc = X86ISD::ATOMSWAP64_DAG;
12693       break;
12694     }
12695     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12696     return;
12697   }
12698   case ISD::ATOMIC_LOAD:
12699     ReplaceATOMIC_LOAD(N, Results, DAG);
12700   }
12701 }
12702
12703 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12704   switch (Opcode) {
12705   default: return NULL;
12706   case X86ISD::BSF:                return "X86ISD::BSF";
12707   case X86ISD::BSR:                return "X86ISD::BSR";
12708   case X86ISD::SHLD:               return "X86ISD::SHLD";
12709   case X86ISD::SHRD:               return "X86ISD::SHRD";
12710   case X86ISD::FAND:               return "X86ISD::FAND";
12711   case X86ISD::FOR:                return "X86ISD::FOR";
12712   case X86ISD::FXOR:               return "X86ISD::FXOR";
12713   case X86ISD::FSRL:               return "X86ISD::FSRL";
12714   case X86ISD::FILD:               return "X86ISD::FILD";
12715   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12716   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12717   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12718   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12719   case X86ISD::FLD:                return "X86ISD::FLD";
12720   case X86ISD::FST:                return "X86ISD::FST";
12721   case X86ISD::CALL:               return "X86ISD::CALL";
12722   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12723   case X86ISD::BT:                 return "X86ISD::BT";
12724   case X86ISD::CMP:                return "X86ISD::CMP";
12725   case X86ISD::COMI:               return "X86ISD::COMI";
12726   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12727   case X86ISD::SETCC:              return "X86ISD::SETCC";
12728   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12729   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12730   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12731   case X86ISD::CMOV:               return "X86ISD::CMOV";
12732   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12733   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12734   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12735   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12736   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12737   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12738   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12739   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12740   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12741   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12742   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12743   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12744   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12745   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12746   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12747   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12748   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12749   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12750   case X86ISD::HADD:               return "X86ISD::HADD";
12751   case X86ISD::HSUB:               return "X86ISD::HSUB";
12752   case X86ISD::FHADD:              return "X86ISD::FHADD";
12753   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12754   case X86ISD::UMAX:               return "X86ISD::UMAX";
12755   case X86ISD::UMIN:               return "X86ISD::UMIN";
12756   case X86ISD::SMAX:               return "X86ISD::SMAX";
12757   case X86ISD::SMIN:               return "X86ISD::SMIN";
12758   case X86ISD::FMAX:               return "X86ISD::FMAX";
12759   case X86ISD::FMIN:               return "X86ISD::FMIN";
12760   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12761   case X86ISD::FMINC:              return "X86ISD::FMINC";
12762   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12763   case X86ISD::FRCP:               return "X86ISD::FRCP";
12764   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12765   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12766   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12767   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12768   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12769   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12770   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12771   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12772   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12773   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12774   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12775   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12776   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12777   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12778   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12779   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12780   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12781   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12782   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12783   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12784   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12785   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12786   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12787   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12788   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12789   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12790   case X86ISD::VSHL:               return "X86ISD::VSHL";
12791   case X86ISD::VSRL:               return "X86ISD::VSRL";
12792   case X86ISD::VSRA:               return "X86ISD::VSRA";
12793   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12794   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12795   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12796   case X86ISD::CMPP:               return "X86ISD::CMPP";
12797   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12798   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12799   case X86ISD::ADD:                return "X86ISD::ADD";
12800   case X86ISD::SUB:                return "X86ISD::SUB";
12801   case X86ISD::ADC:                return "X86ISD::ADC";
12802   case X86ISD::SBB:                return "X86ISD::SBB";
12803   case X86ISD::SMUL:               return "X86ISD::SMUL";
12804   case X86ISD::UMUL:               return "X86ISD::UMUL";
12805   case X86ISD::INC:                return "X86ISD::INC";
12806   case X86ISD::DEC:                return "X86ISD::DEC";
12807   case X86ISD::OR:                 return "X86ISD::OR";
12808   case X86ISD::XOR:                return "X86ISD::XOR";
12809   case X86ISD::AND:                return "X86ISD::AND";
12810   case X86ISD::BLSI:               return "X86ISD::BLSI";
12811   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12812   case X86ISD::BLSR:               return "X86ISD::BLSR";
12813   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12814   case X86ISD::PTEST:              return "X86ISD::PTEST";
12815   case X86ISD::TESTP:              return "X86ISD::TESTP";
12816   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12817   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12818   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12819   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12820   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12821   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12822   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12823   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12824   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12825   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12826   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12827   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12828   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12829   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12830   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12831   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12832   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12833   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12834   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12835   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12836   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12837   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12838   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12839   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12840   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12841   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12842   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12843   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12844   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12845   case X86ISD::SAHF:               return "X86ISD::SAHF";
12846   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12847   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
12848   case X86ISD::FMADD:              return "X86ISD::FMADD";
12849   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12850   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12851   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12852   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12853   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12854   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12855   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12856   case X86ISD::XTEST:              return "X86ISD::XTEST";
12857   }
12858 }
12859
12860 // isLegalAddressingMode - Return true if the addressing mode represented
12861 // by AM is legal for this target, for a load/store of the specified type.
12862 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12863                                               Type *Ty) const {
12864   // X86 supports extremely general addressing modes.
12865   CodeModel::Model M = getTargetMachine().getCodeModel();
12866   Reloc::Model R = getTargetMachine().getRelocationModel();
12867
12868   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12869   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12870     return false;
12871
12872   if (AM.BaseGV) {
12873     unsigned GVFlags =
12874       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12875
12876     // If a reference to this global requires an extra load, we can't fold it.
12877     if (isGlobalStubReference(GVFlags))
12878       return false;
12879
12880     // If BaseGV requires a register for the PIC base, we cannot also have a
12881     // BaseReg specified.
12882     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12883       return false;
12884
12885     // If lower 4G is not available, then we must use rip-relative addressing.
12886     if ((M != CodeModel::Small || R != Reloc::Static) &&
12887         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12888       return false;
12889   }
12890
12891   switch (AM.Scale) {
12892   case 0:
12893   case 1:
12894   case 2:
12895   case 4:
12896   case 8:
12897     // These scales always work.
12898     break;
12899   case 3:
12900   case 5:
12901   case 9:
12902     // These scales are formed with basereg+scalereg.  Only accept if there is
12903     // no basereg yet.
12904     if (AM.HasBaseReg)
12905       return false;
12906     break;
12907   default:  // Other stuff never works.
12908     return false;
12909   }
12910
12911   return true;
12912 }
12913
12914 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12915   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12916     return false;
12917   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12918   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12919   return NumBits1 > NumBits2;
12920 }
12921
12922 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12923   return isInt<32>(Imm);
12924 }
12925
12926 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12927   // Can also use sub to handle negated immediates.
12928   return isInt<32>(Imm);
12929 }
12930
12931 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12932   if (!VT1.isInteger() || !VT2.isInteger())
12933     return false;
12934   unsigned NumBits1 = VT1.getSizeInBits();
12935   unsigned NumBits2 = VT2.getSizeInBits();
12936   return NumBits1 > NumBits2;
12937 }
12938
12939 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12940   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12941   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12942 }
12943
12944 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12945   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12946   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12947 }
12948
12949 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12950   EVT VT1 = Val.getValueType();
12951   if (isZExtFree(VT1, VT2))
12952     return true;
12953
12954   if (Val.getOpcode() != ISD::LOAD)
12955     return false;
12956
12957   if (!VT1.isSimple() || !VT1.isInteger() ||
12958       !VT2.isSimple() || !VT2.isInteger())
12959     return false;
12960
12961   switch (VT1.getSimpleVT().SimpleTy) {
12962   default: break;
12963   case MVT::i8:
12964   case MVT::i16:
12965   case MVT::i32:
12966     // X86 has 8, 16, and 32-bit zero-extending loads.
12967     return true;
12968   }
12969
12970   return false;
12971 }
12972
12973 bool
12974 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12975   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
12976     return false;
12977
12978   VT = VT.getScalarType();
12979
12980   if (!VT.isSimple())
12981     return false;
12982
12983   switch (VT.getSimpleVT().SimpleTy) {
12984   case MVT::f32:
12985   case MVT::f64:
12986     return true;
12987   default:
12988     break;
12989   }
12990
12991   return false;
12992 }
12993
12994 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12995   // i16 instructions are longer (0x66 prefix) and potentially slower.
12996   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12997 }
12998
12999 /// isShuffleMaskLegal - Targets can use this to indicate that they only
13000 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
13001 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
13002 /// are assumed to be legal.
13003 bool
13004 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
13005                                       EVT VT) const {
13006   // Very little shuffling can be done for 64-bit vectors right now.
13007   if (VT.getSizeInBits() == 64)
13008     return false;
13009
13010   // FIXME: pshufb, blends, shifts.
13011   return (VT.getVectorNumElements() == 2 ||
13012           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
13013           isMOVLMask(M, VT) ||
13014           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
13015           isPSHUFDMask(M, VT) ||
13016           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
13017           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
13018           isPALIGNRMask(M, VT, Subtarget) ||
13019           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
13020           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
13021           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
13022           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13023 }
13024
13025 bool
13026 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13027                                           EVT VT) const {
13028   unsigned NumElts = VT.getVectorNumElements();
13029   // FIXME: This collection of masks seems suspect.
13030   if (NumElts == 2)
13031     return true;
13032   if (NumElts == 4 && VT.is128BitVector()) {
13033     return (isMOVLMask(Mask, VT)  ||
13034             isCommutedMOVLMask(Mask, VT, true) ||
13035             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13036             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13037   }
13038   return false;
13039 }
13040
13041 //===----------------------------------------------------------------------===//
13042 //                           X86 Scheduler Hooks
13043 //===----------------------------------------------------------------------===//
13044
13045 /// Utility function to emit xbegin specifying the start of an RTM region.
13046 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13047                                      const TargetInstrInfo *TII) {
13048   DebugLoc DL = MI->getDebugLoc();
13049
13050   const BasicBlock *BB = MBB->getBasicBlock();
13051   MachineFunction::iterator I = MBB;
13052   ++I;
13053
13054   // For the v = xbegin(), we generate
13055   //
13056   // thisMBB:
13057   //  xbegin sinkMBB
13058   //
13059   // mainMBB:
13060   //  eax = -1
13061   //
13062   // sinkMBB:
13063   //  v = eax
13064
13065   MachineBasicBlock *thisMBB = MBB;
13066   MachineFunction *MF = MBB->getParent();
13067   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13068   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13069   MF->insert(I, mainMBB);
13070   MF->insert(I, sinkMBB);
13071
13072   // Transfer the remainder of BB and its successor edges to sinkMBB.
13073   sinkMBB->splice(sinkMBB->begin(), MBB,
13074                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13075   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13076
13077   // thisMBB:
13078   //  xbegin sinkMBB
13079   //  # fallthrough to mainMBB
13080   //  # abortion to sinkMBB
13081   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13082   thisMBB->addSuccessor(mainMBB);
13083   thisMBB->addSuccessor(sinkMBB);
13084
13085   // mainMBB:
13086   //  EAX = -1
13087   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13088   mainMBB->addSuccessor(sinkMBB);
13089
13090   // sinkMBB:
13091   // EAX is live into the sinkMBB
13092   sinkMBB->addLiveIn(X86::EAX);
13093   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13094           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13095     .addReg(X86::EAX);
13096
13097   MI->eraseFromParent();
13098   return sinkMBB;
13099 }
13100
13101 // Get CMPXCHG opcode for the specified data type.
13102 static unsigned getCmpXChgOpcode(EVT VT) {
13103   switch (VT.getSimpleVT().SimpleTy) {
13104   case MVT::i8:  return X86::LCMPXCHG8;
13105   case MVT::i16: return X86::LCMPXCHG16;
13106   case MVT::i32: return X86::LCMPXCHG32;
13107   case MVT::i64: return X86::LCMPXCHG64;
13108   default:
13109     break;
13110   }
13111   llvm_unreachable("Invalid operand size!");
13112 }
13113
13114 // Get LOAD opcode for the specified data type.
13115 static unsigned getLoadOpcode(EVT VT) {
13116   switch (VT.getSimpleVT().SimpleTy) {
13117   case MVT::i8:  return X86::MOV8rm;
13118   case MVT::i16: return X86::MOV16rm;
13119   case MVT::i32: return X86::MOV32rm;
13120   case MVT::i64: return X86::MOV64rm;
13121   default:
13122     break;
13123   }
13124   llvm_unreachable("Invalid operand size!");
13125 }
13126
13127 // Get opcode of the non-atomic one from the specified atomic instruction.
13128 static unsigned getNonAtomicOpcode(unsigned Opc) {
13129   switch (Opc) {
13130   case X86::ATOMAND8:  return X86::AND8rr;
13131   case X86::ATOMAND16: return X86::AND16rr;
13132   case X86::ATOMAND32: return X86::AND32rr;
13133   case X86::ATOMAND64: return X86::AND64rr;
13134   case X86::ATOMOR8:   return X86::OR8rr;
13135   case X86::ATOMOR16:  return X86::OR16rr;
13136   case X86::ATOMOR32:  return X86::OR32rr;
13137   case X86::ATOMOR64:  return X86::OR64rr;
13138   case X86::ATOMXOR8:  return X86::XOR8rr;
13139   case X86::ATOMXOR16: return X86::XOR16rr;
13140   case X86::ATOMXOR32: return X86::XOR32rr;
13141   case X86::ATOMXOR64: return X86::XOR64rr;
13142   }
13143   llvm_unreachable("Unhandled atomic-load-op opcode!");
13144 }
13145
13146 // Get opcode of the non-atomic one from the specified atomic instruction with
13147 // extra opcode.
13148 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13149                                                unsigned &ExtraOpc) {
13150   switch (Opc) {
13151   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13152   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13153   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13154   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13155   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13156   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13157   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13158   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13159   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13160   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13161   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13162   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13163   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13164   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13165   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13166   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13167   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13168   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13169   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13170   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13171   }
13172   llvm_unreachable("Unhandled atomic-load-op opcode!");
13173 }
13174
13175 // Get opcode of the non-atomic one from the specified atomic instruction for
13176 // 64-bit data type on 32-bit target.
13177 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13178   switch (Opc) {
13179   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13180   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13181   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13182   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13183   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13184   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13185   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13186   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13187   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13188   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13189   }
13190   llvm_unreachable("Unhandled atomic-load-op opcode!");
13191 }
13192
13193 // Get opcode of the non-atomic one from the specified atomic instruction for
13194 // 64-bit data type on 32-bit target with extra opcode.
13195 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13196                                                    unsigned &HiOpc,
13197                                                    unsigned &ExtraOpc) {
13198   switch (Opc) {
13199   case X86::ATOMNAND6432:
13200     ExtraOpc = X86::NOT32r;
13201     HiOpc = X86::AND32rr;
13202     return X86::AND32rr;
13203   }
13204   llvm_unreachable("Unhandled atomic-load-op opcode!");
13205 }
13206
13207 // Get pseudo CMOV opcode from the specified data type.
13208 static unsigned getPseudoCMOVOpc(EVT VT) {
13209   switch (VT.getSimpleVT().SimpleTy) {
13210   case MVT::i8:  return X86::CMOV_GR8;
13211   case MVT::i16: return X86::CMOV_GR16;
13212   case MVT::i32: return X86::CMOV_GR32;
13213   default:
13214     break;
13215   }
13216   llvm_unreachable("Unknown CMOV opcode!");
13217 }
13218
13219 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13220 // They will be translated into a spin-loop or compare-exchange loop from
13221 //
13222 //    ...
13223 //    dst = atomic-fetch-op MI.addr, MI.val
13224 //    ...
13225 //
13226 // to
13227 //
13228 //    ...
13229 //    t1 = LOAD MI.addr
13230 // loop:
13231 //    t4 = phi(t1, t3 / loop)
13232 //    t2 = OP MI.val, t4
13233 //    EAX = t4
13234 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13235 //    t3 = EAX
13236 //    JNE loop
13237 // sink:
13238 //    dst = t3
13239 //    ...
13240 MachineBasicBlock *
13241 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13242                                        MachineBasicBlock *MBB) const {
13243   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13244   DebugLoc DL = MI->getDebugLoc();
13245
13246   MachineFunction *MF = MBB->getParent();
13247   MachineRegisterInfo &MRI = MF->getRegInfo();
13248
13249   const BasicBlock *BB = MBB->getBasicBlock();
13250   MachineFunction::iterator I = MBB;
13251   ++I;
13252
13253   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13254          "Unexpected number of operands");
13255
13256   assert(MI->hasOneMemOperand() &&
13257          "Expected atomic-load-op to have one memoperand");
13258
13259   // Memory Reference
13260   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13261   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13262
13263   unsigned DstReg, SrcReg;
13264   unsigned MemOpndSlot;
13265
13266   unsigned CurOp = 0;
13267
13268   DstReg = MI->getOperand(CurOp++).getReg();
13269   MemOpndSlot = CurOp;
13270   CurOp += X86::AddrNumOperands;
13271   SrcReg = MI->getOperand(CurOp++).getReg();
13272
13273   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13274   MVT::SimpleValueType VT = *RC->vt_begin();
13275   unsigned t1 = MRI.createVirtualRegister(RC);
13276   unsigned t2 = MRI.createVirtualRegister(RC);
13277   unsigned t3 = MRI.createVirtualRegister(RC);
13278   unsigned t4 = MRI.createVirtualRegister(RC);
13279   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13280
13281   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13282   unsigned LOADOpc = getLoadOpcode(VT);
13283
13284   // For the atomic load-arith operator, we generate
13285   //
13286   //  thisMBB:
13287   //    t1 = LOAD [MI.addr]
13288   //  mainMBB:
13289   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13290   //    t1 = OP MI.val, EAX
13291   //    EAX = t4
13292   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13293   //    t3 = EAX
13294   //    JNE mainMBB
13295   //  sinkMBB:
13296   //    dst = t3
13297
13298   MachineBasicBlock *thisMBB = MBB;
13299   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13300   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13301   MF->insert(I, mainMBB);
13302   MF->insert(I, sinkMBB);
13303
13304   MachineInstrBuilder MIB;
13305
13306   // Transfer the remainder of BB and its successor edges to sinkMBB.
13307   sinkMBB->splice(sinkMBB->begin(), MBB,
13308                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13309   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13310
13311   // thisMBB:
13312   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13313   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13314     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13315     if (NewMO.isReg())
13316       NewMO.setIsKill(false);
13317     MIB.addOperand(NewMO);
13318   }
13319   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13320     unsigned flags = (*MMOI)->getFlags();
13321     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13322     MachineMemOperand *MMO =
13323       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13324                                (*MMOI)->getSize(),
13325                                (*MMOI)->getBaseAlignment(),
13326                                (*MMOI)->getTBAAInfo(),
13327                                (*MMOI)->getRanges());
13328     MIB.addMemOperand(MMO);
13329   }
13330
13331   thisMBB->addSuccessor(mainMBB);
13332
13333   // mainMBB:
13334   MachineBasicBlock *origMainMBB = mainMBB;
13335
13336   // Add a PHI.
13337   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13338                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13339
13340   unsigned Opc = MI->getOpcode();
13341   switch (Opc) {
13342   default:
13343     llvm_unreachable("Unhandled atomic-load-op opcode!");
13344   case X86::ATOMAND8:
13345   case X86::ATOMAND16:
13346   case X86::ATOMAND32:
13347   case X86::ATOMAND64:
13348   case X86::ATOMOR8:
13349   case X86::ATOMOR16:
13350   case X86::ATOMOR32:
13351   case X86::ATOMOR64:
13352   case X86::ATOMXOR8:
13353   case X86::ATOMXOR16:
13354   case X86::ATOMXOR32:
13355   case X86::ATOMXOR64: {
13356     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13357     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13358       .addReg(t4);
13359     break;
13360   }
13361   case X86::ATOMNAND8:
13362   case X86::ATOMNAND16:
13363   case X86::ATOMNAND32:
13364   case X86::ATOMNAND64: {
13365     unsigned Tmp = MRI.createVirtualRegister(RC);
13366     unsigned NOTOpc;
13367     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13368     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13369       .addReg(t4);
13370     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13371     break;
13372   }
13373   case X86::ATOMMAX8:
13374   case X86::ATOMMAX16:
13375   case X86::ATOMMAX32:
13376   case X86::ATOMMAX64:
13377   case X86::ATOMMIN8:
13378   case X86::ATOMMIN16:
13379   case X86::ATOMMIN32:
13380   case X86::ATOMMIN64:
13381   case X86::ATOMUMAX8:
13382   case X86::ATOMUMAX16:
13383   case X86::ATOMUMAX32:
13384   case X86::ATOMUMAX64:
13385   case X86::ATOMUMIN8:
13386   case X86::ATOMUMIN16:
13387   case X86::ATOMUMIN32:
13388   case X86::ATOMUMIN64: {
13389     unsigned CMPOpc;
13390     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13391
13392     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13393       .addReg(SrcReg)
13394       .addReg(t4);
13395
13396     if (Subtarget->hasCMov()) {
13397       if (VT != MVT::i8) {
13398         // Native support
13399         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13400           .addReg(SrcReg)
13401           .addReg(t4);
13402       } else {
13403         // Promote i8 to i32 to use CMOV32
13404         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13405         const TargetRegisterClass *RC32 =
13406           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13407         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13408         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13409         unsigned Tmp = MRI.createVirtualRegister(RC32);
13410
13411         unsigned Undef = MRI.createVirtualRegister(RC32);
13412         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13413
13414         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13415           .addReg(Undef)
13416           .addReg(SrcReg)
13417           .addImm(X86::sub_8bit);
13418         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13419           .addReg(Undef)
13420           .addReg(t4)
13421           .addImm(X86::sub_8bit);
13422
13423         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13424           .addReg(SrcReg32)
13425           .addReg(AccReg32);
13426
13427         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13428           .addReg(Tmp, 0, X86::sub_8bit);
13429       }
13430     } else {
13431       // Use pseudo select and lower them.
13432       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13433              "Invalid atomic-load-op transformation!");
13434       unsigned SelOpc = getPseudoCMOVOpc(VT);
13435       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13436       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13437       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13438               .addReg(SrcReg).addReg(t4)
13439               .addImm(CC);
13440       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13441       // Replace the original PHI node as mainMBB is changed after CMOV
13442       // lowering.
13443       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13444         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13445       Phi->eraseFromParent();
13446     }
13447     break;
13448   }
13449   }
13450
13451   // Copy PhyReg back from virtual register.
13452   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13453     .addReg(t4);
13454
13455   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13456   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13457     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13458     if (NewMO.isReg())
13459       NewMO.setIsKill(false);
13460     MIB.addOperand(NewMO);
13461   }
13462   MIB.addReg(t2);
13463   MIB.setMemRefs(MMOBegin, MMOEnd);
13464
13465   // Copy PhyReg back to virtual register.
13466   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13467     .addReg(PhyReg);
13468
13469   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13470
13471   mainMBB->addSuccessor(origMainMBB);
13472   mainMBB->addSuccessor(sinkMBB);
13473
13474   // sinkMBB:
13475   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13476           TII->get(TargetOpcode::COPY), DstReg)
13477     .addReg(t3);
13478
13479   MI->eraseFromParent();
13480   return sinkMBB;
13481 }
13482
13483 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13484 // instructions. They will be translated into a spin-loop or compare-exchange
13485 // loop from
13486 //
13487 //    ...
13488 //    dst = atomic-fetch-op MI.addr, MI.val
13489 //    ...
13490 //
13491 // to
13492 //
13493 //    ...
13494 //    t1L = LOAD [MI.addr + 0]
13495 //    t1H = LOAD [MI.addr + 4]
13496 // loop:
13497 //    t4L = phi(t1L, t3L / loop)
13498 //    t4H = phi(t1H, t3H / loop)
13499 //    t2L = OP MI.val.lo, t4L
13500 //    t2H = OP MI.val.hi, t4H
13501 //    EAX = t4L
13502 //    EDX = t4H
13503 //    EBX = t2L
13504 //    ECX = t2H
13505 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13506 //    t3L = EAX
13507 //    t3H = EDX
13508 //    JNE loop
13509 // sink:
13510 //    dstL = t3L
13511 //    dstH = t3H
13512 //    ...
13513 MachineBasicBlock *
13514 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13515                                            MachineBasicBlock *MBB) const {
13516   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13517   DebugLoc DL = MI->getDebugLoc();
13518
13519   MachineFunction *MF = MBB->getParent();
13520   MachineRegisterInfo &MRI = MF->getRegInfo();
13521
13522   const BasicBlock *BB = MBB->getBasicBlock();
13523   MachineFunction::iterator I = MBB;
13524   ++I;
13525
13526   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13527          "Unexpected number of operands");
13528
13529   assert(MI->hasOneMemOperand() &&
13530          "Expected atomic-load-op32 to have one memoperand");
13531
13532   // Memory Reference
13533   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13534   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13535
13536   unsigned DstLoReg, DstHiReg;
13537   unsigned SrcLoReg, SrcHiReg;
13538   unsigned MemOpndSlot;
13539
13540   unsigned CurOp = 0;
13541
13542   DstLoReg = MI->getOperand(CurOp++).getReg();
13543   DstHiReg = MI->getOperand(CurOp++).getReg();
13544   MemOpndSlot = CurOp;
13545   CurOp += X86::AddrNumOperands;
13546   SrcLoReg = MI->getOperand(CurOp++).getReg();
13547   SrcHiReg = MI->getOperand(CurOp++).getReg();
13548
13549   const TargetRegisterClass *RC = &X86::GR32RegClass;
13550   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13551
13552   unsigned t1L = MRI.createVirtualRegister(RC);
13553   unsigned t1H = MRI.createVirtualRegister(RC);
13554   unsigned t2L = MRI.createVirtualRegister(RC);
13555   unsigned t2H = MRI.createVirtualRegister(RC);
13556   unsigned t3L = MRI.createVirtualRegister(RC);
13557   unsigned t3H = MRI.createVirtualRegister(RC);
13558   unsigned t4L = MRI.createVirtualRegister(RC);
13559   unsigned t4H = MRI.createVirtualRegister(RC);
13560
13561   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13562   unsigned LOADOpc = X86::MOV32rm;
13563
13564   // For the atomic load-arith operator, we generate
13565   //
13566   //  thisMBB:
13567   //    t1L = LOAD [MI.addr + 0]
13568   //    t1H = LOAD [MI.addr + 4]
13569   //  mainMBB:
13570   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13571   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13572   //    t2L = OP MI.val.lo, t4L
13573   //    t2H = OP MI.val.hi, t4H
13574   //    EBX = t2L
13575   //    ECX = t2H
13576   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13577   //    t3L = EAX
13578   //    t3H = EDX
13579   //    JNE loop
13580   //  sinkMBB:
13581   //    dstL = t3L
13582   //    dstH = t3H
13583
13584   MachineBasicBlock *thisMBB = MBB;
13585   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13586   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13587   MF->insert(I, mainMBB);
13588   MF->insert(I, sinkMBB);
13589
13590   MachineInstrBuilder MIB;
13591
13592   // Transfer the remainder of BB and its successor edges to sinkMBB.
13593   sinkMBB->splice(sinkMBB->begin(), MBB,
13594                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13595   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13596
13597   // thisMBB:
13598   // Lo
13599   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13600   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13601     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13602     if (NewMO.isReg())
13603       NewMO.setIsKill(false);
13604     MIB.addOperand(NewMO);
13605   }
13606   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13607     unsigned flags = (*MMOI)->getFlags();
13608     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13609     MachineMemOperand *MMO =
13610       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13611                                (*MMOI)->getSize(),
13612                                (*MMOI)->getBaseAlignment(),
13613                                (*MMOI)->getTBAAInfo(),
13614                                (*MMOI)->getRanges());
13615     MIB.addMemOperand(MMO);
13616   };
13617   MachineInstr *LowMI = MIB;
13618
13619   // Hi
13620   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13621   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13622     if (i == X86::AddrDisp) {
13623       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13624     } else {
13625       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13626       if (NewMO.isReg())
13627         NewMO.setIsKill(false);
13628       MIB.addOperand(NewMO);
13629     }
13630   }
13631   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13632
13633   thisMBB->addSuccessor(mainMBB);
13634
13635   // mainMBB:
13636   MachineBasicBlock *origMainMBB = mainMBB;
13637
13638   // Add PHIs.
13639   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13640                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13641   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13642                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13643
13644   unsigned Opc = MI->getOpcode();
13645   switch (Opc) {
13646   default:
13647     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13648   case X86::ATOMAND6432:
13649   case X86::ATOMOR6432:
13650   case X86::ATOMXOR6432:
13651   case X86::ATOMADD6432:
13652   case X86::ATOMSUB6432: {
13653     unsigned HiOpc;
13654     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13655     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13656       .addReg(SrcLoReg);
13657     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13658       .addReg(SrcHiReg);
13659     break;
13660   }
13661   case X86::ATOMNAND6432: {
13662     unsigned HiOpc, NOTOpc;
13663     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13664     unsigned TmpL = MRI.createVirtualRegister(RC);
13665     unsigned TmpH = MRI.createVirtualRegister(RC);
13666     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13667       .addReg(t4L);
13668     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13669       .addReg(t4H);
13670     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13671     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13672     break;
13673   }
13674   case X86::ATOMMAX6432:
13675   case X86::ATOMMIN6432:
13676   case X86::ATOMUMAX6432:
13677   case X86::ATOMUMIN6432: {
13678     unsigned HiOpc;
13679     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13680     unsigned cL = MRI.createVirtualRegister(RC8);
13681     unsigned cH = MRI.createVirtualRegister(RC8);
13682     unsigned cL32 = MRI.createVirtualRegister(RC);
13683     unsigned cH32 = MRI.createVirtualRegister(RC);
13684     unsigned cc = MRI.createVirtualRegister(RC);
13685     // cl := cmp src_lo, lo
13686     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13687       .addReg(SrcLoReg).addReg(t4L);
13688     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13689     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13690     // ch := cmp src_hi, hi
13691     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13692       .addReg(SrcHiReg).addReg(t4H);
13693     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13694     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13695     // cc := if (src_hi == hi) ? cl : ch;
13696     if (Subtarget->hasCMov()) {
13697       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13698         .addReg(cH32).addReg(cL32);
13699     } else {
13700       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13701               .addReg(cH32).addReg(cL32)
13702               .addImm(X86::COND_E);
13703       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13704     }
13705     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13706     if (Subtarget->hasCMov()) {
13707       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13708         .addReg(SrcLoReg).addReg(t4L);
13709       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13710         .addReg(SrcHiReg).addReg(t4H);
13711     } else {
13712       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13713               .addReg(SrcLoReg).addReg(t4L)
13714               .addImm(X86::COND_NE);
13715       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13716       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13717       // 2nd CMOV lowering.
13718       mainMBB->addLiveIn(X86::EFLAGS);
13719       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13720               .addReg(SrcHiReg).addReg(t4H)
13721               .addImm(X86::COND_NE);
13722       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13723       // Replace the original PHI node as mainMBB is changed after CMOV
13724       // lowering.
13725       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13726         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13727       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13728         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13729       PhiL->eraseFromParent();
13730       PhiH->eraseFromParent();
13731     }
13732     break;
13733   }
13734   case X86::ATOMSWAP6432: {
13735     unsigned HiOpc;
13736     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13737     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13738     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13739     break;
13740   }
13741   }
13742
13743   // Copy EDX:EAX back from HiReg:LoReg
13744   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13745   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13746   // Copy ECX:EBX from t1H:t1L
13747   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13748   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13749
13750   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13751   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13752     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13753     if (NewMO.isReg())
13754       NewMO.setIsKill(false);
13755     MIB.addOperand(NewMO);
13756   }
13757   MIB.setMemRefs(MMOBegin, MMOEnd);
13758
13759   // Copy EDX:EAX back to t3H:t3L
13760   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13761   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13762
13763   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13764
13765   mainMBB->addSuccessor(origMainMBB);
13766   mainMBB->addSuccessor(sinkMBB);
13767
13768   // sinkMBB:
13769   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13770           TII->get(TargetOpcode::COPY), DstLoReg)
13771     .addReg(t3L);
13772   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13773           TII->get(TargetOpcode::COPY), DstHiReg)
13774     .addReg(t3H);
13775
13776   MI->eraseFromParent();
13777   return sinkMBB;
13778 }
13779
13780 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13781 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13782 // in the .td file.
13783 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13784                                        const TargetInstrInfo *TII) {
13785   unsigned Opc;
13786   switch (MI->getOpcode()) {
13787   default: llvm_unreachable("illegal opcode!");
13788   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13789   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13790   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13791   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13792   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13793   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13794   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13795   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13796   }
13797
13798   DebugLoc dl = MI->getDebugLoc();
13799   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13800
13801   unsigned NumArgs = MI->getNumOperands();
13802   for (unsigned i = 1; i < NumArgs; ++i) {
13803     MachineOperand &Op = MI->getOperand(i);
13804     if (!(Op.isReg() && Op.isImplicit()))
13805       MIB.addOperand(Op);
13806   }
13807   if (MI->hasOneMemOperand())
13808     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13809
13810   BuildMI(*BB, MI, dl,
13811     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13812     .addReg(X86::XMM0);
13813
13814   MI->eraseFromParent();
13815   return BB;
13816 }
13817
13818 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13819 // defs in an instruction pattern
13820 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13821                                        const TargetInstrInfo *TII) {
13822   unsigned Opc;
13823   switch (MI->getOpcode()) {
13824   default: llvm_unreachable("illegal opcode!");
13825   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13826   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13827   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13828   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13829   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13830   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13831   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13832   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13833   }
13834
13835   DebugLoc dl = MI->getDebugLoc();
13836   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13837
13838   unsigned NumArgs = MI->getNumOperands(); // remove the results
13839   for (unsigned i = 1; i < NumArgs; ++i) {
13840     MachineOperand &Op = MI->getOperand(i);
13841     if (!(Op.isReg() && Op.isImplicit()))
13842       MIB.addOperand(Op);
13843   }
13844   if (MI->hasOneMemOperand())
13845     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13846
13847   BuildMI(*BB, MI, dl,
13848     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13849     .addReg(X86::ECX);
13850
13851   MI->eraseFromParent();
13852   return BB;
13853 }
13854
13855 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13856                                        const TargetInstrInfo *TII,
13857                                        const X86Subtarget* Subtarget) {
13858   DebugLoc dl = MI->getDebugLoc();
13859
13860   // Address into RAX/EAX, other two args into ECX, EDX.
13861   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13862   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13863   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13864   for (int i = 0; i < X86::AddrNumOperands; ++i)
13865     MIB.addOperand(MI->getOperand(i));
13866
13867   unsigned ValOps = X86::AddrNumOperands;
13868   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13869     .addReg(MI->getOperand(ValOps).getReg());
13870   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13871     .addReg(MI->getOperand(ValOps+1).getReg());
13872
13873   // The instruction doesn't actually take any operands though.
13874   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13875
13876   MI->eraseFromParent(); // The pseudo is gone now.
13877   return BB;
13878 }
13879
13880 MachineBasicBlock *
13881 X86TargetLowering::EmitVAARG64WithCustomInserter(
13882                    MachineInstr *MI,
13883                    MachineBasicBlock *MBB) const {
13884   // Emit va_arg instruction on X86-64.
13885
13886   // Operands to this pseudo-instruction:
13887   // 0  ) Output        : destination address (reg)
13888   // 1-5) Input         : va_list address (addr, i64mem)
13889   // 6  ) ArgSize       : Size (in bytes) of vararg type
13890   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13891   // 8  ) Align         : Alignment of type
13892   // 9  ) EFLAGS (implicit-def)
13893
13894   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13895   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13896
13897   unsigned DestReg = MI->getOperand(0).getReg();
13898   MachineOperand &Base = MI->getOperand(1);
13899   MachineOperand &Scale = MI->getOperand(2);
13900   MachineOperand &Index = MI->getOperand(3);
13901   MachineOperand &Disp = MI->getOperand(4);
13902   MachineOperand &Segment = MI->getOperand(5);
13903   unsigned ArgSize = MI->getOperand(6).getImm();
13904   unsigned ArgMode = MI->getOperand(7).getImm();
13905   unsigned Align = MI->getOperand(8).getImm();
13906
13907   // Memory Reference
13908   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13909   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13910   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13911
13912   // Machine Information
13913   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13914   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13915   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13916   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13917   DebugLoc DL = MI->getDebugLoc();
13918
13919   // struct va_list {
13920   //   i32   gp_offset
13921   //   i32   fp_offset
13922   //   i64   overflow_area (address)
13923   //   i64   reg_save_area (address)
13924   // }
13925   // sizeof(va_list) = 24
13926   // alignment(va_list) = 8
13927
13928   unsigned TotalNumIntRegs = 6;
13929   unsigned TotalNumXMMRegs = 8;
13930   bool UseGPOffset = (ArgMode == 1);
13931   bool UseFPOffset = (ArgMode == 2);
13932   unsigned MaxOffset = TotalNumIntRegs * 8 +
13933                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13934
13935   /* Align ArgSize to a multiple of 8 */
13936   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13937   bool NeedsAlign = (Align > 8);
13938
13939   MachineBasicBlock *thisMBB = MBB;
13940   MachineBasicBlock *overflowMBB;
13941   MachineBasicBlock *offsetMBB;
13942   MachineBasicBlock *endMBB;
13943
13944   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13945   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13946   unsigned OffsetReg = 0;
13947
13948   if (!UseGPOffset && !UseFPOffset) {
13949     // If we only pull from the overflow region, we don't create a branch.
13950     // We don't need to alter control flow.
13951     OffsetDestReg = 0; // unused
13952     OverflowDestReg = DestReg;
13953
13954     offsetMBB = NULL;
13955     overflowMBB = thisMBB;
13956     endMBB = thisMBB;
13957   } else {
13958     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13959     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13960     // If not, pull from overflow_area. (branch to overflowMBB)
13961     //
13962     //       thisMBB
13963     //         |     .
13964     //         |        .
13965     //     offsetMBB   overflowMBB
13966     //         |        .
13967     //         |     .
13968     //        endMBB
13969
13970     // Registers for the PHI in endMBB
13971     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13972     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13973
13974     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13975     MachineFunction *MF = MBB->getParent();
13976     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13977     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13978     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13979
13980     MachineFunction::iterator MBBIter = MBB;
13981     ++MBBIter;
13982
13983     // Insert the new basic blocks
13984     MF->insert(MBBIter, offsetMBB);
13985     MF->insert(MBBIter, overflowMBB);
13986     MF->insert(MBBIter, endMBB);
13987
13988     // Transfer the remainder of MBB and its successor edges to endMBB.
13989     endMBB->splice(endMBB->begin(), thisMBB,
13990                     llvm::next(MachineBasicBlock::iterator(MI)),
13991                     thisMBB->end());
13992     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13993
13994     // Make offsetMBB and overflowMBB successors of thisMBB
13995     thisMBB->addSuccessor(offsetMBB);
13996     thisMBB->addSuccessor(overflowMBB);
13997
13998     // endMBB is a successor of both offsetMBB and overflowMBB
13999     offsetMBB->addSuccessor(endMBB);
14000     overflowMBB->addSuccessor(endMBB);
14001
14002     // Load the offset value into a register
14003     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14004     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
14005       .addOperand(Base)
14006       .addOperand(Scale)
14007       .addOperand(Index)
14008       .addDisp(Disp, UseFPOffset ? 4 : 0)
14009       .addOperand(Segment)
14010       .setMemRefs(MMOBegin, MMOEnd);
14011
14012     // Check if there is enough room left to pull this argument.
14013     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
14014       .addReg(OffsetReg)
14015       .addImm(MaxOffset + 8 - ArgSizeA8);
14016
14017     // Branch to "overflowMBB" if offset >= max
14018     // Fall through to "offsetMBB" otherwise
14019     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14020       .addMBB(overflowMBB);
14021   }
14022
14023   // In offsetMBB, emit code to use the reg_save_area.
14024   if (offsetMBB) {
14025     assert(OffsetReg != 0);
14026
14027     // Read the reg_save_area address.
14028     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14029     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14030       .addOperand(Base)
14031       .addOperand(Scale)
14032       .addOperand(Index)
14033       .addDisp(Disp, 16)
14034       .addOperand(Segment)
14035       .setMemRefs(MMOBegin, MMOEnd);
14036
14037     // Zero-extend the offset
14038     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14039       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14040         .addImm(0)
14041         .addReg(OffsetReg)
14042         .addImm(X86::sub_32bit);
14043
14044     // Add the offset to the reg_save_area to get the final address.
14045     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14046       .addReg(OffsetReg64)
14047       .addReg(RegSaveReg);
14048
14049     // Compute the offset for the next argument
14050     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14051     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14052       .addReg(OffsetReg)
14053       .addImm(UseFPOffset ? 16 : 8);
14054
14055     // Store it back into the va_list.
14056     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14057       .addOperand(Base)
14058       .addOperand(Scale)
14059       .addOperand(Index)
14060       .addDisp(Disp, UseFPOffset ? 4 : 0)
14061       .addOperand(Segment)
14062       .addReg(NextOffsetReg)
14063       .setMemRefs(MMOBegin, MMOEnd);
14064
14065     // Jump to endMBB
14066     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14067       .addMBB(endMBB);
14068   }
14069
14070   //
14071   // Emit code to use overflow area
14072   //
14073
14074   // Load the overflow_area address into a register.
14075   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14076   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14077     .addOperand(Base)
14078     .addOperand(Scale)
14079     .addOperand(Index)
14080     .addDisp(Disp, 8)
14081     .addOperand(Segment)
14082     .setMemRefs(MMOBegin, MMOEnd);
14083
14084   // If we need to align it, do so. Otherwise, just copy the address
14085   // to OverflowDestReg.
14086   if (NeedsAlign) {
14087     // Align the overflow address
14088     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14089     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14090
14091     // aligned_addr = (addr + (align-1)) & ~(align-1)
14092     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14093       .addReg(OverflowAddrReg)
14094       .addImm(Align-1);
14095
14096     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14097       .addReg(TmpReg)
14098       .addImm(~(uint64_t)(Align-1));
14099   } else {
14100     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14101       .addReg(OverflowAddrReg);
14102   }
14103
14104   // Compute the next overflow address after this argument.
14105   // (the overflow address should be kept 8-byte aligned)
14106   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14107   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14108     .addReg(OverflowDestReg)
14109     .addImm(ArgSizeA8);
14110
14111   // Store the new overflow address.
14112   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14113     .addOperand(Base)
14114     .addOperand(Scale)
14115     .addOperand(Index)
14116     .addDisp(Disp, 8)
14117     .addOperand(Segment)
14118     .addReg(NextAddrReg)
14119     .setMemRefs(MMOBegin, MMOEnd);
14120
14121   // If we branched, emit the PHI to the front of endMBB.
14122   if (offsetMBB) {
14123     BuildMI(*endMBB, endMBB->begin(), DL,
14124             TII->get(X86::PHI), DestReg)
14125       .addReg(OffsetDestReg).addMBB(offsetMBB)
14126       .addReg(OverflowDestReg).addMBB(overflowMBB);
14127   }
14128
14129   // Erase the pseudo instruction
14130   MI->eraseFromParent();
14131
14132   return endMBB;
14133 }
14134
14135 MachineBasicBlock *
14136 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14137                                                  MachineInstr *MI,
14138                                                  MachineBasicBlock *MBB) const {
14139   // Emit code to save XMM registers to the stack. The ABI says that the
14140   // number of registers to save is given in %al, so it's theoretically
14141   // possible to do an indirect jump trick to avoid saving all of them,
14142   // however this code takes a simpler approach and just executes all
14143   // of the stores if %al is non-zero. It's less code, and it's probably
14144   // easier on the hardware branch predictor, and stores aren't all that
14145   // expensive anyway.
14146
14147   // Create the new basic blocks. One block contains all the XMM stores,
14148   // and one block is the final destination regardless of whether any
14149   // stores were performed.
14150   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14151   MachineFunction *F = MBB->getParent();
14152   MachineFunction::iterator MBBIter = MBB;
14153   ++MBBIter;
14154   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14155   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14156   F->insert(MBBIter, XMMSaveMBB);
14157   F->insert(MBBIter, EndMBB);
14158
14159   // Transfer the remainder of MBB and its successor edges to EndMBB.
14160   EndMBB->splice(EndMBB->begin(), MBB,
14161                  llvm::next(MachineBasicBlock::iterator(MI)),
14162                  MBB->end());
14163   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14164
14165   // The original block will now fall through to the XMM save block.
14166   MBB->addSuccessor(XMMSaveMBB);
14167   // The XMMSaveMBB will fall through to the end block.
14168   XMMSaveMBB->addSuccessor(EndMBB);
14169
14170   // Now add the instructions.
14171   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14172   DebugLoc DL = MI->getDebugLoc();
14173
14174   unsigned CountReg = MI->getOperand(0).getReg();
14175   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14176   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14177
14178   if (!Subtarget->isTargetWin64()) {
14179     // If %al is 0, branch around the XMM save block.
14180     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14181     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14182     MBB->addSuccessor(EndMBB);
14183   }
14184
14185   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14186   // In the XMM save block, save all the XMM argument registers.
14187   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14188     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14189     MachineMemOperand *MMO =
14190       F->getMachineMemOperand(
14191           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14192         MachineMemOperand::MOStore,
14193         /*Size=*/16, /*Align=*/16);
14194     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14195       .addFrameIndex(RegSaveFrameIndex)
14196       .addImm(/*Scale=*/1)
14197       .addReg(/*IndexReg=*/0)
14198       .addImm(/*Disp=*/Offset)
14199       .addReg(/*Segment=*/0)
14200       .addReg(MI->getOperand(i).getReg())
14201       .addMemOperand(MMO);
14202   }
14203
14204   MI->eraseFromParent();   // The pseudo instruction is gone now.
14205
14206   return EndMBB;
14207 }
14208
14209 // The EFLAGS operand of SelectItr might be missing a kill marker
14210 // because there were multiple uses of EFLAGS, and ISel didn't know
14211 // which to mark. Figure out whether SelectItr should have had a
14212 // kill marker, and set it if it should. Returns the correct kill
14213 // marker value.
14214 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14215                                      MachineBasicBlock* BB,
14216                                      const TargetRegisterInfo* TRI) {
14217   // Scan forward through BB for a use/def of EFLAGS.
14218   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14219   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14220     const MachineInstr& mi = *miI;
14221     if (mi.readsRegister(X86::EFLAGS))
14222       return false;
14223     if (mi.definesRegister(X86::EFLAGS))
14224       break; // Should have kill-flag - update below.
14225   }
14226
14227   // If we hit the end of the block, check whether EFLAGS is live into a
14228   // successor.
14229   if (miI == BB->end()) {
14230     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14231                                           sEnd = BB->succ_end();
14232          sItr != sEnd; ++sItr) {
14233       MachineBasicBlock* succ = *sItr;
14234       if (succ->isLiveIn(X86::EFLAGS))
14235         return false;
14236     }
14237   }
14238
14239   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14240   // out. SelectMI should have a kill flag on EFLAGS.
14241   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14242   return true;
14243 }
14244
14245 MachineBasicBlock *
14246 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14247                                      MachineBasicBlock *BB) const {
14248   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14249   DebugLoc DL = MI->getDebugLoc();
14250
14251   // To "insert" a SELECT_CC instruction, we actually have to insert the
14252   // diamond control-flow pattern.  The incoming instruction knows the
14253   // destination vreg to set, the condition code register to branch on, the
14254   // true/false values to select between, and a branch opcode to use.
14255   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14256   MachineFunction::iterator It = BB;
14257   ++It;
14258
14259   //  thisMBB:
14260   //  ...
14261   //   TrueVal = ...
14262   //   cmpTY ccX, r1, r2
14263   //   bCC copy1MBB
14264   //   fallthrough --> copy0MBB
14265   MachineBasicBlock *thisMBB = BB;
14266   MachineFunction *F = BB->getParent();
14267   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14268   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14269   F->insert(It, copy0MBB);
14270   F->insert(It, sinkMBB);
14271
14272   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14273   // live into the sink and copy blocks.
14274   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14275   if (!MI->killsRegister(X86::EFLAGS) &&
14276       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14277     copy0MBB->addLiveIn(X86::EFLAGS);
14278     sinkMBB->addLiveIn(X86::EFLAGS);
14279   }
14280
14281   // Transfer the remainder of BB and its successor edges to sinkMBB.
14282   sinkMBB->splice(sinkMBB->begin(), BB,
14283                   llvm::next(MachineBasicBlock::iterator(MI)),
14284                   BB->end());
14285   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14286
14287   // Add the true and fallthrough blocks as its successors.
14288   BB->addSuccessor(copy0MBB);
14289   BB->addSuccessor(sinkMBB);
14290
14291   // Create the conditional branch instruction.
14292   unsigned Opc =
14293     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14294   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14295
14296   //  copy0MBB:
14297   //   %FalseValue = ...
14298   //   # fallthrough to sinkMBB
14299   copy0MBB->addSuccessor(sinkMBB);
14300
14301   //  sinkMBB:
14302   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14303   //  ...
14304   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14305           TII->get(X86::PHI), MI->getOperand(0).getReg())
14306     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14307     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14308
14309   MI->eraseFromParent();   // The pseudo instruction is gone now.
14310   return sinkMBB;
14311 }
14312
14313 MachineBasicBlock *
14314 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14315                                         bool Is64Bit) const {
14316   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14317   DebugLoc DL = MI->getDebugLoc();
14318   MachineFunction *MF = BB->getParent();
14319   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14320
14321   assert(getTargetMachine().Options.EnableSegmentedStacks);
14322
14323   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14324   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14325
14326   // BB:
14327   //  ... [Till the alloca]
14328   // If stacklet is not large enough, jump to mallocMBB
14329   //
14330   // bumpMBB:
14331   //  Allocate by subtracting from RSP
14332   //  Jump to continueMBB
14333   //
14334   // mallocMBB:
14335   //  Allocate by call to runtime
14336   //
14337   // continueMBB:
14338   //  ...
14339   //  [rest of original BB]
14340   //
14341
14342   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14343   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14344   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14345
14346   MachineRegisterInfo &MRI = MF->getRegInfo();
14347   const TargetRegisterClass *AddrRegClass =
14348     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14349
14350   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14351     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14352     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14353     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14354     sizeVReg = MI->getOperand(1).getReg(),
14355     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14356
14357   MachineFunction::iterator MBBIter = BB;
14358   ++MBBIter;
14359
14360   MF->insert(MBBIter, bumpMBB);
14361   MF->insert(MBBIter, mallocMBB);
14362   MF->insert(MBBIter, continueMBB);
14363
14364   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14365                       (MachineBasicBlock::iterator(MI)), BB->end());
14366   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14367
14368   // Add code to the main basic block to check if the stack limit has been hit,
14369   // and if so, jump to mallocMBB otherwise to bumpMBB.
14370   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14371   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14372     .addReg(tmpSPVReg).addReg(sizeVReg);
14373   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14374     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14375     .addReg(SPLimitVReg);
14376   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14377
14378   // bumpMBB simply decreases the stack pointer, since we know the current
14379   // stacklet has enough space.
14380   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14381     .addReg(SPLimitVReg);
14382   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14383     .addReg(SPLimitVReg);
14384   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14385
14386   // Calls into a routine in libgcc to allocate more space from the heap.
14387   const uint32_t *RegMask =
14388     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14389   if (Is64Bit) {
14390     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14391       .addReg(sizeVReg);
14392     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14393       .addExternalSymbol("__morestack_allocate_stack_space")
14394       .addRegMask(RegMask)
14395       .addReg(X86::RDI, RegState::Implicit)
14396       .addReg(X86::RAX, RegState::ImplicitDefine);
14397   } else {
14398     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14399       .addImm(12);
14400     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14401     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14402       .addExternalSymbol("__morestack_allocate_stack_space")
14403       .addRegMask(RegMask)
14404       .addReg(X86::EAX, RegState::ImplicitDefine);
14405   }
14406
14407   if (!Is64Bit)
14408     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14409       .addImm(16);
14410
14411   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14412     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14413   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14414
14415   // Set up the CFG correctly.
14416   BB->addSuccessor(bumpMBB);
14417   BB->addSuccessor(mallocMBB);
14418   mallocMBB->addSuccessor(continueMBB);
14419   bumpMBB->addSuccessor(continueMBB);
14420
14421   // Take care of the PHI nodes.
14422   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14423           MI->getOperand(0).getReg())
14424     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14425     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14426
14427   // Delete the original pseudo instruction.
14428   MI->eraseFromParent();
14429
14430   // And we're done.
14431   return continueMBB;
14432 }
14433
14434 MachineBasicBlock *
14435 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14436                                           MachineBasicBlock *BB) const {
14437   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14438   DebugLoc DL = MI->getDebugLoc();
14439
14440   assert(!Subtarget->isTargetEnvMacho());
14441
14442   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14443   // non-trivial part is impdef of ESP.
14444
14445   if (Subtarget->isTargetWin64()) {
14446     if (Subtarget->isTargetCygMing()) {
14447       // ___chkstk(Mingw64):
14448       // Clobbers R10, R11, RAX and EFLAGS.
14449       // Updates RSP.
14450       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14451         .addExternalSymbol("___chkstk")
14452         .addReg(X86::RAX, RegState::Implicit)
14453         .addReg(X86::RSP, RegState::Implicit)
14454         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14455         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14456         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14457     } else {
14458       // __chkstk(MSVCRT): does not update stack pointer.
14459       // Clobbers R10, R11 and EFLAGS.
14460       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14461         .addExternalSymbol("__chkstk")
14462         .addReg(X86::RAX, RegState::Implicit)
14463         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14464       // RAX has the offset to be subtracted from RSP.
14465       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14466         .addReg(X86::RSP)
14467         .addReg(X86::RAX);
14468     }
14469   } else {
14470     const char *StackProbeSymbol =
14471       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14472
14473     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14474       .addExternalSymbol(StackProbeSymbol)
14475       .addReg(X86::EAX, RegState::Implicit)
14476       .addReg(X86::ESP, RegState::Implicit)
14477       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14478       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14479       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14480   }
14481
14482   MI->eraseFromParent();   // The pseudo instruction is gone now.
14483   return BB;
14484 }
14485
14486 MachineBasicBlock *
14487 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14488                                       MachineBasicBlock *BB) const {
14489   // This is pretty easy.  We're taking the value that we received from
14490   // our load from the relocation, sticking it in either RDI (x86-64)
14491   // or EAX and doing an indirect call.  The return value will then
14492   // be in the normal return register.
14493   const X86InstrInfo *TII
14494     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14495   DebugLoc DL = MI->getDebugLoc();
14496   MachineFunction *F = BB->getParent();
14497
14498   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14499   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14500
14501   // Get a register mask for the lowered call.
14502   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14503   // proper register mask.
14504   const uint32_t *RegMask =
14505     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14506   if (Subtarget->is64Bit()) {
14507     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14508                                       TII->get(X86::MOV64rm), X86::RDI)
14509     .addReg(X86::RIP)
14510     .addImm(0).addReg(0)
14511     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14512                       MI->getOperand(3).getTargetFlags())
14513     .addReg(0);
14514     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14515     addDirectMem(MIB, X86::RDI);
14516     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14517   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14518     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14519                                       TII->get(X86::MOV32rm), X86::EAX)
14520     .addReg(0)
14521     .addImm(0).addReg(0)
14522     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14523                       MI->getOperand(3).getTargetFlags())
14524     .addReg(0);
14525     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14526     addDirectMem(MIB, X86::EAX);
14527     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14528   } else {
14529     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14530                                       TII->get(X86::MOV32rm), X86::EAX)
14531     .addReg(TII->getGlobalBaseReg(F))
14532     .addImm(0).addReg(0)
14533     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14534                       MI->getOperand(3).getTargetFlags())
14535     .addReg(0);
14536     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14537     addDirectMem(MIB, X86::EAX);
14538     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14539   }
14540
14541   MI->eraseFromParent(); // The pseudo instruction is gone now.
14542   return BB;
14543 }
14544
14545 MachineBasicBlock *
14546 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14547                                     MachineBasicBlock *MBB) const {
14548   DebugLoc DL = MI->getDebugLoc();
14549   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14550
14551   MachineFunction *MF = MBB->getParent();
14552   MachineRegisterInfo &MRI = MF->getRegInfo();
14553
14554   const BasicBlock *BB = MBB->getBasicBlock();
14555   MachineFunction::iterator I = MBB;
14556   ++I;
14557
14558   // Memory Reference
14559   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14560   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14561
14562   unsigned DstReg;
14563   unsigned MemOpndSlot = 0;
14564
14565   unsigned CurOp = 0;
14566
14567   DstReg = MI->getOperand(CurOp++).getReg();
14568   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14569   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14570   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14571   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14572
14573   MemOpndSlot = CurOp;
14574
14575   MVT PVT = getPointerTy();
14576   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14577          "Invalid Pointer Size!");
14578
14579   // For v = setjmp(buf), we generate
14580   //
14581   // thisMBB:
14582   //  buf[LabelOffset] = restoreMBB
14583   //  SjLjSetup restoreMBB
14584   //
14585   // mainMBB:
14586   //  v_main = 0
14587   //
14588   // sinkMBB:
14589   //  v = phi(main, restore)
14590   //
14591   // restoreMBB:
14592   //  v_restore = 1
14593
14594   MachineBasicBlock *thisMBB = MBB;
14595   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14596   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14597   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14598   MF->insert(I, mainMBB);
14599   MF->insert(I, sinkMBB);
14600   MF->push_back(restoreMBB);
14601
14602   MachineInstrBuilder MIB;
14603
14604   // Transfer the remainder of BB and its successor edges to sinkMBB.
14605   sinkMBB->splice(sinkMBB->begin(), MBB,
14606                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14607   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14608
14609   // thisMBB:
14610   unsigned PtrStoreOpc = 0;
14611   unsigned LabelReg = 0;
14612   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14613   Reloc::Model RM = getTargetMachine().getRelocationModel();
14614   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14615                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14616
14617   // Prepare IP either in reg or imm.
14618   if (!UseImmLabel) {
14619     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14620     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14621     LabelReg = MRI.createVirtualRegister(PtrRC);
14622     if (Subtarget->is64Bit()) {
14623       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14624               .addReg(X86::RIP)
14625               .addImm(0)
14626               .addReg(0)
14627               .addMBB(restoreMBB)
14628               .addReg(0);
14629     } else {
14630       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14631       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14632               .addReg(XII->getGlobalBaseReg(MF))
14633               .addImm(0)
14634               .addReg(0)
14635               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14636               .addReg(0);
14637     }
14638   } else
14639     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14640   // Store IP
14641   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14642   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14643     if (i == X86::AddrDisp)
14644       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14645     else
14646       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14647   }
14648   if (!UseImmLabel)
14649     MIB.addReg(LabelReg);
14650   else
14651     MIB.addMBB(restoreMBB);
14652   MIB.setMemRefs(MMOBegin, MMOEnd);
14653   // Setup
14654   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14655           .addMBB(restoreMBB);
14656
14657   const X86RegisterInfo *RegInfo =
14658     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14659   MIB.addRegMask(RegInfo->getNoPreservedMask());
14660   thisMBB->addSuccessor(mainMBB);
14661   thisMBB->addSuccessor(restoreMBB);
14662
14663   // mainMBB:
14664   //  EAX = 0
14665   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14666   mainMBB->addSuccessor(sinkMBB);
14667
14668   // sinkMBB:
14669   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14670           TII->get(X86::PHI), DstReg)
14671     .addReg(mainDstReg).addMBB(mainMBB)
14672     .addReg(restoreDstReg).addMBB(restoreMBB);
14673
14674   // restoreMBB:
14675   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14676   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14677   restoreMBB->addSuccessor(sinkMBB);
14678
14679   MI->eraseFromParent();
14680   return sinkMBB;
14681 }
14682
14683 MachineBasicBlock *
14684 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14685                                      MachineBasicBlock *MBB) const {
14686   DebugLoc DL = MI->getDebugLoc();
14687   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14688
14689   MachineFunction *MF = MBB->getParent();
14690   MachineRegisterInfo &MRI = MF->getRegInfo();
14691
14692   // Memory Reference
14693   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14694   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14695
14696   MVT PVT = getPointerTy();
14697   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14698          "Invalid Pointer Size!");
14699
14700   const TargetRegisterClass *RC =
14701     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14702   unsigned Tmp = MRI.createVirtualRegister(RC);
14703   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14704   const X86RegisterInfo *RegInfo =
14705     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14706   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14707   unsigned SP = RegInfo->getStackRegister();
14708
14709   MachineInstrBuilder MIB;
14710
14711   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14712   const int64_t SPOffset = 2 * PVT.getStoreSize();
14713
14714   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14715   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14716
14717   // Reload FP
14718   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14719   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14720     MIB.addOperand(MI->getOperand(i));
14721   MIB.setMemRefs(MMOBegin, MMOEnd);
14722   // Reload IP
14723   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14724   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14725     if (i == X86::AddrDisp)
14726       MIB.addDisp(MI->getOperand(i), LabelOffset);
14727     else
14728       MIB.addOperand(MI->getOperand(i));
14729   }
14730   MIB.setMemRefs(MMOBegin, MMOEnd);
14731   // Reload SP
14732   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14733   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14734     if (i == X86::AddrDisp)
14735       MIB.addDisp(MI->getOperand(i), SPOffset);
14736     else
14737       MIB.addOperand(MI->getOperand(i));
14738   }
14739   MIB.setMemRefs(MMOBegin, MMOEnd);
14740   // Jump
14741   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14742
14743   MI->eraseFromParent();
14744   return MBB;
14745 }
14746
14747 MachineBasicBlock *
14748 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14749                                                MachineBasicBlock *BB) const {
14750   switch (MI->getOpcode()) {
14751   default: llvm_unreachable("Unexpected instr type to insert");
14752   case X86::TAILJMPd64:
14753   case X86::TAILJMPr64:
14754   case X86::TAILJMPm64:
14755     llvm_unreachable("TAILJMP64 would not be touched here.");
14756   case X86::TCRETURNdi64:
14757   case X86::TCRETURNri64:
14758   case X86::TCRETURNmi64:
14759     return BB;
14760   case X86::WIN_ALLOCA:
14761     return EmitLoweredWinAlloca(MI, BB);
14762   case X86::SEG_ALLOCA_32:
14763     return EmitLoweredSegAlloca(MI, BB, false);
14764   case X86::SEG_ALLOCA_64:
14765     return EmitLoweredSegAlloca(MI, BB, true);
14766   case X86::TLSCall_32:
14767   case X86::TLSCall_64:
14768     return EmitLoweredTLSCall(MI, BB);
14769   case X86::CMOV_GR8:
14770   case X86::CMOV_FR32:
14771   case X86::CMOV_FR64:
14772   case X86::CMOV_V4F32:
14773   case X86::CMOV_V2F64:
14774   case X86::CMOV_V2I64:
14775   case X86::CMOV_V8F32:
14776   case X86::CMOV_V4F64:
14777   case X86::CMOV_V4I64:
14778   case X86::CMOV_GR16:
14779   case X86::CMOV_GR32:
14780   case X86::CMOV_RFP32:
14781   case X86::CMOV_RFP64:
14782   case X86::CMOV_RFP80:
14783     return EmitLoweredSelect(MI, BB);
14784
14785   case X86::FP32_TO_INT16_IN_MEM:
14786   case X86::FP32_TO_INT32_IN_MEM:
14787   case X86::FP32_TO_INT64_IN_MEM:
14788   case X86::FP64_TO_INT16_IN_MEM:
14789   case X86::FP64_TO_INT32_IN_MEM:
14790   case X86::FP64_TO_INT64_IN_MEM:
14791   case X86::FP80_TO_INT16_IN_MEM:
14792   case X86::FP80_TO_INT32_IN_MEM:
14793   case X86::FP80_TO_INT64_IN_MEM: {
14794     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14795     DebugLoc DL = MI->getDebugLoc();
14796
14797     // Change the floating point control register to use "round towards zero"
14798     // mode when truncating to an integer value.
14799     MachineFunction *F = BB->getParent();
14800     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14801     addFrameReference(BuildMI(*BB, MI, DL,
14802                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14803
14804     // Load the old value of the high byte of the control word...
14805     unsigned OldCW =
14806       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14807     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14808                       CWFrameIdx);
14809
14810     // Set the high part to be round to zero...
14811     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14812       .addImm(0xC7F);
14813
14814     // Reload the modified control word now...
14815     addFrameReference(BuildMI(*BB, MI, DL,
14816                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14817
14818     // Restore the memory image of control word to original value
14819     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14820       .addReg(OldCW);
14821
14822     // Get the X86 opcode to use.
14823     unsigned Opc;
14824     switch (MI->getOpcode()) {
14825     default: llvm_unreachable("illegal opcode!");
14826     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14827     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14828     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14829     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14830     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14831     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14832     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14833     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14834     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14835     }
14836
14837     X86AddressMode AM;
14838     MachineOperand &Op = MI->getOperand(0);
14839     if (Op.isReg()) {
14840       AM.BaseType = X86AddressMode::RegBase;
14841       AM.Base.Reg = Op.getReg();
14842     } else {
14843       AM.BaseType = X86AddressMode::FrameIndexBase;
14844       AM.Base.FrameIndex = Op.getIndex();
14845     }
14846     Op = MI->getOperand(1);
14847     if (Op.isImm())
14848       AM.Scale = Op.getImm();
14849     Op = MI->getOperand(2);
14850     if (Op.isImm())
14851       AM.IndexReg = Op.getImm();
14852     Op = MI->getOperand(3);
14853     if (Op.isGlobal()) {
14854       AM.GV = Op.getGlobal();
14855     } else {
14856       AM.Disp = Op.getImm();
14857     }
14858     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14859                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14860
14861     // Reload the original control word now.
14862     addFrameReference(BuildMI(*BB, MI, DL,
14863                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14864
14865     MI->eraseFromParent();   // The pseudo instruction is gone now.
14866     return BB;
14867   }
14868     // String/text processing lowering.
14869   case X86::PCMPISTRM128REG:
14870   case X86::VPCMPISTRM128REG:
14871   case X86::PCMPISTRM128MEM:
14872   case X86::VPCMPISTRM128MEM:
14873   case X86::PCMPESTRM128REG:
14874   case X86::VPCMPESTRM128REG:
14875   case X86::PCMPESTRM128MEM:
14876   case X86::VPCMPESTRM128MEM:
14877     assert(Subtarget->hasSSE42() &&
14878            "Target must have SSE4.2 or AVX features enabled");
14879     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14880
14881   // String/text processing lowering.
14882   case X86::PCMPISTRIREG:
14883   case X86::VPCMPISTRIREG:
14884   case X86::PCMPISTRIMEM:
14885   case X86::VPCMPISTRIMEM:
14886   case X86::PCMPESTRIREG:
14887   case X86::VPCMPESTRIREG:
14888   case X86::PCMPESTRIMEM:
14889   case X86::VPCMPESTRIMEM:
14890     assert(Subtarget->hasSSE42() &&
14891            "Target must have SSE4.2 or AVX features enabled");
14892     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14893
14894   // Thread synchronization.
14895   case X86::MONITOR:
14896     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14897
14898   // xbegin
14899   case X86::XBEGIN:
14900     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14901
14902   // Atomic Lowering.
14903   case X86::ATOMAND8:
14904   case X86::ATOMAND16:
14905   case X86::ATOMAND32:
14906   case X86::ATOMAND64:
14907     // Fall through
14908   case X86::ATOMOR8:
14909   case X86::ATOMOR16:
14910   case X86::ATOMOR32:
14911   case X86::ATOMOR64:
14912     // Fall through
14913   case X86::ATOMXOR16:
14914   case X86::ATOMXOR8:
14915   case X86::ATOMXOR32:
14916   case X86::ATOMXOR64:
14917     // Fall through
14918   case X86::ATOMNAND8:
14919   case X86::ATOMNAND16:
14920   case X86::ATOMNAND32:
14921   case X86::ATOMNAND64:
14922     // Fall through
14923   case X86::ATOMMAX8:
14924   case X86::ATOMMAX16:
14925   case X86::ATOMMAX32:
14926   case X86::ATOMMAX64:
14927     // Fall through
14928   case X86::ATOMMIN8:
14929   case X86::ATOMMIN16:
14930   case X86::ATOMMIN32:
14931   case X86::ATOMMIN64:
14932     // Fall through
14933   case X86::ATOMUMAX8:
14934   case X86::ATOMUMAX16:
14935   case X86::ATOMUMAX32:
14936   case X86::ATOMUMAX64:
14937     // Fall through
14938   case X86::ATOMUMIN8:
14939   case X86::ATOMUMIN16:
14940   case X86::ATOMUMIN32:
14941   case X86::ATOMUMIN64:
14942     return EmitAtomicLoadArith(MI, BB);
14943
14944   // This group does 64-bit operations on a 32-bit host.
14945   case X86::ATOMAND6432:
14946   case X86::ATOMOR6432:
14947   case X86::ATOMXOR6432:
14948   case X86::ATOMNAND6432:
14949   case X86::ATOMADD6432:
14950   case X86::ATOMSUB6432:
14951   case X86::ATOMMAX6432:
14952   case X86::ATOMMIN6432:
14953   case X86::ATOMUMAX6432:
14954   case X86::ATOMUMIN6432:
14955   case X86::ATOMSWAP6432:
14956     return EmitAtomicLoadArith6432(MI, BB);
14957
14958   case X86::VASTART_SAVE_XMM_REGS:
14959     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14960
14961   case X86::VAARG_64:
14962     return EmitVAARG64WithCustomInserter(MI, BB);
14963
14964   case X86::EH_SjLj_SetJmp32:
14965   case X86::EH_SjLj_SetJmp64:
14966     return emitEHSjLjSetJmp(MI, BB);
14967
14968   case X86::EH_SjLj_LongJmp32:
14969   case X86::EH_SjLj_LongJmp64:
14970     return emitEHSjLjLongJmp(MI, BB);
14971   }
14972 }
14973
14974 //===----------------------------------------------------------------------===//
14975 //                           X86 Optimization Hooks
14976 //===----------------------------------------------------------------------===//
14977
14978 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14979                                                        APInt &KnownZero,
14980                                                        APInt &KnownOne,
14981                                                        const SelectionDAG &DAG,
14982                                                        unsigned Depth) const {
14983   unsigned BitWidth = KnownZero.getBitWidth();
14984   unsigned Opc = Op.getOpcode();
14985   assert((Opc >= ISD::BUILTIN_OP_END ||
14986           Opc == ISD::INTRINSIC_WO_CHAIN ||
14987           Opc == ISD::INTRINSIC_W_CHAIN ||
14988           Opc == ISD::INTRINSIC_VOID) &&
14989          "Should use MaskedValueIsZero if you don't know whether Op"
14990          " is a target node!");
14991
14992   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14993   switch (Opc) {
14994   default: break;
14995   case X86ISD::ADD:
14996   case X86ISD::SUB:
14997   case X86ISD::ADC:
14998   case X86ISD::SBB:
14999   case X86ISD::SMUL:
15000   case X86ISD::UMUL:
15001   case X86ISD::INC:
15002   case X86ISD::DEC:
15003   case X86ISD::OR:
15004   case X86ISD::XOR:
15005   case X86ISD::AND:
15006     // These nodes' second result is a boolean.
15007     if (Op.getResNo() == 0)
15008       break;
15009     // Fallthrough
15010   case X86ISD::SETCC:
15011     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15012     break;
15013   case ISD::INTRINSIC_WO_CHAIN: {
15014     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15015     unsigned NumLoBits = 0;
15016     switch (IntId) {
15017     default: break;
15018     case Intrinsic::x86_sse_movmsk_ps:
15019     case Intrinsic::x86_avx_movmsk_ps_256:
15020     case Intrinsic::x86_sse2_movmsk_pd:
15021     case Intrinsic::x86_avx_movmsk_pd_256:
15022     case Intrinsic::x86_mmx_pmovmskb:
15023     case Intrinsic::x86_sse2_pmovmskb_128:
15024     case Intrinsic::x86_avx2_pmovmskb: {
15025       // High bits of movmskp{s|d}, pmovmskb are known zero.
15026       switch (IntId) {
15027         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15028         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
15029         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
15030         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
15031         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
15032         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
15033         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
15034         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
15035       }
15036       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15037       break;
15038     }
15039     }
15040     break;
15041   }
15042   }
15043 }
15044
15045 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15046                                                          unsigned Depth) const {
15047   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15048   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15049     return Op.getValueType().getScalarType().getSizeInBits();
15050
15051   // Fallback case.
15052   return 1;
15053 }
15054
15055 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15056 /// node is a GlobalAddress + offset.
15057 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15058                                        const GlobalValue* &GA,
15059                                        int64_t &Offset) const {
15060   if (N->getOpcode() == X86ISD::Wrapper) {
15061     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15062       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15063       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15064       return true;
15065     }
15066   }
15067   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15068 }
15069
15070 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15071 /// same as extracting the high 128-bit part of 256-bit vector and then
15072 /// inserting the result into the low part of a new 256-bit vector
15073 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15074   EVT VT = SVOp->getValueType(0);
15075   unsigned NumElems = VT.getVectorNumElements();
15076
15077   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15078   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15079     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15080         SVOp->getMaskElt(j) >= 0)
15081       return false;
15082
15083   return true;
15084 }
15085
15086 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15087 /// same as extracting the low 128-bit part of 256-bit vector and then
15088 /// inserting the result into the high part of a new 256-bit vector
15089 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15090   EVT VT = SVOp->getValueType(0);
15091   unsigned NumElems = VT.getVectorNumElements();
15092
15093   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15094   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15095     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15096         SVOp->getMaskElt(j) >= 0)
15097       return false;
15098
15099   return true;
15100 }
15101
15102 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15103 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15104                                         TargetLowering::DAGCombinerInfo &DCI,
15105                                         const X86Subtarget* Subtarget) {
15106   SDLoc dl(N);
15107   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15108   SDValue V1 = SVOp->getOperand(0);
15109   SDValue V2 = SVOp->getOperand(1);
15110   EVT VT = SVOp->getValueType(0);
15111   unsigned NumElems = VT.getVectorNumElements();
15112
15113   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15114       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15115     //
15116     //                   0,0,0,...
15117     //                      |
15118     //    V      UNDEF    BUILD_VECTOR    UNDEF
15119     //     \      /           \           /
15120     //  CONCAT_VECTOR         CONCAT_VECTOR
15121     //         \                  /
15122     //          \                /
15123     //          RESULT: V + zero extended
15124     //
15125     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15126         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15127         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15128       return SDValue();
15129
15130     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15131       return SDValue();
15132
15133     // To match the shuffle mask, the first half of the mask should
15134     // be exactly the first vector, and all the rest a splat with the
15135     // first element of the second one.
15136     for (unsigned i = 0; i != NumElems/2; ++i)
15137       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15138           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15139         return SDValue();
15140
15141     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15142     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15143       if (Ld->hasNUsesOfValue(1, 0)) {
15144         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15145         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15146         SDValue ResNode =
15147           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15148                                   array_lengthof(Ops),
15149                                   Ld->getMemoryVT(),
15150                                   Ld->getPointerInfo(),
15151                                   Ld->getAlignment(),
15152                                   false/*isVolatile*/, true/*ReadMem*/,
15153                                   false/*WriteMem*/);
15154
15155         // Make sure the newly-created LOAD is in the same position as Ld in
15156         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15157         // and update uses of Ld's output chain to use the TokenFactor.
15158         if (Ld->hasAnyUseOfValue(1)) {
15159           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15160                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15161           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15162           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15163                                  SDValue(ResNode.getNode(), 1));
15164         }
15165
15166         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15167       }
15168     }
15169
15170     // Emit a zeroed vector and insert the desired subvector on its
15171     // first half.
15172     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15173     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15174     return DCI.CombineTo(N, InsV);
15175   }
15176
15177   //===--------------------------------------------------------------------===//
15178   // Combine some shuffles into subvector extracts and inserts:
15179   //
15180
15181   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15182   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15183     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15184     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15185     return DCI.CombineTo(N, InsV);
15186   }
15187
15188   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15189   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15190     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15191     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15192     return DCI.CombineTo(N, InsV);
15193   }
15194
15195   return SDValue();
15196 }
15197
15198 /// PerformShuffleCombine - Performs several different shuffle combines.
15199 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15200                                      TargetLowering::DAGCombinerInfo &DCI,
15201                                      const X86Subtarget *Subtarget) {
15202   SDLoc dl(N);
15203   EVT VT = N->getValueType(0);
15204
15205   // Don't create instructions with illegal types after legalize types has run.
15206   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15207   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15208     return SDValue();
15209
15210   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15211   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15212       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15213     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15214
15215   // Only handle 128 wide vector from here on.
15216   if (!VT.is128BitVector())
15217     return SDValue();
15218
15219   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15220   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15221   // consecutive, non-overlapping, and in the right order.
15222   SmallVector<SDValue, 16> Elts;
15223   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15224     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15225
15226   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15227 }
15228
15229 /// PerformTruncateCombine - Converts truncate operation to
15230 /// a sequence of vector shuffle operations.
15231 /// It is possible when we truncate 256-bit vector to 128-bit vector
15232 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15233                                       TargetLowering::DAGCombinerInfo &DCI,
15234                                       const X86Subtarget *Subtarget)  {
15235   return SDValue();
15236 }
15237
15238 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15239 /// specific shuffle of a load can be folded into a single element load.
15240 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15241 /// shuffles have been customed lowered so we need to handle those here.
15242 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15243                                          TargetLowering::DAGCombinerInfo &DCI) {
15244   if (DCI.isBeforeLegalizeOps())
15245     return SDValue();
15246
15247   SDValue InVec = N->getOperand(0);
15248   SDValue EltNo = N->getOperand(1);
15249
15250   if (!isa<ConstantSDNode>(EltNo))
15251     return SDValue();
15252
15253   EVT VT = InVec.getValueType();
15254
15255   bool HasShuffleIntoBitcast = false;
15256   if (InVec.getOpcode() == ISD::BITCAST) {
15257     // Don't duplicate a load with other uses.
15258     if (!InVec.hasOneUse())
15259       return SDValue();
15260     EVT BCVT = InVec.getOperand(0).getValueType();
15261     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15262       return SDValue();
15263     InVec = InVec.getOperand(0);
15264     HasShuffleIntoBitcast = true;
15265   }
15266
15267   if (!isTargetShuffle(InVec.getOpcode()))
15268     return SDValue();
15269
15270   // Don't duplicate a load with other uses.
15271   if (!InVec.hasOneUse())
15272     return SDValue();
15273
15274   SmallVector<int, 16> ShuffleMask;
15275   bool UnaryShuffle;
15276   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15277                             UnaryShuffle))
15278     return SDValue();
15279
15280   // Select the input vector, guarding against out of range extract vector.
15281   unsigned NumElems = VT.getVectorNumElements();
15282   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15283   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15284   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15285                                          : InVec.getOperand(1);
15286
15287   // If inputs to shuffle are the same for both ops, then allow 2 uses
15288   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15289
15290   if (LdNode.getOpcode() == ISD::BITCAST) {
15291     // Don't duplicate a load with other uses.
15292     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15293       return SDValue();
15294
15295     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15296     LdNode = LdNode.getOperand(0);
15297   }
15298
15299   if (!ISD::isNormalLoad(LdNode.getNode()))
15300     return SDValue();
15301
15302   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15303
15304   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15305     return SDValue();
15306
15307   if (HasShuffleIntoBitcast) {
15308     // If there's a bitcast before the shuffle, check if the load type and
15309     // alignment is valid.
15310     unsigned Align = LN0->getAlignment();
15311     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15312     unsigned NewAlign = TLI.getDataLayout()->
15313       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15314
15315     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15316       return SDValue();
15317   }
15318
15319   // All checks match so transform back to vector_shuffle so that DAG combiner
15320   // can finish the job
15321   SDLoc dl(N);
15322
15323   // Create shuffle node taking into account the case that its a unary shuffle
15324   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15325   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15326                                  InVec.getOperand(0), Shuffle,
15327                                  &ShuffleMask[0]);
15328   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15329   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15330                      EltNo);
15331 }
15332
15333 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15334 /// generation and convert it from being a bunch of shuffles and extracts
15335 /// to a simple store and scalar loads to extract the elements.
15336 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15337                                          TargetLowering::DAGCombinerInfo &DCI) {
15338   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15339   if (NewOp.getNode())
15340     return NewOp;
15341
15342   SDValue InputVector = N->getOperand(0);
15343   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15344   // from mmx to v2i32 has a single usage.
15345   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15346       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15347       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15348     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15349                        N->getValueType(0),
15350                        InputVector.getNode()->getOperand(0));
15351
15352   // Only operate on vectors of 4 elements, where the alternative shuffling
15353   // gets to be more expensive.
15354   if (InputVector.getValueType() != MVT::v4i32)
15355     return SDValue();
15356
15357   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15358   // single use which is a sign-extend or zero-extend, and all elements are
15359   // used.
15360   SmallVector<SDNode *, 4> Uses;
15361   unsigned ExtractedElements = 0;
15362   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15363        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15364     if (UI.getUse().getResNo() != InputVector.getResNo())
15365       return SDValue();
15366
15367     SDNode *Extract = *UI;
15368     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15369       return SDValue();
15370
15371     if (Extract->getValueType(0) != MVT::i32)
15372       return SDValue();
15373     if (!Extract->hasOneUse())
15374       return SDValue();
15375     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15376         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15377       return SDValue();
15378     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15379       return SDValue();
15380
15381     // Record which element was extracted.
15382     ExtractedElements |=
15383       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15384
15385     Uses.push_back(Extract);
15386   }
15387
15388   // If not all the elements were used, this may not be worthwhile.
15389   if (ExtractedElements != 15)
15390     return SDValue();
15391
15392   // Ok, we've now decided to do the transformation.
15393   SDLoc dl(InputVector);
15394
15395   // Store the value to a temporary stack slot.
15396   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15397   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15398                             MachinePointerInfo(), false, false, 0);
15399
15400   // Replace each use (extract) with a load of the appropriate element.
15401   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15402        UE = Uses.end(); UI != UE; ++UI) {
15403     SDNode *Extract = *UI;
15404
15405     // cOMpute the element's address.
15406     SDValue Idx = Extract->getOperand(1);
15407     unsigned EltSize =
15408         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15409     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15410     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15411     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15412
15413     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15414                                      StackPtr, OffsetVal);
15415
15416     // Load the scalar.
15417     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15418                                      ScalarAddr, MachinePointerInfo(),
15419                                      false, false, false, 0);
15420
15421     // Replace the exact with the load.
15422     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15423   }
15424
15425   // The replacement was made in place; don't return anything.
15426   return SDValue();
15427 }
15428
15429 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15430 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15431                                    SDValue RHS, SelectionDAG &DAG,
15432                                    const X86Subtarget *Subtarget) {
15433   if (!VT.isVector())
15434     return 0;
15435
15436   switch (VT.getSimpleVT().SimpleTy) {
15437   default: return 0;
15438   case MVT::v32i8:
15439   case MVT::v16i16:
15440   case MVT::v8i32:
15441     if (!Subtarget->hasAVX2())
15442       return 0;
15443   case MVT::v16i8:
15444   case MVT::v8i16:
15445   case MVT::v4i32:
15446     if (!Subtarget->hasSSE2())
15447       return 0;
15448   }
15449
15450   // SSE2 has only a small subset of the operations.
15451   bool hasUnsigned = Subtarget->hasSSE41() ||
15452                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15453   bool hasSigned = Subtarget->hasSSE41() ||
15454                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15455
15456   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15457
15458   // Check for x CC y ? x : y.
15459   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15460       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15461     switch (CC) {
15462     default: break;
15463     case ISD::SETULT:
15464     case ISD::SETULE:
15465       return hasUnsigned ? X86ISD::UMIN : 0;
15466     case ISD::SETUGT:
15467     case ISD::SETUGE:
15468       return hasUnsigned ? X86ISD::UMAX : 0;
15469     case ISD::SETLT:
15470     case ISD::SETLE:
15471       return hasSigned ? X86ISD::SMIN : 0;
15472     case ISD::SETGT:
15473     case ISD::SETGE:
15474       return hasSigned ? X86ISD::SMAX : 0;
15475     }
15476   // Check for x CC y ? y : x -- a min/max with reversed arms.
15477   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15478              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15479     switch (CC) {
15480     default: break;
15481     case ISD::SETULT:
15482     case ISD::SETULE:
15483       return hasUnsigned ? X86ISD::UMAX : 0;
15484     case ISD::SETUGT:
15485     case ISD::SETUGE:
15486       return hasUnsigned ? X86ISD::UMIN : 0;
15487     case ISD::SETLT:
15488     case ISD::SETLE:
15489       return hasSigned ? X86ISD::SMAX : 0;
15490     case ISD::SETGT:
15491     case ISD::SETGE:
15492       return hasSigned ? X86ISD::SMIN : 0;
15493     }
15494   }
15495
15496   return 0;
15497 }
15498
15499 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15500 /// nodes.
15501 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15502                                     TargetLowering::DAGCombinerInfo &DCI,
15503                                     const X86Subtarget *Subtarget) {
15504   SDLoc DL(N);
15505   SDValue Cond = N->getOperand(0);
15506   // Get the LHS/RHS of the select.
15507   SDValue LHS = N->getOperand(1);
15508   SDValue RHS = N->getOperand(2);
15509   EVT VT = LHS.getValueType();
15510
15511   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15512   // instructions match the semantics of the common C idiom x<y?x:y but not
15513   // x<=y?x:y, because of how they handle negative zero (which can be
15514   // ignored in unsafe-math mode).
15515   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15516       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15517       (Subtarget->hasSSE2() ||
15518        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15519     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15520
15521     unsigned Opcode = 0;
15522     // Check for x CC y ? x : y.
15523     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15524         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15525       switch (CC) {
15526       default: break;
15527       case ISD::SETULT:
15528         // Converting this to a min would handle NaNs incorrectly, and swapping
15529         // the operands would cause it to handle comparisons between positive
15530         // and negative zero incorrectly.
15531         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15532           if (!DAG.getTarget().Options.UnsafeFPMath &&
15533               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15534             break;
15535           std::swap(LHS, RHS);
15536         }
15537         Opcode = X86ISD::FMIN;
15538         break;
15539       case ISD::SETOLE:
15540         // Converting this to a min would handle comparisons between positive
15541         // and negative zero incorrectly.
15542         if (!DAG.getTarget().Options.UnsafeFPMath &&
15543             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15544           break;
15545         Opcode = X86ISD::FMIN;
15546         break;
15547       case ISD::SETULE:
15548         // Converting this to a min would handle both negative zeros and NaNs
15549         // incorrectly, but we can swap the operands to fix both.
15550         std::swap(LHS, RHS);
15551       case ISD::SETOLT:
15552       case ISD::SETLT:
15553       case ISD::SETLE:
15554         Opcode = X86ISD::FMIN;
15555         break;
15556
15557       case ISD::SETOGE:
15558         // Converting this to a max would handle comparisons between positive
15559         // and negative zero incorrectly.
15560         if (!DAG.getTarget().Options.UnsafeFPMath &&
15561             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15562           break;
15563         Opcode = X86ISD::FMAX;
15564         break;
15565       case ISD::SETUGT:
15566         // Converting this to a max would handle NaNs incorrectly, and swapping
15567         // the operands would cause it to handle comparisons between positive
15568         // and negative zero incorrectly.
15569         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15570           if (!DAG.getTarget().Options.UnsafeFPMath &&
15571               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15572             break;
15573           std::swap(LHS, RHS);
15574         }
15575         Opcode = X86ISD::FMAX;
15576         break;
15577       case ISD::SETUGE:
15578         // Converting this to a max would handle both negative zeros and NaNs
15579         // incorrectly, but we can swap the operands to fix both.
15580         std::swap(LHS, RHS);
15581       case ISD::SETOGT:
15582       case ISD::SETGT:
15583       case ISD::SETGE:
15584         Opcode = X86ISD::FMAX;
15585         break;
15586       }
15587     // Check for x CC y ? y : x -- a min/max with reversed arms.
15588     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15589                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15590       switch (CC) {
15591       default: break;
15592       case ISD::SETOGE:
15593         // Converting this to a min would handle comparisons between positive
15594         // and negative zero incorrectly, and swapping the operands would
15595         // cause it to handle NaNs incorrectly.
15596         if (!DAG.getTarget().Options.UnsafeFPMath &&
15597             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15598           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15599             break;
15600           std::swap(LHS, RHS);
15601         }
15602         Opcode = X86ISD::FMIN;
15603         break;
15604       case ISD::SETUGT:
15605         // Converting this to a min would handle NaNs incorrectly.
15606         if (!DAG.getTarget().Options.UnsafeFPMath &&
15607             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15608           break;
15609         Opcode = X86ISD::FMIN;
15610         break;
15611       case ISD::SETUGE:
15612         // Converting this to a min would handle both negative zeros and NaNs
15613         // incorrectly, but we can swap the operands to fix both.
15614         std::swap(LHS, RHS);
15615       case ISD::SETOGT:
15616       case ISD::SETGT:
15617       case ISD::SETGE:
15618         Opcode = X86ISD::FMIN;
15619         break;
15620
15621       case ISD::SETULT:
15622         // Converting this to a max would handle NaNs incorrectly.
15623         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15624           break;
15625         Opcode = X86ISD::FMAX;
15626         break;
15627       case ISD::SETOLE:
15628         // Converting this to a max would handle comparisons between positive
15629         // and negative zero incorrectly, and swapping the operands would
15630         // cause it to handle NaNs incorrectly.
15631         if (!DAG.getTarget().Options.UnsafeFPMath &&
15632             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15633           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15634             break;
15635           std::swap(LHS, RHS);
15636         }
15637         Opcode = X86ISD::FMAX;
15638         break;
15639       case ISD::SETULE:
15640         // Converting this to a max would handle both negative zeros and NaNs
15641         // incorrectly, but we can swap the operands to fix both.
15642         std::swap(LHS, RHS);
15643       case ISD::SETOLT:
15644       case ISD::SETLT:
15645       case ISD::SETLE:
15646         Opcode = X86ISD::FMAX;
15647         break;
15648       }
15649     }
15650
15651     if (Opcode)
15652       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15653   }
15654
15655   // If this is a select between two integer constants, try to do some
15656   // optimizations.
15657   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15658     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15659       // Don't do this for crazy integer types.
15660       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15661         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15662         // so that TrueC (the true value) is larger than FalseC.
15663         bool NeedsCondInvert = false;
15664
15665         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15666             // Efficiently invertible.
15667             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15668              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15669               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15670           NeedsCondInvert = true;
15671           std::swap(TrueC, FalseC);
15672         }
15673
15674         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15675         if (FalseC->getAPIntValue() == 0 &&
15676             TrueC->getAPIntValue().isPowerOf2()) {
15677           if (NeedsCondInvert) // Invert the condition if needed.
15678             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15679                                DAG.getConstant(1, Cond.getValueType()));
15680
15681           // Zero extend the condition if needed.
15682           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15683
15684           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15685           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15686                              DAG.getConstant(ShAmt, MVT::i8));
15687         }
15688
15689         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15690         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15691           if (NeedsCondInvert) // Invert the condition if needed.
15692             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15693                                DAG.getConstant(1, Cond.getValueType()));
15694
15695           // Zero extend the condition if needed.
15696           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15697                              FalseC->getValueType(0), Cond);
15698           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15699                              SDValue(FalseC, 0));
15700         }
15701
15702         // Optimize cases that will turn into an LEA instruction.  This requires
15703         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15704         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15705           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15706           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15707
15708           bool isFastMultiplier = false;
15709           if (Diff < 10) {
15710             switch ((unsigned char)Diff) {
15711               default: break;
15712               case 1:  // result = add base, cond
15713               case 2:  // result = lea base(    , cond*2)
15714               case 3:  // result = lea base(cond, cond*2)
15715               case 4:  // result = lea base(    , cond*4)
15716               case 5:  // result = lea base(cond, cond*4)
15717               case 8:  // result = lea base(    , cond*8)
15718               case 9:  // result = lea base(cond, cond*8)
15719                 isFastMultiplier = true;
15720                 break;
15721             }
15722           }
15723
15724           if (isFastMultiplier) {
15725             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15726             if (NeedsCondInvert) // Invert the condition if needed.
15727               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15728                                  DAG.getConstant(1, Cond.getValueType()));
15729
15730             // Zero extend the condition if needed.
15731             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15732                                Cond);
15733             // Scale the condition by the difference.
15734             if (Diff != 1)
15735               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15736                                  DAG.getConstant(Diff, Cond.getValueType()));
15737
15738             // Add the base if non-zero.
15739             if (FalseC->getAPIntValue() != 0)
15740               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15741                                  SDValue(FalseC, 0));
15742             return Cond;
15743           }
15744         }
15745       }
15746   }
15747
15748   // Canonicalize max and min:
15749   // (x > y) ? x : y -> (x >= y) ? x : y
15750   // (x < y) ? x : y -> (x <= y) ? x : y
15751   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15752   // the need for an extra compare
15753   // against zero. e.g.
15754   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15755   // subl   %esi, %edi
15756   // testl  %edi, %edi
15757   // movl   $0, %eax
15758   // cmovgl %edi, %eax
15759   // =>
15760   // xorl   %eax, %eax
15761   // subl   %esi, $edi
15762   // cmovsl %eax, %edi
15763   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15764       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15765       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15766     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15767     switch (CC) {
15768     default: break;
15769     case ISD::SETLT:
15770     case ISD::SETGT: {
15771       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15772       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
15773                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15774       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15775     }
15776     }
15777   }
15778
15779   // Match VSELECTs into subs with unsigned saturation.
15780   if (!DCI.isBeforeLegalize() &&
15781       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15782       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15783       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15784        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15785     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15786
15787     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15788     // left side invert the predicate to simplify logic below.
15789     SDValue Other;
15790     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15791       Other = RHS;
15792       CC = ISD::getSetCCInverse(CC, true);
15793     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15794       Other = LHS;
15795     }
15796
15797     if (Other.getNode() && Other->getNumOperands() == 2 &&
15798         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15799       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15800       SDValue CondRHS = Cond->getOperand(1);
15801
15802       // Look for a general sub with unsigned saturation first.
15803       // x >= y ? x-y : 0 --> subus x, y
15804       // x >  y ? x-y : 0 --> subus x, y
15805       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15806           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15807         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15808
15809       // If the RHS is a constant we have to reverse the const canonicalization.
15810       // x > C-1 ? x+-C : 0 --> subus x, C
15811       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15812           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15813         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15814         if (CondRHS.getConstantOperandVal(0) == -A-1)
15815           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15816                              DAG.getConstant(-A, VT));
15817       }
15818
15819       // Another special case: If C was a sign bit, the sub has been
15820       // canonicalized into a xor.
15821       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15822       //        it's safe to decanonicalize the xor?
15823       // x s< 0 ? x^C : 0 --> subus x, C
15824       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15825           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15826           isSplatVector(OpRHS.getNode())) {
15827         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15828         if (A.isSignBit())
15829           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15830       }
15831     }
15832   }
15833
15834   // Try to match a min/max vector operation.
15835   if (!DCI.isBeforeLegalize() &&
15836       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15837     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15838       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15839
15840   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
15841   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
15842       Cond.getOpcode() == ISD::SETCC) {
15843
15844     assert(Cond.getValueType().isVector() &&
15845            "vector select expects a vector selector!");
15846
15847     EVT IntVT = Cond.getValueType();
15848     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
15849     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
15850
15851     if (!TValIsAllOnes && !FValIsAllZeros) {
15852       // Try invert the condition if true value is not all 1s and false value
15853       // is not all 0s.
15854       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
15855       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
15856
15857       if (TValIsAllZeros || FValIsAllOnes) {
15858         SDValue CC = Cond.getOperand(2);
15859         ISD::CondCode NewCC =
15860           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
15861                                Cond.getOperand(0).getValueType().isInteger());
15862         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
15863         std::swap(LHS, RHS);
15864         TValIsAllOnes = FValIsAllOnes;
15865         FValIsAllZeros = TValIsAllZeros;
15866       }
15867     }
15868
15869     if (TValIsAllOnes || FValIsAllZeros) {
15870       SDValue Ret;
15871
15872       if (TValIsAllOnes && FValIsAllZeros)
15873         Ret = Cond;
15874       else if (TValIsAllOnes)
15875         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
15876                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
15877       else if (FValIsAllZeros)
15878         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
15879                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
15880
15881       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
15882     }
15883   }
15884
15885   // If we know that this node is legal then we know that it is going to be
15886   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15887   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15888   // to simplify previous instructions.
15889   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15890   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15891       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15892     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15893
15894     // Don't optimize vector selects that map to mask-registers.
15895     if (BitWidth == 1)
15896       return SDValue();
15897
15898     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15899     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15900
15901     APInt KnownZero, KnownOne;
15902     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15903                                           DCI.isBeforeLegalizeOps());
15904     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15905         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15906       DCI.CommitTargetLoweringOpt(TLO);
15907   }
15908
15909   return SDValue();
15910 }
15911
15912 // Check whether a boolean test is testing a boolean value generated by
15913 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15914 // code.
15915 //
15916 // Simplify the following patterns:
15917 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15918 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15919 // to (Op EFLAGS Cond)
15920 //
15921 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15922 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15923 // to (Op EFLAGS !Cond)
15924 //
15925 // where Op could be BRCOND or CMOV.
15926 //
15927 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15928   // Quit if not CMP and SUB with its value result used.
15929   if (Cmp.getOpcode() != X86ISD::CMP &&
15930       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15931       return SDValue();
15932
15933   // Quit if not used as a boolean value.
15934   if (CC != X86::COND_E && CC != X86::COND_NE)
15935     return SDValue();
15936
15937   // Check CMP operands. One of them should be 0 or 1 and the other should be
15938   // an SetCC or extended from it.
15939   SDValue Op1 = Cmp.getOperand(0);
15940   SDValue Op2 = Cmp.getOperand(1);
15941
15942   SDValue SetCC;
15943   const ConstantSDNode* C = 0;
15944   bool needOppositeCond = (CC == X86::COND_E);
15945   bool checkAgainstTrue = false; // Is it a comparison against 1?
15946
15947   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15948     SetCC = Op2;
15949   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15950     SetCC = Op1;
15951   else // Quit if all operands are not constants.
15952     return SDValue();
15953
15954   if (C->getZExtValue() == 1) {
15955     needOppositeCond = !needOppositeCond;
15956     checkAgainstTrue = true;
15957   } else if (C->getZExtValue() != 0)
15958     // Quit if the constant is neither 0 or 1.
15959     return SDValue();
15960
15961   bool truncatedToBoolWithAnd = false;
15962   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
15963   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15964          SetCC.getOpcode() == ISD::TRUNCATE ||
15965          SetCC.getOpcode() == ISD::AND) {
15966     if (SetCC.getOpcode() == ISD::AND) {
15967       int OpIdx = -1;
15968       ConstantSDNode *CS;
15969       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
15970           CS->getZExtValue() == 1)
15971         OpIdx = 1;
15972       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
15973           CS->getZExtValue() == 1)
15974         OpIdx = 0;
15975       if (OpIdx == -1)
15976         break;
15977       SetCC = SetCC.getOperand(OpIdx);
15978       truncatedToBoolWithAnd = true;
15979     } else
15980       SetCC = SetCC.getOperand(0);
15981   }
15982
15983   switch (SetCC.getOpcode()) {
15984   case X86ISD::SETCC_CARRY:
15985     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
15986     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
15987     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
15988     // truncated to i1 using 'and'.
15989     if (checkAgainstTrue && !truncatedToBoolWithAnd)
15990       break;
15991     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
15992            "Invalid use of SETCC_CARRY!");
15993     // FALL THROUGH
15994   case X86ISD::SETCC:
15995     // Set the condition code or opposite one if necessary.
15996     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15997     if (needOppositeCond)
15998       CC = X86::GetOppositeBranchCondition(CC);
15999     return SetCC.getOperand(1);
16000   case X86ISD::CMOV: {
16001     // Check whether false/true value has canonical one, i.e. 0 or 1.
16002     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
16003     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
16004     // Quit if true value is not a constant.
16005     if (!TVal)
16006       return SDValue();
16007     // Quit if false value is not a constant.
16008     if (!FVal) {
16009       SDValue Op = SetCC.getOperand(0);
16010       // Skip 'zext' or 'trunc' node.
16011       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
16012           Op.getOpcode() == ISD::TRUNCATE)
16013         Op = Op.getOperand(0);
16014       // A special case for rdrand/rdseed, where 0 is set if false cond is
16015       // found.
16016       if ((Op.getOpcode() != X86ISD::RDRAND &&
16017            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
16018         return SDValue();
16019     }
16020     // Quit if false value is not the constant 0 or 1.
16021     bool FValIsFalse = true;
16022     if (FVal && FVal->getZExtValue() != 0) {
16023       if (FVal->getZExtValue() != 1)
16024         return SDValue();
16025       // If FVal is 1, opposite cond is needed.
16026       needOppositeCond = !needOppositeCond;
16027       FValIsFalse = false;
16028     }
16029     // Quit if TVal is not the constant opposite of FVal.
16030     if (FValIsFalse && TVal->getZExtValue() != 1)
16031       return SDValue();
16032     if (!FValIsFalse && TVal->getZExtValue() != 0)
16033       return SDValue();
16034     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16035     if (needOppositeCond)
16036       CC = X86::GetOppositeBranchCondition(CC);
16037     return SetCC.getOperand(3);
16038   }
16039   }
16040
16041   return SDValue();
16042 }
16043
16044 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16045 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16046                                   TargetLowering::DAGCombinerInfo &DCI,
16047                                   const X86Subtarget *Subtarget) {
16048   SDLoc DL(N);
16049
16050   // If the flag operand isn't dead, don't touch this CMOV.
16051   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16052     return SDValue();
16053
16054   SDValue FalseOp = N->getOperand(0);
16055   SDValue TrueOp = N->getOperand(1);
16056   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16057   SDValue Cond = N->getOperand(3);
16058
16059   if (CC == X86::COND_E || CC == X86::COND_NE) {
16060     switch (Cond.getOpcode()) {
16061     default: break;
16062     case X86ISD::BSR:
16063     case X86ISD::BSF:
16064       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16065       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16066         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16067     }
16068   }
16069
16070   SDValue Flags;
16071
16072   Flags = checkBoolTestSetCCCombine(Cond, CC);
16073   if (Flags.getNode() &&
16074       // Extra check as FCMOV only supports a subset of X86 cond.
16075       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16076     SDValue Ops[] = { FalseOp, TrueOp,
16077                       DAG.getConstant(CC, MVT::i8), Flags };
16078     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16079                        Ops, array_lengthof(Ops));
16080   }
16081
16082   // If this is a select between two integer constants, try to do some
16083   // optimizations.  Note that the operands are ordered the opposite of SELECT
16084   // operands.
16085   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16086     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16087       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16088       // larger than FalseC (the false value).
16089       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16090         CC = X86::GetOppositeBranchCondition(CC);
16091         std::swap(TrueC, FalseC);
16092         std::swap(TrueOp, FalseOp);
16093       }
16094
16095       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16096       // This is efficient for any integer data type (including i8/i16) and
16097       // shift amount.
16098       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16099         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16100                            DAG.getConstant(CC, MVT::i8), Cond);
16101
16102         // Zero extend the condition if needed.
16103         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16104
16105         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16106         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16107                            DAG.getConstant(ShAmt, MVT::i8));
16108         if (N->getNumValues() == 2)  // Dead flag value?
16109           return DCI.CombineTo(N, Cond, SDValue());
16110         return Cond;
16111       }
16112
16113       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16114       // for any integer data type, including i8/i16.
16115       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16116         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16117                            DAG.getConstant(CC, MVT::i8), Cond);
16118
16119         // Zero extend the condition if needed.
16120         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16121                            FalseC->getValueType(0), Cond);
16122         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16123                            SDValue(FalseC, 0));
16124
16125         if (N->getNumValues() == 2)  // Dead flag value?
16126           return DCI.CombineTo(N, Cond, SDValue());
16127         return Cond;
16128       }
16129
16130       // Optimize cases that will turn into an LEA instruction.  This requires
16131       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16132       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16133         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16134         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16135
16136         bool isFastMultiplier = false;
16137         if (Diff < 10) {
16138           switch ((unsigned char)Diff) {
16139           default: break;
16140           case 1:  // result = add base, cond
16141           case 2:  // result = lea base(    , cond*2)
16142           case 3:  // result = lea base(cond, cond*2)
16143           case 4:  // result = lea base(    , cond*4)
16144           case 5:  // result = lea base(cond, cond*4)
16145           case 8:  // result = lea base(    , cond*8)
16146           case 9:  // result = lea base(cond, cond*8)
16147             isFastMultiplier = true;
16148             break;
16149           }
16150         }
16151
16152         if (isFastMultiplier) {
16153           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16154           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16155                              DAG.getConstant(CC, MVT::i8), Cond);
16156           // Zero extend the condition if needed.
16157           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16158                              Cond);
16159           // Scale the condition by the difference.
16160           if (Diff != 1)
16161             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16162                                DAG.getConstant(Diff, Cond.getValueType()));
16163
16164           // Add the base if non-zero.
16165           if (FalseC->getAPIntValue() != 0)
16166             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16167                                SDValue(FalseC, 0));
16168           if (N->getNumValues() == 2)  // Dead flag value?
16169             return DCI.CombineTo(N, Cond, SDValue());
16170           return Cond;
16171         }
16172       }
16173     }
16174   }
16175
16176   // Handle these cases:
16177   //   (select (x != c), e, c) -> select (x != c), e, x),
16178   //   (select (x == c), c, e) -> select (x == c), x, e)
16179   // where the c is an integer constant, and the "select" is the combination
16180   // of CMOV and CMP.
16181   //
16182   // The rationale for this change is that the conditional-move from a constant
16183   // needs two instructions, however, conditional-move from a register needs
16184   // only one instruction.
16185   //
16186   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16187   //  some instruction-combining opportunities. This opt needs to be
16188   //  postponed as late as possible.
16189   //
16190   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16191     // the DCI.xxxx conditions are provided to postpone the optimization as
16192     // late as possible.
16193
16194     ConstantSDNode *CmpAgainst = 0;
16195     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16196         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16197         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16198
16199       if (CC == X86::COND_NE &&
16200           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16201         CC = X86::GetOppositeBranchCondition(CC);
16202         std::swap(TrueOp, FalseOp);
16203       }
16204
16205       if (CC == X86::COND_E &&
16206           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16207         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16208                           DAG.getConstant(CC, MVT::i8), Cond };
16209         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16210                            array_lengthof(Ops));
16211       }
16212     }
16213   }
16214
16215   return SDValue();
16216 }
16217
16218 /// PerformMulCombine - Optimize a single multiply with constant into two
16219 /// in order to implement it with two cheaper instructions, e.g.
16220 /// LEA + SHL, LEA + LEA.
16221 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16222                                  TargetLowering::DAGCombinerInfo &DCI) {
16223   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16224     return SDValue();
16225
16226   EVT VT = N->getValueType(0);
16227   if (VT != MVT::i64)
16228     return SDValue();
16229
16230   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16231   if (!C)
16232     return SDValue();
16233   uint64_t MulAmt = C->getZExtValue();
16234   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16235     return SDValue();
16236
16237   uint64_t MulAmt1 = 0;
16238   uint64_t MulAmt2 = 0;
16239   if ((MulAmt % 9) == 0) {
16240     MulAmt1 = 9;
16241     MulAmt2 = MulAmt / 9;
16242   } else if ((MulAmt % 5) == 0) {
16243     MulAmt1 = 5;
16244     MulAmt2 = MulAmt / 5;
16245   } else if ((MulAmt % 3) == 0) {
16246     MulAmt1 = 3;
16247     MulAmt2 = MulAmt / 3;
16248   }
16249   if (MulAmt2 &&
16250       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16251     SDLoc DL(N);
16252
16253     if (isPowerOf2_64(MulAmt2) &&
16254         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16255       // If second multiplifer is pow2, issue it first. We want the multiply by
16256       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16257       // is an add.
16258       std::swap(MulAmt1, MulAmt2);
16259
16260     SDValue NewMul;
16261     if (isPowerOf2_64(MulAmt1))
16262       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16263                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16264     else
16265       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16266                            DAG.getConstant(MulAmt1, VT));
16267
16268     if (isPowerOf2_64(MulAmt2))
16269       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16270                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16271     else
16272       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16273                            DAG.getConstant(MulAmt2, VT));
16274
16275     // Do not add new nodes to DAG combiner worklist.
16276     DCI.CombineTo(N, NewMul, false);
16277   }
16278   return SDValue();
16279 }
16280
16281 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16282   SDValue N0 = N->getOperand(0);
16283   SDValue N1 = N->getOperand(1);
16284   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16285   EVT VT = N0.getValueType();
16286
16287   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16288   // since the result of setcc_c is all zero's or all ones.
16289   if (VT.isInteger() && !VT.isVector() &&
16290       N1C && N0.getOpcode() == ISD::AND &&
16291       N0.getOperand(1).getOpcode() == ISD::Constant) {
16292     SDValue N00 = N0.getOperand(0);
16293     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16294         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16295           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16296          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16297       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16298       APInt ShAmt = N1C->getAPIntValue();
16299       Mask = Mask.shl(ShAmt);
16300       if (Mask != 0)
16301         return DAG.getNode(ISD::AND, SDLoc(N), VT,
16302                            N00, DAG.getConstant(Mask, VT));
16303     }
16304   }
16305
16306   // Hardware support for vector shifts is sparse which makes us scalarize the
16307   // vector operations in many cases. Also, on sandybridge ADD is faster than
16308   // shl.
16309   // (shl V, 1) -> add V,V
16310   if (isSplatVector(N1.getNode())) {
16311     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16312     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16313     // We shift all of the values by one. In many cases we do not have
16314     // hardware support for this operation. This is better expressed as an ADD
16315     // of two values.
16316     if (N1C && (1 == N1C->getZExtValue())) {
16317       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16318     }
16319   }
16320
16321   return SDValue();
16322 }
16323
16324 /// \brief Returns a vector of 0s if the node in input is a vector logical
16325 /// shift by a constant amount which is known to be bigger than or equal 
16326 /// to the vector element size in bits.
16327 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
16328                                       const X86Subtarget *Subtarget) {
16329   EVT VT = N->getValueType(0);
16330
16331   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
16332       (!Subtarget->hasInt256() ||
16333        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
16334     return SDValue();
16335
16336   SDValue Amt = N->getOperand(1);
16337   SDLoc DL(N);
16338   if (isSplatVector(Amt.getNode())) {
16339     SDValue SclrAmt = Amt->getOperand(0);
16340     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
16341       APInt ShiftAmt = C->getAPIntValue();
16342       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
16343
16344       // SSE2/AVX2 logical shifts always return a vector of 0s
16345       // if the shift amount is bigger than or equal to 
16346       // the element size. The constant shift amount will be
16347       // encoded as a 8-bit immediate.
16348       if (ShiftAmt.trunc(8).uge(MaxAmount))
16349         return getZeroVector(VT, Subtarget, DAG, DL);
16350     }
16351   }
16352
16353   return SDValue();
16354 }
16355
16356 /// PerformShiftCombine - Combine shifts.
16357 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16358                                    TargetLowering::DAGCombinerInfo &DCI,
16359                                    const X86Subtarget *Subtarget) {
16360   if (N->getOpcode() == ISD::SHL) {
16361     SDValue V = PerformSHLCombine(N, DAG);
16362     if (V.getNode()) return V;
16363   }
16364
16365   if (N->getOpcode() != ISD::SRA) {
16366     // Try to fold this logical shift into a zero vector.
16367     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
16368     if (V.getNode()) return V;
16369   }
16370
16371   return SDValue();
16372 }
16373
16374 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16375 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16376 // and friends.  Likewise for OR -> CMPNEQSS.
16377 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16378                             TargetLowering::DAGCombinerInfo &DCI,
16379                             const X86Subtarget *Subtarget) {
16380   unsigned opcode;
16381
16382   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16383   // we're requiring SSE2 for both.
16384   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16385     SDValue N0 = N->getOperand(0);
16386     SDValue N1 = N->getOperand(1);
16387     SDValue CMP0 = N0->getOperand(1);
16388     SDValue CMP1 = N1->getOperand(1);
16389     SDLoc DL(N);
16390
16391     // The SETCCs should both refer to the same CMP.
16392     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16393       return SDValue();
16394
16395     SDValue CMP00 = CMP0->getOperand(0);
16396     SDValue CMP01 = CMP0->getOperand(1);
16397     EVT     VT    = CMP00.getValueType();
16398
16399     if (VT == MVT::f32 || VT == MVT::f64) {
16400       bool ExpectingFlags = false;
16401       // Check for any users that want flags:
16402       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16403            !ExpectingFlags && UI != UE; ++UI)
16404         switch (UI->getOpcode()) {
16405         default:
16406         case ISD::BR_CC:
16407         case ISD::BRCOND:
16408         case ISD::SELECT:
16409           ExpectingFlags = true;
16410           break;
16411         case ISD::CopyToReg:
16412         case ISD::SIGN_EXTEND:
16413         case ISD::ZERO_EXTEND:
16414         case ISD::ANY_EXTEND:
16415           break;
16416         }
16417
16418       if (!ExpectingFlags) {
16419         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16420         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16421
16422         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16423           X86::CondCode tmp = cc0;
16424           cc0 = cc1;
16425           cc1 = tmp;
16426         }
16427
16428         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16429             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16430           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16431           X86ISD::NodeType NTOperator = is64BitFP ?
16432             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16433           // FIXME: need symbolic constants for these magic numbers.
16434           // See X86ATTInstPrinter.cpp:printSSECC().
16435           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16436           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16437                                               DAG.getConstant(x86cc, MVT::i8));
16438           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16439                                               OnesOrZeroesF);
16440           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16441                                       DAG.getConstant(1, MVT::i32));
16442           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16443           return OneBitOfTruth;
16444         }
16445       }
16446     }
16447   }
16448   return SDValue();
16449 }
16450
16451 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16452 /// so it can be folded inside ANDNP.
16453 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16454   EVT VT = N->getValueType(0);
16455
16456   // Match direct AllOnes for 128 and 256-bit vectors
16457   if (ISD::isBuildVectorAllOnes(N))
16458     return true;
16459
16460   // Look through a bit convert.
16461   if (N->getOpcode() == ISD::BITCAST)
16462     N = N->getOperand(0).getNode();
16463
16464   // Sometimes the operand may come from a insert_subvector building a 256-bit
16465   // allones vector
16466   if (VT.is256BitVector() &&
16467       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16468     SDValue V1 = N->getOperand(0);
16469     SDValue V2 = N->getOperand(1);
16470
16471     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16472         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16473         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16474         ISD::isBuildVectorAllOnes(V2.getNode()))
16475       return true;
16476   }
16477
16478   return false;
16479 }
16480
16481 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16482 // register. In most cases we actually compare or select YMM-sized registers
16483 // and mixing the two types creates horrible code. This method optimizes
16484 // some of the transition sequences.
16485 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16486                                  TargetLowering::DAGCombinerInfo &DCI,
16487                                  const X86Subtarget *Subtarget) {
16488   EVT VT = N->getValueType(0);
16489   if (!VT.is256BitVector())
16490     return SDValue();
16491
16492   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16493           N->getOpcode() == ISD::ZERO_EXTEND ||
16494           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16495
16496   SDValue Narrow = N->getOperand(0);
16497   EVT NarrowVT = Narrow->getValueType(0);
16498   if (!NarrowVT.is128BitVector())
16499     return SDValue();
16500
16501   if (Narrow->getOpcode() != ISD::XOR &&
16502       Narrow->getOpcode() != ISD::AND &&
16503       Narrow->getOpcode() != ISD::OR)
16504     return SDValue();
16505
16506   SDValue N0  = Narrow->getOperand(0);
16507   SDValue N1  = Narrow->getOperand(1);
16508   SDLoc DL(Narrow);
16509
16510   // The Left side has to be a trunc.
16511   if (N0.getOpcode() != ISD::TRUNCATE)
16512     return SDValue();
16513
16514   // The type of the truncated inputs.
16515   EVT WideVT = N0->getOperand(0)->getValueType(0);
16516   if (WideVT != VT)
16517     return SDValue();
16518
16519   // The right side has to be a 'trunc' or a constant vector.
16520   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16521   bool RHSConst = (isSplatVector(N1.getNode()) &&
16522                    isa<ConstantSDNode>(N1->getOperand(0)));
16523   if (!RHSTrunc && !RHSConst)
16524     return SDValue();
16525
16526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16527
16528   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16529     return SDValue();
16530
16531   // Set N0 and N1 to hold the inputs to the new wide operation.
16532   N0 = N0->getOperand(0);
16533   if (RHSConst) {
16534     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16535                      N1->getOperand(0));
16536     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16537     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16538   } else if (RHSTrunc) {
16539     N1 = N1->getOperand(0);
16540   }
16541
16542   // Generate the wide operation.
16543   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16544   unsigned Opcode = N->getOpcode();
16545   switch (Opcode) {
16546   case ISD::ANY_EXTEND:
16547     return Op;
16548   case ISD::ZERO_EXTEND: {
16549     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16550     APInt Mask = APInt::getAllOnesValue(InBits);
16551     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16552     return DAG.getNode(ISD::AND, DL, VT,
16553                        Op, DAG.getConstant(Mask, VT));
16554   }
16555   case ISD::SIGN_EXTEND:
16556     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16557                        Op, DAG.getValueType(NarrowVT));
16558   default:
16559     llvm_unreachable("Unexpected opcode");
16560   }
16561 }
16562
16563 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16564                                  TargetLowering::DAGCombinerInfo &DCI,
16565                                  const X86Subtarget *Subtarget) {
16566   EVT VT = N->getValueType(0);
16567   if (DCI.isBeforeLegalizeOps())
16568     return SDValue();
16569
16570   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16571   if (R.getNode())
16572     return R;
16573
16574   // Create BLSI, and BLSR instructions
16575   // BLSI is X & (-X)
16576   // BLSR is X & (X-1)
16577   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16578     SDValue N0 = N->getOperand(0);
16579     SDValue N1 = N->getOperand(1);
16580     SDLoc DL(N);
16581
16582     // Check LHS for neg
16583     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16584         isZero(N0.getOperand(0)))
16585       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16586
16587     // Check RHS for neg
16588     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16589         isZero(N1.getOperand(0)))
16590       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16591
16592     // Check LHS for X-1
16593     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16594         isAllOnes(N0.getOperand(1)))
16595       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16596
16597     // Check RHS for X-1
16598     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16599         isAllOnes(N1.getOperand(1)))
16600       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16601
16602     return SDValue();
16603   }
16604
16605   // Want to form ANDNP nodes:
16606   // 1) In the hopes of then easily combining them with OR and AND nodes
16607   //    to form PBLEND/PSIGN.
16608   // 2) To match ANDN packed intrinsics
16609   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16610     return SDValue();
16611
16612   SDValue N0 = N->getOperand(0);
16613   SDValue N1 = N->getOperand(1);
16614   SDLoc DL(N);
16615
16616   // Check LHS for vnot
16617   if (N0.getOpcode() == ISD::XOR &&
16618       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16619       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16620     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16621
16622   // Check RHS for vnot
16623   if (N1.getOpcode() == ISD::XOR &&
16624       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16625       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16626     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16627
16628   return SDValue();
16629 }
16630
16631 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16632                                 TargetLowering::DAGCombinerInfo &DCI,
16633                                 const X86Subtarget *Subtarget) {
16634   EVT VT = N->getValueType(0);
16635   if (DCI.isBeforeLegalizeOps())
16636     return SDValue();
16637
16638   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16639   if (R.getNode())
16640     return R;
16641
16642   SDValue N0 = N->getOperand(0);
16643   SDValue N1 = N->getOperand(1);
16644
16645   // look for psign/blend
16646   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16647     if (!Subtarget->hasSSSE3() ||
16648         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16649       return SDValue();
16650
16651     // Canonicalize pandn to RHS
16652     if (N0.getOpcode() == X86ISD::ANDNP)
16653       std::swap(N0, N1);
16654     // or (and (m, y), (pandn m, x))
16655     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16656       SDValue Mask = N1.getOperand(0);
16657       SDValue X    = N1.getOperand(1);
16658       SDValue Y;
16659       if (N0.getOperand(0) == Mask)
16660         Y = N0.getOperand(1);
16661       if (N0.getOperand(1) == Mask)
16662         Y = N0.getOperand(0);
16663
16664       // Check to see if the mask appeared in both the AND and ANDNP and
16665       if (!Y.getNode())
16666         return SDValue();
16667
16668       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16669       // Look through mask bitcast.
16670       if (Mask.getOpcode() == ISD::BITCAST)
16671         Mask = Mask.getOperand(0);
16672       if (X.getOpcode() == ISD::BITCAST)
16673         X = X.getOperand(0);
16674       if (Y.getOpcode() == ISD::BITCAST)
16675         Y = Y.getOperand(0);
16676
16677       EVT MaskVT = Mask.getValueType();
16678
16679       // Validate that the Mask operand is a vector sra node.
16680       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16681       // there is no psrai.b
16682       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16683       unsigned SraAmt = ~0;
16684       if (Mask.getOpcode() == ISD::SRA) {
16685         SDValue Amt = Mask.getOperand(1);
16686         if (isSplatVector(Amt.getNode())) {
16687           SDValue SclrAmt = Amt->getOperand(0);
16688           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16689             SraAmt = C->getZExtValue();
16690         }
16691       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16692         SDValue SraC = Mask.getOperand(1);
16693         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16694       }
16695       if ((SraAmt + 1) != EltBits)
16696         return SDValue();
16697
16698       SDLoc DL(N);
16699
16700       // Now we know we at least have a plendvb with the mask val.  See if
16701       // we can form a psignb/w/d.
16702       // psign = x.type == y.type == mask.type && y = sub(0, x);
16703       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16704           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16705           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16706         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16707                "Unsupported VT for PSIGN");
16708         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16709         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16710       }
16711       // PBLENDVB only available on SSE 4.1
16712       if (!Subtarget->hasSSE41())
16713         return SDValue();
16714
16715       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16716
16717       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16718       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16719       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16720       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16721       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16722     }
16723   }
16724
16725   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16726     return SDValue();
16727
16728   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16729   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16730     std::swap(N0, N1);
16731   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16732     return SDValue();
16733   if (!N0.hasOneUse() || !N1.hasOneUse())
16734     return SDValue();
16735
16736   SDValue ShAmt0 = N0.getOperand(1);
16737   if (ShAmt0.getValueType() != MVT::i8)
16738     return SDValue();
16739   SDValue ShAmt1 = N1.getOperand(1);
16740   if (ShAmt1.getValueType() != MVT::i8)
16741     return SDValue();
16742   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16743     ShAmt0 = ShAmt0.getOperand(0);
16744   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16745     ShAmt1 = ShAmt1.getOperand(0);
16746
16747   SDLoc DL(N);
16748   unsigned Opc = X86ISD::SHLD;
16749   SDValue Op0 = N0.getOperand(0);
16750   SDValue Op1 = N1.getOperand(0);
16751   if (ShAmt0.getOpcode() == ISD::SUB) {
16752     Opc = X86ISD::SHRD;
16753     std::swap(Op0, Op1);
16754     std::swap(ShAmt0, ShAmt1);
16755   }
16756
16757   unsigned Bits = VT.getSizeInBits();
16758   if (ShAmt1.getOpcode() == ISD::SUB) {
16759     SDValue Sum = ShAmt1.getOperand(0);
16760     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16761       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16762       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16763         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16764       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16765         return DAG.getNode(Opc, DL, VT,
16766                            Op0, Op1,
16767                            DAG.getNode(ISD::TRUNCATE, DL,
16768                                        MVT::i8, ShAmt0));
16769     }
16770   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16771     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16772     if (ShAmt0C &&
16773         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16774       return DAG.getNode(Opc, DL, VT,
16775                          N0.getOperand(0), N1.getOperand(0),
16776                          DAG.getNode(ISD::TRUNCATE, DL,
16777                                        MVT::i8, ShAmt0));
16778   }
16779
16780   return SDValue();
16781 }
16782
16783 // Generate NEG and CMOV for integer abs.
16784 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16785   EVT VT = N->getValueType(0);
16786
16787   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16788   // 8-bit integer abs to NEG and CMOV.
16789   if (VT.isInteger() && VT.getSizeInBits() == 8)
16790     return SDValue();
16791
16792   SDValue N0 = N->getOperand(0);
16793   SDValue N1 = N->getOperand(1);
16794   SDLoc DL(N);
16795
16796   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16797   // and change it to SUB and CMOV.
16798   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16799       N0.getOpcode() == ISD::ADD &&
16800       N0.getOperand(1) == N1 &&
16801       N1.getOpcode() == ISD::SRA &&
16802       N1.getOperand(0) == N0.getOperand(0))
16803     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16804       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16805         // Generate SUB & CMOV.
16806         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16807                                   DAG.getConstant(0, VT), N0.getOperand(0));
16808
16809         SDValue Ops[] = { N0.getOperand(0), Neg,
16810                           DAG.getConstant(X86::COND_GE, MVT::i8),
16811                           SDValue(Neg.getNode(), 1) };
16812         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16813                            Ops, array_lengthof(Ops));
16814       }
16815   return SDValue();
16816 }
16817
16818 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16819 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16820                                  TargetLowering::DAGCombinerInfo &DCI,
16821                                  const X86Subtarget *Subtarget) {
16822   EVT VT = N->getValueType(0);
16823   if (DCI.isBeforeLegalizeOps())
16824     return SDValue();
16825
16826   if (Subtarget->hasCMov()) {
16827     SDValue RV = performIntegerAbsCombine(N, DAG);
16828     if (RV.getNode())
16829       return RV;
16830   }
16831
16832   // Try forming BMI if it is available.
16833   if (!Subtarget->hasBMI())
16834     return SDValue();
16835
16836   if (VT != MVT::i32 && VT != MVT::i64)
16837     return SDValue();
16838
16839   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16840
16841   // Create BLSMSK instructions by finding X ^ (X-1)
16842   SDValue N0 = N->getOperand(0);
16843   SDValue N1 = N->getOperand(1);
16844   SDLoc DL(N);
16845
16846   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16847       isAllOnes(N0.getOperand(1)))
16848     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16849
16850   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16851       isAllOnes(N1.getOperand(1)))
16852     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16853
16854   return SDValue();
16855 }
16856
16857 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16858 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16859                                   TargetLowering::DAGCombinerInfo &DCI,
16860                                   const X86Subtarget *Subtarget) {
16861   LoadSDNode *Ld = cast<LoadSDNode>(N);
16862   EVT RegVT = Ld->getValueType(0);
16863   EVT MemVT = Ld->getMemoryVT();
16864   SDLoc dl(Ld);
16865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16866   unsigned RegSz = RegVT.getSizeInBits();
16867
16868   // On Sandybridge unaligned 256bit loads are inefficient.
16869   ISD::LoadExtType Ext = Ld->getExtensionType();
16870   unsigned Alignment = Ld->getAlignment();
16871   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16872   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16873       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16874     unsigned NumElems = RegVT.getVectorNumElements();
16875     if (NumElems < 2)
16876       return SDValue();
16877
16878     SDValue Ptr = Ld->getBasePtr();
16879     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16880
16881     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16882                                   NumElems/2);
16883     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16884                                 Ld->getPointerInfo(), Ld->isVolatile(),
16885                                 Ld->isNonTemporal(), Ld->isInvariant(),
16886                                 Alignment);
16887     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16888     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16889                                 Ld->getPointerInfo(), Ld->isVolatile(),
16890                                 Ld->isNonTemporal(), Ld->isInvariant(),
16891                                 std::min(16U, Alignment));
16892     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16893                              Load1.getValue(1),
16894                              Load2.getValue(1));
16895
16896     SDValue NewVec = DAG.getUNDEF(RegVT);
16897     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16898     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16899     return DCI.CombineTo(N, NewVec, TF, true);
16900   }
16901
16902   // If this is a vector EXT Load then attempt to optimize it using a
16903   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16904   // expansion is still better than scalar code.
16905   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16906   // emit a shuffle and a arithmetic shift.
16907   // TODO: It is possible to support ZExt by zeroing the undef values
16908   // during the shuffle phase or after the shuffle.
16909   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16910       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16911     assert(MemVT != RegVT && "Cannot extend to the same type");
16912     assert(MemVT.isVector() && "Must load a vector from memory");
16913
16914     unsigned NumElems = RegVT.getVectorNumElements();
16915     unsigned MemSz = MemVT.getSizeInBits();
16916     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16917
16918     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16919       return SDValue();
16920
16921     // All sizes must be a power of two.
16922     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16923       return SDValue();
16924
16925     // Attempt to load the original value using scalar loads.
16926     // Find the largest scalar type that divides the total loaded size.
16927     MVT SclrLoadTy = MVT::i8;
16928     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16929          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16930       MVT Tp = (MVT::SimpleValueType)tp;
16931       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16932         SclrLoadTy = Tp;
16933       }
16934     }
16935
16936     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16937     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16938         (64 <= MemSz))
16939       SclrLoadTy = MVT::f64;
16940
16941     // Calculate the number of scalar loads that we need to perform
16942     // in order to load our vector from memory.
16943     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16944     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16945       return SDValue();
16946
16947     unsigned loadRegZize = RegSz;
16948     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16949       loadRegZize /= 2;
16950
16951     // Represent our vector as a sequence of elements which are the
16952     // largest scalar that we can load.
16953     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16954       loadRegZize/SclrLoadTy.getSizeInBits());
16955
16956     // Represent the data using the same element type that is stored in
16957     // memory. In practice, we ''widen'' MemVT.
16958     EVT WideVecVT =
16959           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16960                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16961
16962     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16963       "Invalid vector type");
16964
16965     // We can't shuffle using an illegal type.
16966     if (!TLI.isTypeLegal(WideVecVT))
16967       return SDValue();
16968
16969     SmallVector<SDValue, 8> Chains;
16970     SDValue Ptr = Ld->getBasePtr();
16971     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16972                                         TLI.getPointerTy());
16973     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16974
16975     for (unsigned i = 0; i < NumLoads; ++i) {
16976       // Perform a single load.
16977       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16978                                        Ptr, Ld->getPointerInfo(),
16979                                        Ld->isVolatile(), Ld->isNonTemporal(),
16980                                        Ld->isInvariant(), Ld->getAlignment());
16981       Chains.push_back(ScalarLoad.getValue(1));
16982       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16983       // another round of DAGCombining.
16984       if (i == 0)
16985         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16986       else
16987         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16988                           ScalarLoad, DAG.getIntPtrConstant(i));
16989
16990       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16991     }
16992
16993     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16994                                Chains.size());
16995
16996     // Bitcast the loaded value to a vector of the original element type, in
16997     // the size of the target vector type.
16998     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16999     unsigned SizeRatio = RegSz/MemSz;
17000
17001     if (Ext == ISD::SEXTLOAD) {
17002       // If we have SSE4.1 we can directly emit a VSEXT node.
17003       if (Subtarget->hasSSE41()) {
17004         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
17005         return DCI.CombineTo(N, Sext, TF, true);
17006       }
17007
17008       // Otherwise we'll shuffle the small elements in the high bits of the
17009       // larger type and perform an arithmetic shift. If the shift is not legal
17010       // it's better to scalarize.
17011       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
17012         return SDValue();
17013
17014       // Redistribute the loaded elements into the different locations.
17015       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17016       for (unsigned i = 0; i != NumElems; ++i)
17017         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
17018
17019       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17020                                            DAG.getUNDEF(WideVecVT),
17021                                            &ShuffleVec[0]);
17022
17023       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17024
17025       // Build the arithmetic shift.
17026       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
17027                      MemVT.getVectorElementType().getSizeInBits();
17028       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
17029                           DAG.getConstant(Amt, RegVT));
17030
17031       return DCI.CombineTo(N, Shuff, TF, true);
17032     }
17033
17034     // Redistribute the loaded elements into the different locations.
17035     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17036     for (unsigned i = 0; i != NumElems; ++i)
17037       ShuffleVec[i*SizeRatio] = i;
17038
17039     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
17040                                          DAG.getUNDEF(WideVecVT),
17041                                          &ShuffleVec[0]);
17042
17043     // Bitcast to the requested type.
17044     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
17045     // Replace the original load with the new sequence
17046     // and return the new chain.
17047     return DCI.CombineTo(N, Shuff, TF, true);
17048   }
17049
17050   return SDValue();
17051 }
17052
17053 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
17054 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
17055                                    const X86Subtarget *Subtarget) {
17056   StoreSDNode *St = cast<StoreSDNode>(N);
17057   EVT VT = St->getValue().getValueType();
17058   EVT StVT = St->getMemoryVT();
17059   SDLoc dl(St);
17060   SDValue StoredVal = St->getOperand(1);
17061   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17062
17063   // If we are saving a concatenation of two XMM registers, perform two stores.
17064   // On Sandy Bridge, 256-bit memory operations are executed by two
17065   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17066   // memory  operation.
17067   unsigned Alignment = St->getAlignment();
17068   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17069   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17070       StVT == VT && !IsAligned) {
17071     unsigned NumElems = VT.getVectorNumElements();
17072     if (NumElems < 2)
17073       return SDValue();
17074
17075     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17076     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17077
17078     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17079     SDValue Ptr0 = St->getBasePtr();
17080     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17081
17082     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17083                                 St->getPointerInfo(), St->isVolatile(),
17084                                 St->isNonTemporal(), Alignment);
17085     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17086                                 St->getPointerInfo(), St->isVolatile(),
17087                                 St->isNonTemporal(),
17088                                 std::min(16U, Alignment));
17089     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17090   }
17091
17092   // Optimize trunc store (of multiple scalars) to shuffle and store.
17093   // First, pack all of the elements in one place. Next, store to memory
17094   // in fewer chunks.
17095   if (St->isTruncatingStore() && VT.isVector()) {
17096     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17097     unsigned NumElems = VT.getVectorNumElements();
17098     assert(StVT != VT && "Cannot truncate to the same type");
17099     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17100     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17101
17102     // From, To sizes and ElemCount must be pow of two
17103     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17104     // We are going to use the original vector elt for storing.
17105     // Accumulated smaller vector elements must be a multiple of the store size.
17106     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17107
17108     unsigned SizeRatio  = FromSz / ToSz;
17109
17110     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17111
17112     // Create a type on which we perform the shuffle
17113     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17114             StVT.getScalarType(), NumElems*SizeRatio);
17115
17116     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17117
17118     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17119     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17120     for (unsigned i = 0; i != NumElems; ++i)
17121       ShuffleVec[i] = i * SizeRatio;
17122
17123     // Can't shuffle using an illegal type.
17124     if (!TLI.isTypeLegal(WideVecVT))
17125       return SDValue();
17126
17127     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17128                                          DAG.getUNDEF(WideVecVT),
17129                                          &ShuffleVec[0]);
17130     // At this point all of the data is stored at the bottom of the
17131     // register. We now need to save it to mem.
17132
17133     // Find the largest store unit
17134     MVT StoreType = MVT::i8;
17135     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17136          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17137       MVT Tp = (MVT::SimpleValueType)tp;
17138       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17139         StoreType = Tp;
17140     }
17141
17142     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17143     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17144         (64 <= NumElems * ToSz))
17145       StoreType = MVT::f64;
17146
17147     // Bitcast the original vector into a vector of store-size units
17148     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17149             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17150     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17151     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17152     SmallVector<SDValue, 8> Chains;
17153     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17154                                         TLI.getPointerTy());
17155     SDValue Ptr = St->getBasePtr();
17156
17157     // Perform one or more big stores into memory.
17158     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17159       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17160                                    StoreType, ShuffWide,
17161                                    DAG.getIntPtrConstant(i));
17162       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17163                                 St->getPointerInfo(), St->isVolatile(),
17164                                 St->isNonTemporal(), St->getAlignment());
17165       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17166       Chains.push_back(Ch);
17167     }
17168
17169     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17170                                Chains.size());
17171   }
17172
17173   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17174   // the FP state in cases where an emms may be missing.
17175   // A preferable solution to the general problem is to figure out the right
17176   // places to insert EMMS.  This qualifies as a quick hack.
17177
17178   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17179   if (VT.getSizeInBits() != 64)
17180     return SDValue();
17181
17182   const Function *F = DAG.getMachineFunction().getFunction();
17183   bool NoImplicitFloatOps = F->getAttributes().
17184     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17185   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17186                      && Subtarget->hasSSE2();
17187   if ((VT.isVector() ||
17188        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17189       isa<LoadSDNode>(St->getValue()) &&
17190       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17191       St->getChain().hasOneUse() && !St->isVolatile()) {
17192     SDNode* LdVal = St->getValue().getNode();
17193     LoadSDNode *Ld = 0;
17194     int TokenFactorIndex = -1;
17195     SmallVector<SDValue, 8> Ops;
17196     SDNode* ChainVal = St->getChain().getNode();
17197     // Must be a store of a load.  We currently handle two cases:  the load
17198     // is a direct child, and it's under an intervening TokenFactor.  It is
17199     // possible to dig deeper under nested TokenFactors.
17200     if (ChainVal == LdVal)
17201       Ld = cast<LoadSDNode>(St->getChain());
17202     else if (St->getValue().hasOneUse() &&
17203              ChainVal->getOpcode() == ISD::TokenFactor) {
17204       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17205         if (ChainVal->getOperand(i).getNode() == LdVal) {
17206           TokenFactorIndex = i;
17207           Ld = cast<LoadSDNode>(St->getValue());
17208         } else
17209           Ops.push_back(ChainVal->getOperand(i));
17210       }
17211     }
17212
17213     if (!Ld || !ISD::isNormalLoad(Ld))
17214       return SDValue();
17215
17216     // If this is not the MMX case, i.e. we are just turning i64 load/store
17217     // into f64 load/store, avoid the transformation if there are multiple
17218     // uses of the loaded value.
17219     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17220       return SDValue();
17221
17222     SDLoc LdDL(Ld);
17223     SDLoc StDL(N);
17224     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17225     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17226     // pair instead.
17227     if (Subtarget->is64Bit() || F64IsLegal) {
17228       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17229       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17230                                   Ld->getPointerInfo(), Ld->isVolatile(),
17231                                   Ld->isNonTemporal(), Ld->isInvariant(),
17232                                   Ld->getAlignment());
17233       SDValue NewChain = NewLd.getValue(1);
17234       if (TokenFactorIndex != -1) {
17235         Ops.push_back(NewChain);
17236         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17237                                Ops.size());
17238       }
17239       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17240                           St->getPointerInfo(),
17241                           St->isVolatile(), St->isNonTemporal(),
17242                           St->getAlignment());
17243     }
17244
17245     // Otherwise, lower to two pairs of 32-bit loads / stores.
17246     SDValue LoAddr = Ld->getBasePtr();
17247     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17248                                  DAG.getConstant(4, MVT::i32));
17249
17250     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17251                                Ld->getPointerInfo(),
17252                                Ld->isVolatile(), Ld->isNonTemporal(),
17253                                Ld->isInvariant(), Ld->getAlignment());
17254     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17255                                Ld->getPointerInfo().getWithOffset(4),
17256                                Ld->isVolatile(), Ld->isNonTemporal(),
17257                                Ld->isInvariant(),
17258                                MinAlign(Ld->getAlignment(), 4));
17259
17260     SDValue NewChain = LoLd.getValue(1);
17261     if (TokenFactorIndex != -1) {
17262       Ops.push_back(LoLd);
17263       Ops.push_back(HiLd);
17264       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17265                              Ops.size());
17266     }
17267
17268     LoAddr = St->getBasePtr();
17269     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17270                          DAG.getConstant(4, MVT::i32));
17271
17272     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17273                                 St->getPointerInfo(),
17274                                 St->isVolatile(), St->isNonTemporal(),
17275                                 St->getAlignment());
17276     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17277                                 St->getPointerInfo().getWithOffset(4),
17278                                 St->isVolatile(),
17279                                 St->isNonTemporal(),
17280                                 MinAlign(St->getAlignment(), 4));
17281     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17282   }
17283   return SDValue();
17284 }
17285
17286 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17287 /// and return the operands for the horizontal operation in LHS and RHS.  A
17288 /// horizontal operation performs the binary operation on successive elements
17289 /// of its first operand, then on successive elements of its second operand,
17290 /// returning the resulting values in a vector.  For example, if
17291 ///   A = < float a0, float a1, float a2, float a3 >
17292 /// and
17293 ///   B = < float b0, float b1, float b2, float b3 >
17294 /// then the result of doing a horizontal operation on A and B is
17295 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17296 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17297 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17298 /// set to A, RHS to B, and the routine returns 'true'.
17299 /// Note that the binary operation should have the property that if one of the
17300 /// operands is UNDEF then the result is UNDEF.
17301 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17302   // Look for the following pattern: if
17303   //   A = < float a0, float a1, float a2, float a3 >
17304   //   B = < float b0, float b1, float b2, float b3 >
17305   // and
17306   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17307   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17308   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17309   // which is A horizontal-op B.
17310
17311   // At least one of the operands should be a vector shuffle.
17312   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17313       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17314     return false;
17315
17316   EVT VT = LHS.getValueType();
17317
17318   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17319          "Unsupported vector type for horizontal add/sub");
17320
17321   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17322   // operate independently on 128-bit lanes.
17323   unsigned NumElts = VT.getVectorNumElements();
17324   unsigned NumLanes = VT.getSizeInBits()/128;
17325   unsigned NumLaneElts = NumElts / NumLanes;
17326   assert((NumLaneElts % 2 == 0) &&
17327          "Vector type should have an even number of elements in each lane");
17328   unsigned HalfLaneElts = NumLaneElts/2;
17329
17330   // View LHS in the form
17331   //   LHS = VECTOR_SHUFFLE A, B, LMask
17332   // If LHS is not a shuffle then pretend it is the shuffle
17333   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17334   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17335   // type VT.
17336   SDValue A, B;
17337   SmallVector<int, 16> LMask(NumElts);
17338   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17339     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17340       A = LHS.getOperand(0);
17341     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17342       B = LHS.getOperand(1);
17343     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17344     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17345   } else {
17346     if (LHS.getOpcode() != ISD::UNDEF)
17347       A = LHS;
17348     for (unsigned i = 0; i != NumElts; ++i)
17349       LMask[i] = i;
17350   }
17351
17352   // Likewise, view RHS in the form
17353   //   RHS = VECTOR_SHUFFLE C, D, RMask
17354   SDValue C, D;
17355   SmallVector<int, 16> RMask(NumElts);
17356   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17357     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17358       C = RHS.getOperand(0);
17359     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17360       D = RHS.getOperand(1);
17361     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17362     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17363   } else {
17364     if (RHS.getOpcode() != ISD::UNDEF)
17365       C = RHS;
17366     for (unsigned i = 0; i != NumElts; ++i)
17367       RMask[i] = i;
17368   }
17369
17370   // Check that the shuffles are both shuffling the same vectors.
17371   if (!(A == C && B == D) && !(A == D && B == C))
17372     return false;
17373
17374   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17375   if (!A.getNode() && !B.getNode())
17376     return false;
17377
17378   // If A and B occur in reverse order in RHS, then "swap" them (which means
17379   // rewriting the mask).
17380   if (A != C)
17381     CommuteVectorShuffleMask(RMask, NumElts);
17382
17383   // At this point LHS and RHS are equivalent to
17384   //   LHS = VECTOR_SHUFFLE A, B, LMask
17385   //   RHS = VECTOR_SHUFFLE A, B, RMask
17386   // Check that the masks correspond to performing a horizontal operation.
17387   for (unsigned i = 0; i != NumElts; ++i) {
17388     int LIdx = LMask[i], RIdx = RMask[i];
17389
17390     // Ignore any UNDEF components.
17391     if (LIdx < 0 || RIdx < 0 ||
17392         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17393         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17394       continue;
17395
17396     // Check that successive elements are being operated on.  If not, this is
17397     // not a horizontal operation.
17398     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17399     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17400     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17401     if (!(LIdx == Index && RIdx == Index + 1) &&
17402         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17403       return false;
17404   }
17405
17406   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17407   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17408   return true;
17409 }
17410
17411 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17412 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17413                                   const X86Subtarget *Subtarget) {
17414   EVT VT = N->getValueType(0);
17415   SDValue LHS = N->getOperand(0);
17416   SDValue RHS = N->getOperand(1);
17417
17418   // Try to synthesize horizontal adds from adds of shuffles.
17419   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17420        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17421       isHorizontalBinOp(LHS, RHS, true))
17422     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17423   return SDValue();
17424 }
17425
17426 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17427 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17428                                   const X86Subtarget *Subtarget) {
17429   EVT VT = N->getValueType(0);
17430   SDValue LHS = N->getOperand(0);
17431   SDValue RHS = N->getOperand(1);
17432
17433   // Try to synthesize horizontal subs from subs of shuffles.
17434   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17435        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17436       isHorizontalBinOp(LHS, RHS, false))
17437     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17438   return SDValue();
17439 }
17440
17441 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17442 /// X86ISD::FXOR nodes.
17443 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17444   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17445   // F[X]OR(0.0, x) -> x
17446   // F[X]OR(x, 0.0) -> x
17447   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17448     if (C->getValueAPF().isPosZero())
17449       return N->getOperand(1);
17450   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17451     if (C->getValueAPF().isPosZero())
17452       return N->getOperand(0);
17453   return SDValue();
17454 }
17455
17456 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17457 /// X86ISD::FMAX nodes.
17458 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17459   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17460
17461   // Only perform optimizations if UnsafeMath is used.
17462   if (!DAG.getTarget().Options.UnsafeFPMath)
17463     return SDValue();
17464
17465   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17466   // into FMINC and FMAXC, which are Commutative operations.
17467   unsigned NewOp = 0;
17468   switch (N->getOpcode()) {
17469     default: llvm_unreachable("unknown opcode");
17470     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17471     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17472   }
17473
17474   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
17475                      N->getOperand(0), N->getOperand(1));
17476 }
17477
17478 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17479 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17480   // FAND(0.0, x) -> 0.0
17481   // FAND(x, 0.0) -> 0.0
17482   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17483     if (C->getValueAPF().isPosZero())
17484       return N->getOperand(0);
17485   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17486     if (C->getValueAPF().isPosZero())
17487       return N->getOperand(1);
17488   return SDValue();
17489 }
17490
17491 static SDValue PerformBTCombine(SDNode *N,
17492                                 SelectionDAG &DAG,
17493                                 TargetLowering::DAGCombinerInfo &DCI) {
17494   // BT ignores high bits in the bit index operand.
17495   SDValue Op1 = N->getOperand(1);
17496   if (Op1.hasOneUse()) {
17497     unsigned BitWidth = Op1.getValueSizeInBits();
17498     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17499     APInt KnownZero, KnownOne;
17500     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17501                                           !DCI.isBeforeLegalizeOps());
17502     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17503     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17504         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17505       DCI.CommitTargetLoweringOpt(TLO);
17506   }
17507   return SDValue();
17508 }
17509
17510 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17511   SDValue Op = N->getOperand(0);
17512   if (Op.getOpcode() == ISD::BITCAST)
17513     Op = Op.getOperand(0);
17514   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17515   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17516       VT.getVectorElementType().getSizeInBits() ==
17517       OpVT.getVectorElementType().getSizeInBits()) {
17518     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
17519   }
17520   return SDValue();
17521 }
17522
17523 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17524                                                const X86Subtarget *Subtarget) {
17525   EVT VT = N->getValueType(0);
17526   if (!VT.isVector())
17527     return SDValue();
17528
17529   SDValue N0 = N->getOperand(0);
17530   SDValue N1 = N->getOperand(1);
17531   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17532   SDLoc dl(N);
17533
17534   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17535   // both SSE and AVX2 since there is no sign-extended shift right
17536   // operation on a vector with 64-bit elements.
17537   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17538   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17539   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17540       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17541     SDValue N00 = N0.getOperand(0);
17542
17543     // EXTLOAD has a better solution on AVX2,
17544     // it may be replaced with X86ISD::VSEXT node.
17545     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17546       if (!ISD::isNormalLoad(N00.getNode()))
17547         return SDValue();
17548
17549     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17550         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17551                                   N00, N1);
17552       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17553     }
17554   }
17555   return SDValue();
17556 }
17557
17558 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17559                                   TargetLowering::DAGCombinerInfo &DCI,
17560                                   const X86Subtarget *Subtarget) {
17561   if (!DCI.isBeforeLegalizeOps())
17562     return SDValue();
17563
17564   if (!Subtarget->hasFp256())
17565     return SDValue();
17566
17567   EVT VT = N->getValueType(0);
17568   if (VT.isVector() && VT.getSizeInBits() == 256) {
17569     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17570     if (R.getNode())
17571       return R;
17572   }
17573
17574   return SDValue();
17575 }
17576
17577 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17578                                  const X86Subtarget* Subtarget) {
17579   SDLoc dl(N);
17580   EVT VT = N->getValueType(0);
17581
17582   // Let legalize expand this if it isn't a legal type yet.
17583   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17584     return SDValue();
17585
17586   EVT ScalarVT = VT.getScalarType();
17587   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17588       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17589     return SDValue();
17590
17591   SDValue A = N->getOperand(0);
17592   SDValue B = N->getOperand(1);
17593   SDValue C = N->getOperand(2);
17594
17595   bool NegA = (A.getOpcode() == ISD::FNEG);
17596   bool NegB = (B.getOpcode() == ISD::FNEG);
17597   bool NegC = (C.getOpcode() == ISD::FNEG);
17598
17599   // Negative multiplication when NegA xor NegB
17600   bool NegMul = (NegA != NegB);
17601   if (NegA)
17602     A = A.getOperand(0);
17603   if (NegB)
17604     B = B.getOperand(0);
17605   if (NegC)
17606     C = C.getOperand(0);
17607
17608   unsigned Opcode;
17609   if (!NegMul)
17610     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17611   else
17612     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17613
17614   return DAG.getNode(Opcode, dl, VT, A, B, C);
17615 }
17616
17617 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17618                                   TargetLowering::DAGCombinerInfo &DCI,
17619                                   const X86Subtarget *Subtarget) {
17620   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17621   //           (and (i32 x86isd::setcc_carry), 1)
17622   // This eliminates the zext. This transformation is necessary because
17623   // ISD::SETCC is always legalized to i8.
17624   SDLoc dl(N);
17625   SDValue N0 = N->getOperand(0);
17626   EVT VT = N->getValueType(0);
17627
17628   if (N0.getOpcode() == ISD::AND &&
17629       N0.hasOneUse() &&
17630       N0.getOperand(0).hasOneUse()) {
17631     SDValue N00 = N0.getOperand(0);
17632     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17633       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17634       if (!C || C->getZExtValue() != 1)
17635         return SDValue();
17636       return DAG.getNode(ISD::AND, dl, VT,
17637                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17638                                      N00.getOperand(0), N00.getOperand(1)),
17639                          DAG.getConstant(1, VT));
17640     }
17641   }
17642
17643   if (VT.is256BitVector()) {
17644     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17645     if (R.getNode())
17646       return R;
17647   }
17648
17649   return SDValue();
17650 }
17651
17652 // Optimize x == -y --> x+y == 0
17653 //          x != -y --> x+y != 0
17654 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17655   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17656   SDValue LHS = N->getOperand(0);
17657   SDValue RHS = N->getOperand(1);
17658
17659   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17660     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17661       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17662         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17663                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17664         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17665                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17666       }
17667   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17668     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17669       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17670         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17671                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17672         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17673                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17674       }
17675   return SDValue();
17676 }
17677
17678 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17679 // as "sbb reg,reg", since it can be extended without zext and produces
17680 // an all-ones bit which is more useful than 0/1 in some cases.
17681 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17682   return DAG.getNode(ISD::AND, DL, MVT::i8,
17683                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17684                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17685                      DAG.getConstant(1, MVT::i8));
17686 }
17687
17688 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17689 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17690                                    TargetLowering::DAGCombinerInfo &DCI,
17691                                    const X86Subtarget *Subtarget) {
17692   SDLoc DL(N);
17693   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17694   SDValue EFLAGS = N->getOperand(1);
17695
17696   if (CC == X86::COND_A) {
17697     // Try to convert COND_A into COND_B in an attempt to facilitate
17698     // materializing "setb reg".
17699     //
17700     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17701     // cannot take an immediate as its first operand.
17702     //
17703     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17704         EFLAGS.getValueType().isInteger() &&
17705         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17706       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
17707                                    EFLAGS.getNode()->getVTList(),
17708                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17709       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17710       return MaterializeSETB(DL, NewEFLAGS, DAG);
17711     }
17712   }
17713
17714   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17715   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17716   // cases.
17717   if (CC == X86::COND_B)
17718     return MaterializeSETB(DL, EFLAGS, DAG);
17719
17720   SDValue Flags;
17721
17722   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17723   if (Flags.getNode()) {
17724     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17725     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17726   }
17727
17728   return SDValue();
17729 }
17730
17731 // Optimize branch condition evaluation.
17732 //
17733 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17734                                     TargetLowering::DAGCombinerInfo &DCI,
17735                                     const X86Subtarget *Subtarget) {
17736   SDLoc DL(N);
17737   SDValue Chain = N->getOperand(0);
17738   SDValue Dest = N->getOperand(1);
17739   SDValue EFLAGS = N->getOperand(3);
17740   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17741
17742   SDValue Flags;
17743
17744   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17745   if (Flags.getNode()) {
17746     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17747     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17748                        Flags);
17749   }
17750
17751   return SDValue();
17752 }
17753
17754 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17755                                         const X86TargetLowering *XTLI) {
17756   SDValue Op0 = N->getOperand(0);
17757   EVT InVT = Op0->getValueType(0);
17758
17759   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17760   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17761     SDLoc dl(N);
17762     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17763     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17764     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17765   }
17766
17767   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17768   // a 32-bit target where SSE doesn't support i64->FP operations.
17769   if (Op0.getOpcode() == ISD::LOAD) {
17770     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17771     EVT VT = Ld->getValueType(0);
17772     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17773         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17774         !XTLI->getSubtarget()->is64Bit() &&
17775         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17776       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17777                                           Ld->getChain(), Op0, DAG);
17778       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17779       return FILDChain;
17780     }
17781   }
17782   return SDValue();
17783 }
17784
17785 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17786 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17787                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17788   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17789   // the result is either zero or one (depending on the input carry bit).
17790   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17791   if (X86::isZeroNode(N->getOperand(0)) &&
17792       X86::isZeroNode(N->getOperand(1)) &&
17793       // We don't have a good way to replace an EFLAGS use, so only do this when
17794       // dead right now.
17795       SDValue(N, 1).use_empty()) {
17796     SDLoc DL(N);
17797     EVT VT = N->getValueType(0);
17798     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17799     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17800                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17801                                            DAG.getConstant(X86::COND_B,MVT::i8),
17802                                            N->getOperand(2)),
17803                                DAG.getConstant(1, VT));
17804     return DCI.CombineTo(N, Res1, CarryOut);
17805   }
17806
17807   return SDValue();
17808 }
17809
17810 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17811 //      (add Y, (setne X, 0)) -> sbb -1, Y
17812 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17813 //      (sub (setne X, 0), Y) -> adc -1, Y
17814 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17815   SDLoc DL(N);
17816
17817   // Look through ZExts.
17818   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17819   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17820     return SDValue();
17821
17822   SDValue SetCC = Ext.getOperand(0);
17823   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17824     return SDValue();
17825
17826   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17827   if (CC != X86::COND_E && CC != X86::COND_NE)
17828     return SDValue();
17829
17830   SDValue Cmp = SetCC.getOperand(1);
17831   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17832       !X86::isZeroNode(Cmp.getOperand(1)) ||
17833       !Cmp.getOperand(0).getValueType().isInteger())
17834     return SDValue();
17835
17836   SDValue CmpOp0 = Cmp.getOperand(0);
17837   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17838                                DAG.getConstant(1, CmpOp0.getValueType()));
17839
17840   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17841   if (CC == X86::COND_NE)
17842     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17843                        DL, OtherVal.getValueType(), OtherVal,
17844                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17845   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17846                      DL, OtherVal.getValueType(), OtherVal,
17847                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17848 }
17849
17850 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17851 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17852                                  const X86Subtarget *Subtarget) {
17853   EVT VT = N->getValueType(0);
17854   SDValue Op0 = N->getOperand(0);
17855   SDValue Op1 = N->getOperand(1);
17856
17857   // Try to synthesize horizontal adds from adds of shuffles.
17858   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17859        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17860       isHorizontalBinOp(Op0, Op1, true))
17861     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
17862
17863   return OptimizeConditionalInDecrement(N, DAG);
17864 }
17865
17866 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17867                                  const X86Subtarget *Subtarget) {
17868   SDValue Op0 = N->getOperand(0);
17869   SDValue Op1 = N->getOperand(1);
17870
17871   // X86 can't encode an immediate LHS of a sub. See if we can push the
17872   // negation into a preceding instruction.
17873   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17874     // If the RHS of the sub is a XOR with one use and a constant, invert the
17875     // immediate. Then add one to the LHS of the sub so we can turn
17876     // X-Y -> X+~Y+1, saving one register.
17877     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17878         isa<ConstantSDNode>(Op1.getOperand(1))) {
17879       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17880       EVT VT = Op0.getValueType();
17881       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
17882                                    Op1.getOperand(0),
17883                                    DAG.getConstant(~XorC, VT));
17884       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
17885                          DAG.getConstant(C->getAPIntValue()+1, VT));
17886     }
17887   }
17888
17889   // Try to synthesize horizontal adds from adds of shuffles.
17890   EVT VT = N->getValueType(0);
17891   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17892        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17893       isHorizontalBinOp(Op0, Op1, true))
17894     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
17895
17896   return OptimizeConditionalInDecrement(N, DAG);
17897 }
17898
17899 /// performVZEXTCombine - Performs build vector combines
17900 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17901                                         TargetLowering::DAGCombinerInfo &DCI,
17902                                         const X86Subtarget *Subtarget) {
17903   // (vzext (bitcast (vzext (x)) -> (vzext x)
17904   SDValue In = N->getOperand(0);
17905   while (In.getOpcode() == ISD::BITCAST)
17906     In = In.getOperand(0);
17907
17908   if (In.getOpcode() != X86ISD::VZEXT)
17909     return SDValue();
17910
17911   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
17912                      In.getOperand(0));
17913 }
17914
17915 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17916                                              DAGCombinerInfo &DCI) const {
17917   SelectionDAG &DAG = DCI.DAG;
17918   switch (N->getOpcode()) {
17919   default: break;
17920   case ISD::EXTRACT_VECTOR_ELT:
17921     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17922   case ISD::VSELECT:
17923   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17924   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17925   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17926   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17927   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17928   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17929   case ISD::SHL:
17930   case ISD::SRA:
17931   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17932   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17933   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17934   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17935   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17936   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17937   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17938   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17939   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17940   case X86ISD::FXOR:
17941   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17942   case X86ISD::FMIN:
17943   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17944   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17945   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17946   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17947   case ISD::ANY_EXTEND:
17948   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17949   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17950   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17951   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17952   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17953   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17954   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17955   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17956   case X86ISD::SHUFP:       // Handle all target specific shuffles
17957   case X86ISD::PALIGNR:
17958   case X86ISD::UNPCKH:
17959   case X86ISD::UNPCKL:
17960   case X86ISD::MOVHLPS:
17961   case X86ISD::MOVLHPS:
17962   case X86ISD::PSHUFD:
17963   case X86ISD::PSHUFHW:
17964   case X86ISD::PSHUFLW:
17965   case X86ISD::MOVSS:
17966   case X86ISD::MOVSD:
17967   case X86ISD::VPERMILP:
17968   case X86ISD::VPERM2X128:
17969   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17970   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17971   }
17972
17973   return SDValue();
17974 }
17975
17976 /// isTypeDesirableForOp - Return true if the target has native support for
17977 /// the specified value type and it is 'desirable' to use the type for the
17978 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17979 /// instruction encodings are longer and some i16 instructions are slow.
17980 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17981   if (!isTypeLegal(VT))
17982     return false;
17983   if (VT != MVT::i16)
17984     return true;
17985
17986   switch (Opc) {
17987   default:
17988     return true;
17989   case ISD::LOAD:
17990   case ISD::SIGN_EXTEND:
17991   case ISD::ZERO_EXTEND:
17992   case ISD::ANY_EXTEND:
17993   case ISD::SHL:
17994   case ISD::SRL:
17995   case ISD::SUB:
17996   case ISD::ADD:
17997   case ISD::MUL:
17998   case ISD::AND:
17999   case ISD::OR:
18000   case ISD::XOR:
18001     return false;
18002   }
18003 }
18004
18005 /// IsDesirableToPromoteOp - This method query the target whether it is
18006 /// beneficial for dag combiner to promote the specified node. If true, it
18007 /// should return the desired promotion type by reference.
18008 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
18009   EVT VT = Op.getValueType();
18010   if (VT != MVT::i16)
18011     return false;
18012
18013   bool Promote = false;
18014   bool Commute = false;
18015   switch (Op.getOpcode()) {
18016   default: break;
18017   case ISD::LOAD: {
18018     LoadSDNode *LD = cast<LoadSDNode>(Op);
18019     // If the non-extending load has a single use and it's not live out, then it
18020     // might be folded.
18021     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
18022                                                      Op.hasOneUse()*/) {
18023       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
18024              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
18025         // The only case where we'd want to promote LOAD (rather then it being
18026         // promoted as an operand is when it's only use is liveout.
18027         if (UI->getOpcode() != ISD::CopyToReg)
18028           return false;
18029       }
18030     }
18031     Promote = true;
18032     break;
18033   }
18034   case ISD::SIGN_EXTEND:
18035   case ISD::ZERO_EXTEND:
18036   case ISD::ANY_EXTEND:
18037     Promote = true;
18038     break;
18039   case ISD::SHL:
18040   case ISD::SRL: {
18041     SDValue N0 = Op.getOperand(0);
18042     // Look out for (store (shl (load), x)).
18043     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
18044       return false;
18045     Promote = true;
18046     break;
18047   }
18048   case ISD::ADD:
18049   case ISD::MUL:
18050   case ISD::AND:
18051   case ISD::OR:
18052   case ISD::XOR:
18053     Commute = true;
18054     // fallthrough
18055   case ISD::SUB: {
18056     SDValue N0 = Op.getOperand(0);
18057     SDValue N1 = Op.getOperand(1);
18058     if (!Commute && MayFoldLoad(N1))
18059       return false;
18060     // Avoid disabling potential load folding opportunities.
18061     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18062       return false;
18063     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18064       return false;
18065     Promote = true;
18066   }
18067   }
18068
18069   PVT = MVT::i32;
18070   return Promote;
18071 }
18072
18073 //===----------------------------------------------------------------------===//
18074 //                           X86 Inline Assembly Support
18075 //===----------------------------------------------------------------------===//
18076
18077 namespace {
18078   // Helper to match a string separated by whitespace.
18079   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18080     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18081
18082     for (unsigned i = 0, e = args.size(); i != e; ++i) {
18083       StringRef piece(*args[i]);
18084       if (!s.startswith(piece)) // Check if the piece matches.
18085         return false;
18086
18087       s = s.substr(piece.size());
18088       StringRef::size_type pos = s.find_first_not_of(" \t");
18089       if (pos == 0) // We matched a prefix.
18090         return false;
18091
18092       s = s.substr(pos);
18093     }
18094
18095     return s.empty();
18096   }
18097   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18098 }
18099
18100 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18101   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18102
18103   std::string AsmStr = IA->getAsmString();
18104
18105   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18106   if (!Ty || Ty->getBitWidth() % 16 != 0)
18107     return false;
18108
18109   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18110   SmallVector<StringRef, 4> AsmPieces;
18111   SplitString(AsmStr, AsmPieces, ";\n");
18112
18113   switch (AsmPieces.size()) {
18114   default: return false;
18115   case 1:
18116     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18117     // we will turn this bswap into something that will be lowered to logical
18118     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18119     // lower so don't worry about this.
18120     // bswap $0
18121     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18122         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18123         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18124         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18125         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18126         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18127       // No need to check constraints, nothing other than the equivalent of
18128       // "=r,0" would be valid here.
18129       return IntrinsicLowering::LowerToByteSwap(CI);
18130     }
18131
18132     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18133     if (CI->getType()->isIntegerTy(16) &&
18134         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18135         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18136          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18137       AsmPieces.clear();
18138       const std::string &ConstraintsStr = IA->getConstraintString();
18139       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18140       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18141       if (AsmPieces.size() == 4 &&
18142           AsmPieces[0] == "~{cc}" &&
18143           AsmPieces[1] == "~{dirflag}" &&
18144           AsmPieces[2] == "~{flags}" &&
18145           AsmPieces[3] == "~{fpsr}")
18146       return IntrinsicLowering::LowerToByteSwap(CI);
18147     }
18148     break;
18149   case 3:
18150     if (CI->getType()->isIntegerTy(32) &&
18151         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18152         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18153         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18154         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18155       AsmPieces.clear();
18156       const std::string &ConstraintsStr = IA->getConstraintString();
18157       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18158       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18159       if (AsmPieces.size() == 4 &&
18160           AsmPieces[0] == "~{cc}" &&
18161           AsmPieces[1] == "~{dirflag}" &&
18162           AsmPieces[2] == "~{flags}" &&
18163           AsmPieces[3] == "~{fpsr}")
18164         return IntrinsicLowering::LowerToByteSwap(CI);
18165     }
18166
18167     if (CI->getType()->isIntegerTy(64)) {
18168       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18169       if (Constraints.size() >= 2 &&
18170           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18171           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18172         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18173         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18174             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18175             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18176           return IntrinsicLowering::LowerToByteSwap(CI);
18177       }
18178     }
18179     break;
18180   }
18181   return false;
18182 }
18183
18184 /// getConstraintType - Given a constraint letter, return the type of
18185 /// constraint it is for this target.
18186 X86TargetLowering::ConstraintType
18187 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18188   if (Constraint.size() == 1) {
18189     switch (Constraint[0]) {
18190     case 'R':
18191     case 'q':
18192     case 'Q':
18193     case 'f':
18194     case 't':
18195     case 'u':
18196     case 'y':
18197     case 'x':
18198     case 'Y':
18199     case 'l':
18200       return C_RegisterClass;
18201     case 'a':
18202     case 'b':
18203     case 'c':
18204     case 'd':
18205     case 'S':
18206     case 'D':
18207     case 'A':
18208       return C_Register;
18209     case 'I':
18210     case 'J':
18211     case 'K':
18212     case 'L':
18213     case 'M':
18214     case 'N':
18215     case 'G':
18216     case 'C':
18217     case 'e':
18218     case 'Z':
18219       return C_Other;
18220     default:
18221       break;
18222     }
18223   }
18224   return TargetLowering::getConstraintType(Constraint);
18225 }
18226
18227 /// Examine constraint type and operand type and determine a weight value.
18228 /// This object must already have been set up with the operand type
18229 /// and the current alternative constraint selected.
18230 TargetLowering::ConstraintWeight
18231   X86TargetLowering::getSingleConstraintMatchWeight(
18232     AsmOperandInfo &info, const char *constraint) const {
18233   ConstraintWeight weight = CW_Invalid;
18234   Value *CallOperandVal = info.CallOperandVal;
18235     // If we don't have a value, we can't do a match,
18236     // but allow it at the lowest weight.
18237   if (CallOperandVal == NULL)
18238     return CW_Default;
18239   Type *type = CallOperandVal->getType();
18240   // Look at the constraint type.
18241   switch (*constraint) {
18242   default:
18243     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18244   case 'R':
18245   case 'q':
18246   case 'Q':
18247   case 'a':
18248   case 'b':
18249   case 'c':
18250   case 'd':
18251   case 'S':
18252   case 'D':
18253   case 'A':
18254     if (CallOperandVal->getType()->isIntegerTy())
18255       weight = CW_SpecificReg;
18256     break;
18257   case 'f':
18258   case 't':
18259   case 'u':
18260     if (type->isFloatingPointTy())
18261       weight = CW_SpecificReg;
18262     break;
18263   case 'y':
18264     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18265       weight = CW_SpecificReg;
18266     break;
18267   case 'x':
18268   case 'Y':
18269     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18270         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18271       weight = CW_Register;
18272     break;
18273   case 'I':
18274     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18275       if (C->getZExtValue() <= 31)
18276         weight = CW_Constant;
18277     }
18278     break;
18279   case 'J':
18280     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18281       if (C->getZExtValue() <= 63)
18282         weight = CW_Constant;
18283     }
18284     break;
18285   case 'K':
18286     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18287       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18288         weight = CW_Constant;
18289     }
18290     break;
18291   case 'L':
18292     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18293       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18294         weight = CW_Constant;
18295     }
18296     break;
18297   case 'M':
18298     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18299       if (C->getZExtValue() <= 3)
18300         weight = CW_Constant;
18301     }
18302     break;
18303   case 'N':
18304     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18305       if (C->getZExtValue() <= 0xff)
18306         weight = CW_Constant;
18307     }
18308     break;
18309   case 'G':
18310   case 'C':
18311     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18312       weight = CW_Constant;
18313     }
18314     break;
18315   case 'e':
18316     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18317       if ((C->getSExtValue() >= -0x80000000LL) &&
18318           (C->getSExtValue() <= 0x7fffffffLL))
18319         weight = CW_Constant;
18320     }
18321     break;
18322   case 'Z':
18323     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18324       if (C->getZExtValue() <= 0xffffffff)
18325         weight = CW_Constant;
18326     }
18327     break;
18328   }
18329   return weight;
18330 }
18331
18332 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18333 /// with another that has more specific requirements based on the type of the
18334 /// corresponding operand.
18335 const char *X86TargetLowering::
18336 LowerXConstraint(EVT ConstraintVT) const {
18337   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18338   // 'f' like normal targets.
18339   if (ConstraintVT.isFloatingPoint()) {
18340     if (Subtarget->hasSSE2())
18341       return "Y";
18342     if (Subtarget->hasSSE1())
18343       return "x";
18344   }
18345
18346   return TargetLowering::LowerXConstraint(ConstraintVT);
18347 }
18348
18349 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18350 /// vector.  If it is invalid, don't add anything to Ops.
18351 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18352                                                      std::string &Constraint,
18353                                                      std::vector<SDValue>&Ops,
18354                                                      SelectionDAG &DAG) const {
18355   SDValue Result(0, 0);
18356
18357   // Only support length 1 constraints for now.
18358   if (Constraint.length() > 1) return;
18359
18360   char ConstraintLetter = Constraint[0];
18361   switch (ConstraintLetter) {
18362   default: break;
18363   case 'I':
18364     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18365       if (C->getZExtValue() <= 31) {
18366         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18367         break;
18368       }
18369     }
18370     return;
18371   case 'J':
18372     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18373       if (C->getZExtValue() <= 63) {
18374         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18375         break;
18376       }
18377     }
18378     return;
18379   case 'K':
18380     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18381       if (isInt<8>(C->getSExtValue())) {
18382         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18383         break;
18384       }
18385     }
18386     return;
18387   case 'N':
18388     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18389       if (C->getZExtValue() <= 255) {
18390         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18391         break;
18392       }
18393     }
18394     return;
18395   case 'e': {
18396     // 32-bit signed value
18397     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18398       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18399                                            C->getSExtValue())) {
18400         // Widen to 64 bits here to get it sign extended.
18401         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18402         break;
18403       }
18404     // FIXME gcc accepts some relocatable values here too, but only in certain
18405     // memory models; it's complicated.
18406     }
18407     return;
18408   }
18409   case 'Z': {
18410     // 32-bit unsigned value
18411     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18412       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18413                                            C->getZExtValue())) {
18414         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18415         break;
18416       }
18417     }
18418     // FIXME gcc accepts some relocatable values here too, but only in certain
18419     // memory models; it's complicated.
18420     return;
18421   }
18422   case 'i': {
18423     // Literal immediates are always ok.
18424     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18425       // Widen to 64 bits here to get it sign extended.
18426       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18427       break;
18428     }
18429
18430     // In any sort of PIC mode addresses need to be computed at runtime by
18431     // adding in a register or some sort of table lookup.  These can't
18432     // be used as immediates.
18433     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18434       return;
18435
18436     // If we are in non-pic codegen mode, we allow the address of a global (with
18437     // an optional displacement) to be used with 'i'.
18438     GlobalAddressSDNode *GA = 0;
18439     int64_t Offset = 0;
18440
18441     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18442     while (1) {
18443       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18444         Offset += GA->getOffset();
18445         break;
18446       } else if (Op.getOpcode() == ISD::ADD) {
18447         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18448           Offset += C->getZExtValue();
18449           Op = Op.getOperand(0);
18450           continue;
18451         }
18452       } else if (Op.getOpcode() == ISD::SUB) {
18453         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18454           Offset += -C->getZExtValue();
18455           Op = Op.getOperand(0);
18456           continue;
18457         }
18458       }
18459
18460       // Otherwise, this isn't something we can handle, reject it.
18461       return;
18462     }
18463
18464     const GlobalValue *GV = GA->getGlobal();
18465     // If we require an extra load to get this address, as in PIC mode, we
18466     // can't accept it.
18467     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18468                                                         getTargetMachine())))
18469       return;
18470
18471     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
18472                                         GA->getValueType(0), Offset);
18473     break;
18474   }
18475   }
18476
18477   if (Result.getNode()) {
18478     Ops.push_back(Result);
18479     return;
18480   }
18481   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18482 }
18483
18484 std::pair<unsigned, const TargetRegisterClass*>
18485 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18486                                                 MVT VT) const {
18487   // First, see if this is a constraint that directly corresponds to an LLVM
18488   // register class.
18489   if (Constraint.size() == 1) {
18490     // GCC Constraint Letters
18491     switch (Constraint[0]) {
18492     default: break;
18493       // TODO: Slight differences here in allocation order and leaving
18494       // RIP in the class. Do they matter any more here than they do
18495       // in the normal allocation?
18496     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18497       if (Subtarget->is64Bit()) {
18498         if (VT == MVT::i32 || VT == MVT::f32)
18499           return std::make_pair(0U, &X86::GR32RegClass);
18500         if (VT == MVT::i16)
18501           return std::make_pair(0U, &X86::GR16RegClass);
18502         if (VT == MVT::i8 || VT == MVT::i1)
18503           return std::make_pair(0U, &X86::GR8RegClass);
18504         if (VT == MVT::i64 || VT == MVT::f64)
18505           return std::make_pair(0U, &X86::GR64RegClass);
18506         break;
18507       }
18508       // 32-bit fallthrough
18509     case 'Q':   // Q_REGS
18510       if (VT == MVT::i32 || VT == MVT::f32)
18511         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18512       if (VT == MVT::i16)
18513         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18514       if (VT == MVT::i8 || VT == MVT::i1)
18515         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18516       if (VT == MVT::i64)
18517         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18518       break;
18519     case 'r':   // GENERAL_REGS
18520     case 'l':   // INDEX_REGS
18521       if (VT == MVT::i8 || VT == MVT::i1)
18522         return std::make_pair(0U, &X86::GR8RegClass);
18523       if (VT == MVT::i16)
18524         return std::make_pair(0U, &X86::GR16RegClass);
18525       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18526         return std::make_pair(0U, &X86::GR32RegClass);
18527       return std::make_pair(0U, &X86::GR64RegClass);
18528     case 'R':   // LEGACY_REGS
18529       if (VT == MVT::i8 || VT == MVT::i1)
18530         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18531       if (VT == MVT::i16)
18532         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18533       if (VT == MVT::i32 || !Subtarget->is64Bit())
18534         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18535       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18536     case 'f':  // FP Stack registers.
18537       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18538       // value to the correct fpstack register class.
18539       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18540         return std::make_pair(0U, &X86::RFP32RegClass);
18541       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18542         return std::make_pair(0U, &X86::RFP64RegClass);
18543       return std::make_pair(0U, &X86::RFP80RegClass);
18544     case 'y':   // MMX_REGS if MMX allowed.
18545       if (!Subtarget->hasMMX()) break;
18546       return std::make_pair(0U, &X86::VR64RegClass);
18547     case 'Y':   // SSE_REGS if SSE2 allowed
18548       if (!Subtarget->hasSSE2()) break;
18549       // FALL THROUGH.
18550     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18551       if (!Subtarget->hasSSE1()) break;
18552
18553       switch (VT.SimpleTy) {
18554       default: break;
18555       // Scalar SSE types.
18556       case MVT::f32:
18557       case MVT::i32:
18558         return std::make_pair(0U, &X86::FR32RegClass);
18559       case MVT::f64:
18560       case MVT::i64:
18561         return std::make_pair(0U, &X86::FR64RegClass);
18562       // Vector types.
18563       case MVT::v16i8:
18564       case MVT::v8i16:
18565       case MVT::v4i32:
18566       case MVT::v2i64:
18567       case MVT::v4f32:
18568       case MVT::v2f64:
18569         return std::make_pair(0U, &X86::VR128RegClass);
18570       // AVX types.
18571       case MVT::v32i8:
18572       case MVT::v16i16:
18573       case MVT::v8i32:
18574       case MVT::v4i64:
18575       case MVT::v8f32:
18576       case MVT::v4f64:
18577         return std::make_pair(0U, &X86::VR256RegClass);
18578       }
18579       break;
18580     }
18581   }
18582
18583   // Use the default implementation in TargetLowering to convert the register
18584   // constraint into a member of a register class.
18585   std::pair<unsigned, const TargetRegisterClass*> Res;
18586   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18587
18588   // Not found as a standard register?
18589   if (Res.second == 0) {
18590     // Map st(0) -> st(7) -> ST0
18591     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18592         tolower(Constraint[1]) == 's' &&
18593         tolower(Constraint[2]) == 't' &&
18594         Constraint[3] == '(' &&
18595         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18596         Constraint[5] == ')' &&
18597         Constraint[6] == '}') {
18598
18599       Res.first = X86::ST0+Constraint[4]-'0';
18600       Res.second = &X86::RFP80RegClass;
18601       return Res;
18602     }
18603
18604     // GCC allows "st(0)" to be called just plain "st".
18605     if (StringRef("{st}").equals_lower(Constraint)) {
18606       Res.first = X86::ST0;
18607       Res.second = &X86::RFP80RegClass;
18608       return Res;
18609     }
18610
18611     // flags -> EFLAGS
18612     if (StringRef("{flags}").equals_lower(Constraint)) {
18613       Res.first = X86::EFLAGS;
18614       Res.second = &X86::CCRRegClass;
18615       return Res;
18616     }
18617
18618     // 'A' means EAX + EDX.
18619     if (Constraint == "A") {
18620       Res.first = X86::EAX;
18621       Res.second = &X86::GR32_ADRegClass;
18622       return Res;
18623     }
18624     return Res;
18625   }
18626
18627   // Otherwise, check to see if this is a register class of the wrong value
18628   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18629   // turn into {ax},{dx}.
18630   if (Res.second->hasType(VT))
18631     return Res;   // Correct type already, nothing to do.
18632
18633   // All of the single-register GCC register classes map their values onto
18634   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18635   // really want an 8-bit or 32-bit register, map to the appropriate register
18636   // class and return the appropriate register.
18637   if (Res.second == &X86::GR16RegClass) {
18638     if (VT == MVT::i8 || VT == MVT::i1) {
18639       unsigned DestReg = 0;
18640       switch (Res.first) {
18641       default: break;
18642       case X86::AX: DestReg = X86::AL; break;
18643       case X86::DX: DestReg = X86::DL; break;
18644       case X86::CX: DestReg = X86::CL; break;
18645       case X86::BX: DestReg = X86::BL; break;
18646       }
18647       if (DestReg) {
18648         Res.first = DestReg;
18649         Res.second = &X86::GR8RegClass;
18650       }
18651     } else if (VT == MVT::i32 || VT == MVT::f32) {
18652       unsigned DestReg = 0;
18653       switch (Res.first) {
18654       default: break;
18655       case X86::AX: DestReg = X86::EAX; break;
18656       case X86::DX: DestReg = X86::EDX; break;
18657       case X86::CX: DestReg = X86::ECX; break;
18658       case X86::BX: DestReg = X86::EBX; break;
18659       case X86::SI: DestReg = X86::ESI; break;
18660       case X86::DI: DestReg = X86::EDI; break;
18661       case X86::BP: DestReg = X86::EBP; break;
18662       case X86::SP: DestReg = X86::ESP; break;
18663       }
18664       if (DestReg) {
18665         Res.first = DestReg;
18666         Res.second = &X86::GR32RegClass;
18667       }
18668     } else if (VT == MVT::i64 || VT == MVT::f64) {
18669       unsigned DestReg = 0;
18670       switch (Res.first) {
18671       default: break;
18672       case X86::AX: DestReg = X86::RAX; break;
18673       case X86::DX: DestReg = X86::RDX; break;
18674       case X86::CX: DestReg = X86::RCX; break;
18675       case X86::BX: DestReg = X86::RBX; break;
18676       case X86::SI: DestReg = X86::RSI; break;
18677       case X86::DI: DestReg = X86::RDI; break;
18678       case X86::BP: DestReg = X86::RBP; break;
18679       case X86::SP: DestReg = X86::RSP; break;
18680       }
18681       if (DestReg) {
18682         Res.first = DestReg;
18683         Res.second = &X86::GR64RegClass;
18684       }
18685     }
18686   } else if (Res.second == &X86::FR32RegClass ||
18687              Res.second == &X86::FR64RegClass ||
18688              Res.second == &X86::VR128RegClass) {
18689     // Handle references to XMM physical registers that got mapped into the
18690     // wrong class.  This can happen with constraints like {xmm0} where the
18691     // target independent register mapper will just pick the first match it can
18692     // find, ignoring the required type.
18693
18694     if (VT == MVT::f32 || VT == MVT::i32)
18695       Res.second = &X86::FR32RegClass;
18696     else if (VT == MVT::f64 || VT == MVT::i64)
18697       Res.second = &X86::FR64RegClass;
18698     else if (X86::VR128RegClass.hasType(VT))
18699       Res.second = &X86::VR128RegClass;
18700     else if (X86::VR256RegClass.hasType(VT))
18701       Res.second = &X86::VR256RegClass;
18702   }
18703
18704   return Res;
18705 }