Fix an unused variable warning from r161742.
[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 "X86.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.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, DebugLoc 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, DebugLoc 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   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
89   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
90                                VecIdx);
91
92   return Result;
93 }
94
95 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference.  Idx is an index in the 128 bits
98 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101                                   unsigned IdxVal, SelectionDAG &DAG,
102                                   DebugLoc dl) {
103   // Inserting UNDEF is Result
104   if (Vec.getOpcode() == ISD::UNDEF)
105     return Result;
106
107   EVT VT = Vec.getValueType();
108   assert(VT.is128BitVector() && "Unexpected vector size!");
109
110   EVT ElVT = VT.getVectorElementType();
111   EVT ResultVT = Result.getValueType();
112
113   // Insert the relevant 128 bits.
114   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115
116   // This is the index of the first element of the 128-bit chunk
117   // we want.
118   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
119                                * ElemsPerChunk);
120
121   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
122   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
123                      VecIdx);
124 }
125
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131                                    unsigned NumElems, SelectionDAG &DAG,
132                                    DebugLoc dl) {
133   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
135 }
136
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139   bool is64Bit = Subtarget->is64Bit();
140
141   if (Subtarget->isTargetEnvMacho()) {
142     if (is64Bit)
143       return new X86_64MachoTargetObjectFile();
144     return new TargetLoweringObjectFileMachO();
145   }
146
147   if (Subtarget->isTargetLinux())
148     return new X86LinuxTargetObjectFile();
149   if (Subtarget->isTargetELF())
150     return new TargetLoweringObjectFileELF();
151   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152     return new TargetLoweringObjectFileCOFF();
153   llvm_unreachable("unknown subtarget type");
154 }
155
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157   : TargetLowering(TM, createTLOF(TM)) {
158   Subtarget = &TM.getSubtarget<X86Subtarget>();
159   X86ScalarSSEf64 = Subtarget->hasSSE2();
160   X86ScalarSSEf32 = Subtarget->hasSSE1();
161   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
162
163   RegInfo = TM.getRegisterInfo();
164   TD = getTargetData();
165
166   // Set up the TargetLowering object.
167   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168
169   // X86 is weird, it always uses i8 for shift amounts and setcc results.
170   setBooleanContents(ZeroOrOneBooleanContent);
171   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   // For 64-bit since we have so many registers use the ILP scheduler, for
175   // 32-bit code use the register pressure specific scheduling.
176   // For Atom, always use ILP scheduling.
177   if (Subtarget->isAtom())
178     setSchedulingPreference(Sched::ILP);
179   else if (Subtarget->is64Bit())
180     setSchedulingPreference(Sched::ILP);
181   else
182     setSchedulingPreference(Sched::RegPressure);
183   setStackPointerRegisterToSaveRestore(X86StackPtr);
184
185   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
186     // Setup Windows compiler runtime calls.
187     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
188     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
189     setLibcallName(RTLIB::SREM_I64, "_allrem");
190     setLibcallName(RTLIB::UREM_I64, "_aullrem");
191     setLibcallName(RTLIB::MUL_I64, "_allmul");
192     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
193     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
194     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
195     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
196     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
197
198     // The _ftol2 runtime function has an unusual calling conv, which
199     // is modeled by a special pseudo-instruction.
200     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
201     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
202     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
203     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
204   }
205
206   if (Subtarget->isTargetDarwin()) {
207     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
208     setUseUnderscoreSetJmp(false);
209     setUseUnderscoreLongJmp(false);
210   } else if (Subtarget->isTargetMingw()) {
211     // MS runtime is weird: it exports _setjmp, but longjmp!
212     setUseUnderscoreSetJmp(true);
213     setUseUnderscoreLongJmp(false);
214   } else {
215     setUseUnderscoreSetJmp(true);
216     setUseUnderscoreLongJmp(true);
217   }
218
219   // Set up the register classes.
220   addRegisterClass(MVT::i8, &X86::GR8RegClass);
221   addRegisterClass(MVT::i16, &X86::GR16RegClass);
222   addRegisterClass(MVT::i32, &X86::GR32RegClass);
223   if (Subtarget->is64Bit())
224     addRegisterClass(MVT::i64, &X86::GR64RegClass);
225
226   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
227
228   // We don't accept any truncstore of integer registers.
229   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
230   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
231   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
232   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
233   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
234   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
235
236   // SETOEQ and SETUNE require checking two conditions.
237   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
238   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
239   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
240   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
241   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
242   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
243
244   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
245   // operation.
246   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
247   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
248   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
249
250   if (Subtarget->is64Bit()) {
251     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
252     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
253   } else if (!TM.Options.UseSoftFloat) {
254     // We have an algorithm for SSE2->double, and we turn this into a
255     // 64-bit FILD followed by conditional FADD for other targets.
256     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
257     // We have an algorithm for SSE2, and we turn this into a 64-bit
258     // FILD for other targets.
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
260   }
261
262   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
263   // this operation.
264   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
265   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
266
267   if (!TM.Options.UseSoftFloat) {
268     // SSE has no i16 to fp conversion, only i32
269     if (X86ScalarSSEf32) {
270       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
271       // f32 and f64 cases are Legal, f80 case is not
272       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
273     } else {
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
275       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
276     }
277   } else {
278     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
279     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
280   }
281
282   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
283   // are Legal, f80 is custom lowered.
284   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
285   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
286
287   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
288   // this operation.
289   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
290   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
291
292   if (X86ScalarSSEf32) {
293     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
294     // f32 and f64 cases are Legal, f80 case is not
295     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
296   } else {
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
298     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
299   }
300
301   // Handle FP_TO_UINT by promoting the destination to a larger signed
302   // conversion.
303   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
304   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
305   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
306
307   if (Subtarget->is64Bit()) {
308     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
309     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
310   } else if (!TM.Options.UseSoftFloat) {
311     // Since AVX is a superset of SSE3, only check for SSE here.
312     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
313       // Expand FP_TO_UINT into a select.
314       // FIXME: We would like to use a Custom expander here eventually to do
315       // the optimal thing for SSE vs. the default expansion in the legalizer.
316       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
317     else
318       // With SSE3 we can use fisttpll to convert to a signed i64; without
319       // SSE, we're stuck with a fistpll.
320       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
321   }
322
323   if (isTargetFTOL()) {
324     // Use the _ftol2 runtime function, which has a pseudo-instruction
325     // to handle its weird calling convention.
326     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
327   }
328
329   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330   if (!X86ScalarSSEf64) {
331     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
332     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
333     if (Subtarget->is64Bit()) {
334       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
335       // Without SSE, i64->f64 goes through memory.
336       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
337     }
338   }
339
340   // Scalar integer divide and remainder are lowered to use operations that
341   // produce two results, to match the available instructions. This exposes
342   // the two-result form to trivial CSE, which is able to combine x/y and x%y
343   // into a single instruction.
344   //
345   // Scalar integer multiply-high is also lowered to use two-result
346   // operations, to match the available instructions. However, plain multiply
347   // (low) operations are left as Legal, as there are single-result
348   // instructions for this in x86. Using the two-result multiply instructions
349   // when both high and low results are needed must be arranged by dagcombine.
350   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
351     MVT VT = IntVTs[i];
352     setOperationAction(ISD::MULHS, VT, Expand);
353     setOperationAction(ISD::MULHU, VT, Expand);
354     setOperationAction(ISD::SDIV, VT, Expand);
355     setOperationAction(ISD::UDIV, VT, Expand);
356     setOperationAction(ISD::SREM, VT, Expand);
357     setOperationAction(ISD::UREM, VT, Expand);
358
359     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360     setOperationAction(ISD::ADDC, VT, Custom);
361     setOperationAction(ISD::ADDE, VT, Custom);
362     setOperationAction(ISD::SUBC, VT, Custom);
363     setOperationAction(ISD::SUBE, VT, Custom);
364   }
365
366   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
367   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
368   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
369   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
370   if (Subtarget->is64Bit())
371     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
375   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
376   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
379   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
380
381   // Promote the i8 variants and force them on up to i32 which has a shorter
382   // encoding.
383   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
384   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
385   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
386   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
387   if (Subtarget->hasBMI()) {
388     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
389     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
390     if (Subtarget->is64Bit())
391       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
392   } else {
393     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
394     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
395     if (Subtarget->is64Bit())
396       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
397   }
398
399   if (Subtarget->hasLZCNT()) {
400     // When promoting the i8 variants, force them to i32 for a shorter
401     // encoding.
402     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
403     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
404     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
405     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
406     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
407     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
408     if (Subtarget->is64Bit())
409       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
410   } else {
411     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
412     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
413     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
414     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
415     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
416     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
417     if (Subtarget->is64Bit()) {
418       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
419       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
420     }
421   }
422
423   if (Subtarget->hasPOPCNT()) {
424     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
425   } else {
426     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
427     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
428     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
429     if (Subtarget->is64Bit())
430       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
431   }
432
433   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
434   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
435
436   // These should be promoted to a larger select which is supported.
437   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
438   // X86 wants to expand cmov itself.
439   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
440   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
441   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
442   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
443   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
444   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
445   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
446   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
447   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
448   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
450   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
451   if (Subtarget->is64Bit()) {
452     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
453     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
454   }
455   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
456
457   // Darwin ABI issue.
458   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
459   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
460   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
461   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
462   if (Subtarget->is64Bit())
463     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
464   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
465   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
466   if (Subtarget->is64Bit()) {
467     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
468     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
469     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
470     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
471     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
472   }
473   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
474   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
475   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
476   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
477   if (Subtarget->is64Bit()) {
478     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
479     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
480     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
481   }
482
483   if (Subtarget->hasSSE1())
484     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
485
486   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
487   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
488
489   // On X86 and X86-64, atomic operations are lowered to locked instructions.
490   // Locked instructions, in turn, have implicit fence semantics (all memory
491   // operations are flushed before issuing the locked instruction, and they
492   // are not buffered), so we can fold away the common pattern of
493   // fence-atomic-fence.
494   setShouldFoldAtomicFences(true);
495
496   // Expand certain atomics
497   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
498     MVT VT = IntVTs[i];
499     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
500     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
501     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
502   }
503
504   if (!Subtarget->is64Bit()) {
505     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
507     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
508     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
509     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
513   }
514
515   if (Subtarget->hasCmpxchg16b()) {
516     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
517   }
518
519   // FIXME - use subtarget debug flags
520   if (!Subtarget->isTargetDarwin() &&
521       !Subtarget->isTargetELF() &&
522       !Subtarget->isTargetCygMing()) {
523     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
524   }
525
526   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
527   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
528   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
529   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
530   if (Subtarget->is64Bit()) {
531     setExceptionPointerRegister(X86::RAX);
532     setExceptionSelectorRegister(X86::RDX);
533   } else {
534     setExceptionPointerRegister(X86::EAX);
535     setExceptionSelectorRegister(X86::EDX);
536   }
537   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
538   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
539
540   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
541   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
542
543   setOperationAction(ISD::TRAP, MVT::Other, Legal);
544
545   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
546   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
547   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
548   if (Subtarget->is64Bit()) {
549     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
550     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
551   } else {
552     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
553     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
554   }
555
556   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
557   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
558
559   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
560     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
561                        MVT::i64 : MVT::i32, Custom);
562   else if (TM.Options.EnableSegmentedStacks)
563     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
564                        MVT::i64 : MVT::i32, Custom);
565   else
566     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
567                        MVT::i64 : MVT::i32, Expand);
568
569   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
570     // f32 and f64 use SSE.
571     // Set up the FP register classes.
572     addRegisterClass(MVT::f32, &X86::FR32RegClass);
573     addRegisterClass(MVT::f64, &X86::FR64RegClass);
574
575     // Use ANDPD to simulate FABS.
576     setOperationAction(ISD::FABS , MVT::f64, Custom);
577     setOperationAction(ISD::FABS , MVT::f32, Custom);
578
579     // Use XORP to simulate FNEG.
580     setOperationAction(ISD::FNEG , MVT::f64, Custom);
581     setOperationAction(ISD::FNEG , MVT::f32, Custom);
582
583     // Use ANDPD and ORPD to simulate FCOPYSIGN.
584     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
585     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
586
587     // Lower this to FGETSIGNx86 plus an AND.
588     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
589     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
590
591     // We don't support sin/cos/fmod
592     setOperationAction(ISD::FSIN , MVT::f64, Expand);
593     setOperationAction(ISD::FCOS , MVT::f64, Expand);
594     setOperationAction(ISD::FSIN , MVT::f32, Expand);
595     setOperationAction(ISD::FCOS , MVT::f32, Expand);
596
597     // Expand FP immediates into loads from the stack, except for the special
598     // cases we handle.
599     addLegalFPImmediate(APFloat(+0.0)); // xorpd
600     addLegalFPImmediate(APFloat(+0.0f)); // xorps
601   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
602     // Use SSE for f32, x87 for f64.
603     // Set up the FP register classes.
604     addRegisterClass(MVT::f32, &X86::FR32RegClass);
605     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
606
607     // Use ANDPS to simulate FABS.
608     setOperationAction(ISD::FABS , MVT::f32, Custom);
609
610     // Use XORP to simulate FNEG.
611     setOperationAction(ISD::FNEG , MVT::f32, Custom);
612
613     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
614
615     // Use ANDPS and ORPS to simulate FCOPYSIGN.
616     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
617     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
618
619     // We don't support sin/cos/fmod
620     setOperationAction(ISD::FSIN , MVT::f32, Expand);
621     setOperationAction(ISD::FCOS , MVT::f32, Expand);
622
623     // Special cases we handle for FP constants.
624     addLegalFPImmediate(APFloat(+0.0f)); // xorps
625     addLegalFPImmediate(APFloat(+0.0)); // FLD0
626     addLegalFPImmediate(APFloat(+1.0)); // FLD1
627     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
628     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
629
630     if (!TM.Options.UnsafeFPMath) {
631       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
632       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
633     }
634   } else if (!TM.Options.UseSoftFloat) {
635     // f32 and f64 in x87.
636     // Set up the FP register classes.
637     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
638     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
639
640     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
641     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
642     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
643     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
644
645     if (!TM.Options.UnsafeFPMath) {
646       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
647       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
648     }
649     addLegalFPImmediate(APFloat(+0.0)); // FLD0
650     addLegalFPImmediate(APFloat(+1.0)); // FLD1
651     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
652     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
653     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
654     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
655     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
656     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
657   }
658
659   // We don't support FMA.
660   setOperationAction(ISD::FMA, MVT::f64, Expand);
661   setOperationAction(ISD::FMA, MVT::f32, Expand);
662
663   // Long double always uses X87.
664   if (!TM.Options.UseSoftFloat) {
665     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
666     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
667     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
668     {
669       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
670       addLegalFPImmediate(TmpFlt);  // FLD0
671       TmpFlt.changeSign();
672       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
673
674       bool ignored;
675       APFloat TmpFlt2(+1.0);
676       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
677                       &ignored);
678       addLegalFPImmediate(TmpFlt2);  // FLD1
679       TmpFlt2.changeSign();
680       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
681     }
682
683     if (!TM.Options.UnsafeFPMath) {
684       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
685       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
686     }
687
688     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
689     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
690     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
691     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
692     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
693     setOperationAction(ISD::FMA, MVT::f80, Expand);
694   }
695
696   // Always use a library call for pow.
697   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
698   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
699   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
700
701   setOperationAction(ISD::FLOG, MVT::f80, Expand);
702   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
703   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
704   setOperationAction(ISD::FEXP, MVT::f80, Expand);
705   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
706
707   // First set operation action for all vector types to either promote
708   // (for widening) or expand (for scalarization). Then we will selectively
709   // turn on ones that can be effectively codegen'd.
710   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
711            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
712     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
727     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
729     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
730     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
765     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
770     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
771              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
772       setTruncStoreAction((MVT::SimpleValueType)VT,
773                           (MVT::SimpleValueType)InnerVT, Expand);
774     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
775     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
776     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
777   }
778
779   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
780   // with -msoft-float, disable use of MMX as well.
781   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
782     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
783     // No operations on x86mmx supported, everything uses intrinsics.
784   }
785
786   // MMX-sized vectors (other than x86mmx) are expected to be expanded
787   // into smaller operations.
788   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
789   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
790   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
791   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
792   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
793   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
794   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
795   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
796   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
797   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
798   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
799   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
800   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
801   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
802   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
803   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
804   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
805   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
806   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
807   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
808   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
809   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
810   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
811   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
812   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
813   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
814   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
815   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
816   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
817
818   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
819     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
820
821     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
822     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
823     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
824     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
825     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
826     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
827     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
828     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
829     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
830     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
831     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
832   }
833
834   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
835     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
836
837     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
838     // registers cannot be used even for integer operations.
839     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
840     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
841     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
842     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
843
844     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
845     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
846     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
847     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
848     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
849     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
850     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
851     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
852     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
853     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
854     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
855     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
856     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
857     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
858     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
859     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
860
861     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
862     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
863     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
864     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
865
866     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
867     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
868     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
869     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
870     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
871
872     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
873     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
874       MVT VT = (MVT::SimpleValueType)i;
875       // Do not attempt to custom lower non-power-of-2 vectors
876       if (!isPowerOf2_32(VT.getVectorNumElements()))
877         continue;
878       // Do not attempt to custom lower non-128-bit vectors
879       if (!VT.is128BitVector())
880         continue;
881       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
882       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
883       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
884     }
885
886     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
887     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
888     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
889     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
890     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
891     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
892
893     if (Subtarget->is64Bit()) {
894       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
895       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
896     }
897
898     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
899     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900       MVT VT = (MVT::SimpleValueType)i;
901
902       // Do not attempt to promote non-128-bit vectors
903       if (!VT.is128BitVector())
904         continue;
905
906       setOperationAction(ISD::AND,    VT, Promote);
907       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
908       setOperationAction(ISD::OR,     VT, Promote);
909       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
910       setOperationAction(ISD::XOR,    VT, Promote);
911       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
912       setOperationAction(ISD::LOAD,   VT, Promote);
913       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
914       setOperationAction(ISD::SELECT, VT, Promote);
915       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
916     }
917
918     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
919
920     // Custom lower v2i64 and v2f64 selects.
921     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
922     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
923     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
924     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
925
926     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
927     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
928   }
929
930   if (Subtarget->hasSSE41()) {
931     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
932     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
933     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
934     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
935     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
936     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
937     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
938     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
939     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
940     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
941
942     // FIXME: Do we need to handle scalar-to-vector here?
943     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
944
945     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
946     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
947     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
948     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
949     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
950
951     // i8 and i16 vectors are custom , because the source register and source
952     // source memory operand types are not the same width.  f32 vectors are
953     // custom since the immediate controlling the insert encodes additional
954     // information.
955     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
956     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
957     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
958     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
959
960     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
961     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
962     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
963     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
964
965     // FIXME: these should be Legal but thats only for the case where
966     // the index is constant.  For now custom expand to deal with that.
967     if (Subtarget->is64Bit()) {
968       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
969       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
970     }
971   }
972
973   if (Subtarget->hasSSE2()) {
974     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
975     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
976
977     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
978     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
979
980     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
981     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
982
983     if (Subtarget->hasAVX2()) {
984       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
985       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
986
987       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
988       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
989
990       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
991     } else {
992       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
993       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
994
995       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
996       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
997
998       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
999     }
1000   }
1001
1002   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1003     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1004     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1005     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1006     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1007     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1008     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1009
1010     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1011     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1012     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1013
1014     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1015     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1016     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1017     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1018     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1019     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1020
1021     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1022     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1023     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1024     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1025     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1026     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1027
1028     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1029     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1030     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1031
1032     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1033     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1034
1035     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1036     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1037
1038     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1039     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1040
1041     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1042     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1043     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1044     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1045
1046     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1047     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1048     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1049
1050     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1051     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1052     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1053     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1054
1055     if (Subtarget->hasFMA()) {
1056       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1057       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1058       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1059       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1060       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1061       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1062     }
1063
1064     if (Subtarget->hasAVX2()) {
1065       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1066       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1067       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1068       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1069
1070       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1071       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1072       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1073       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1074
1075       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1076       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1077       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1078       // Don't lower v32i8 because there is no 128-bit byte mul
1079
1080       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1081
1082       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1083       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1084
1085       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1086       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1087
1088       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1089     } else {
1090       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1091       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1092       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1093       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1094
1095       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1096       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1097       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1098       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1099
1100       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1101       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1102       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1103       // Don't lower v32i8 because there is no 128-bit byte mul
1104
1105       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1106       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1107
1108       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1109       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1110
1111       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1112     }
1113
1114     // Custom lower several nodes for 256-bit types.
1115     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1116              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1117       MVT VT = (MVT::SimpleValueType)i;
1118
1119       // Extract subvector is special because the value type
1120       // (result) is 128-bit but the source is 256-bit wide.
1121       if (VT.is128BitVector())
1122         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1123
1124       // Do not attempt to custom lower other non-256-bit vectors
1125       if (!VT.is256BitVector())
1126         continue;
1127
1128       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1129       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1130       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1131       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1132       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1133       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1134       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1135     }
1136
1137     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1138     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1139       MVT VT = (MVT::SimpleValueType)i;
1140
1141       // Do not attempt to promote non-256-bit vectors
1142       if (!VT.is256BitVector())
1143         continue;
1144
1145       setOperationAction(ISD::AND,    VT, Promote);
1146       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1147       setOperationAction(ISD::OR,     VT, Promote);
1148       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1149       setOperationAction(ISD::XOR,    VT, Promote);
1150       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1151       setOperationAction(ISD::LOAD,   VT, Promote);
1152       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1153       setOperationAction(ISD::SELECT, VT, Promote);
1154       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1155     }
1156   }
1157
1158   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1159   // of this type with custom code.
1160   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1161            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1162     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1163                        Custom);
1164   }
1165
1166   // We want to custom lower some of our intrinsics.
1167   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1168   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1169
1170
1171   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1172   // handle type legalization for these operations here.
1173   //
1174   // FIXME: We really should do custom legalization for addition and
1175   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1176   // than generic legalization for 64-bit multiplication-with-overflow, though.
1177   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1178     // Add/Sub/Mul with overflow operations are custom lowered.
1179     MVT VT = IntVTs[i];
1180     setOperationAction(ISD::SADDO, VT, Custom);
1181     setOperationAction(ISD::UADDO, VT, Custom);
1182     setOperationAction(ISD::SSUBO, VT, Custom);
1183     setOperationAction(ISD::USUBO, VT, Custom);
1184     setOperationAction(ISD::SMULO, VT, Custom);
1185     setOperationAction(ISD::UMULO, VT, Custom);
1186   }
1187
1188   // There are no 8-bit 3-address imul/mul instructions
1189   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1190   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1191
1192   if (!Subtarget->is64Bit()) {
1193     // These libcalls are not available in 32-bit.
1194     setLibcallName(RTLIB::SHL_I128, 0);
1195     setLibcallName(RTLIB::SRL_I128, 0);
1196     setLibcallName(RTLIB::SRA_I128, 0);
1197   }
1198
1199   // We have target-specific dag combine patterns for the following nodes:
1200   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1201   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1202   setTargetDAGCombine(ISD::VSELECT);
1203   setTargetDAGCombine(ISD::SELECT);
1204   setTargetDAGCombine(ISD::SHL);
1205   setTargetDAGCombine(ISD::SRA);
1206   setTargetDAGCombine(ISD::SRL);
1207   setTargetDAGCombine(ISD::OR);
1208   setTargetDAGCombine(ISD::AND);
1209   setTargetDAGCombine(ISD::ADD);
1210   setTargetDAGCombine(ISD::FADD);
1211   setTargetDAGCombine(ISD::FSUB);
1212   setTargetDAGCombine(ISD::FMA);
1213   setTargetDAGCombine(ISD::SUB);
1214   setTargetDAGCombine(ISD::LOAD);
1215   setTargetDAGCombine(ISD::STORE);
1216   setTargetDAGCombine(ISD::ZERO_EXTEND);
1217   setTargetDAGCombine(ISD::ANY_EXTEND);
1218   setTargetDAGCombine(ISD::SIGN_EXTEND);
1219   setTargetDAGCombine(ISD::TRUNCATE);
1220   setTargetDAGCombine(ISD::UINT_TO_FP);
1221   setTargetDAGCombine(ISD::SINT_TO_FP);
1222   setTargetDAGCombine(ISD::SETCC);
1223   setTargetDAGCombine(ISD::FP_TO_SINT);
1224   if (Subtarget->is64Bit())
1225     setTargetDAGCombine(ISD::MUL);
1226   setTargetDAGCombine(ISD::XOR);
1227
1228   computeRegisterProperties();
1229
1230   // On Darwin, -Os means optimize for size without hurting performance,
1231   // do not reduce the limit.
1232   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1233   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1234   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1235   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1236   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1237   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1238   setPrefLoopAlignment(4); // 2^4 bytes.
1239   benefitFromCodePlacementOpt = true;
1240
1241   // Predictable cmov don't hurt on atom because it's in-order.
1242   predictableSelectIsExpensive = !Subtarget->isAtom();
1243
1244   setPrefFunctionAlignment(4); // 2^4 bytes.
1245 }
1246
1247
1248 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1249   if (!VT.isVector()) return MVT::i8;
1250   return VT.changeVectorElementTypeToInteger();
1251 }
1252
1253
1254 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1255 /// the desired ByVal argument alignment.
1256 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1257   if (MaxAlign == 16)
1258     return;
1259   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1260     if (VTy->getBitWidth() == 128)
1261       MaxAlign = 16;
1262   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1263     unsigned EltAlign = 0;
1264     getMaxByValAlign(ATy->getElementType(), EltAlign);
1265     if (EltAlign > MaxAlign)
1266       MaxAlign = EltAlign;
1267   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1268     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1269       unsigned EltAlign = 0;
1270       getMaxByValAlign(STy->getElementType(i), EltAlign);
1271       if (EltAlign > MaxAlign)
1272         MaxAlign = EltAlign;
1273       if (MaxAlign == 16)
1274         break;
1275     }
1276   }
1277 }
1278
1279 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1280 /// function arguments in the caller parameter area. For X86, aggregates
1281 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1282 /// are at 4-byte boundaries.
1283 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1284   if (Subtarget->is64Bit()) {
1285     // Max of 8 and alignment of type.
1286     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1287     if (TyAlign > 8)
1288       return TyAlign;
1289     return 8;
1290   }
1291
1292   unsigned Align = 4;
1293   if (Subtarget->hasSSE1())
1294     getMaxByValAlign(Ty, Align);
1295   return Align;
1296 }
1297
1298 /// getOptimalMemOpType - Returns the target specific optimal type for load
1299 /// and store operations as a result of memset, memcpy, and memmove
1300 /// lowering. If DstAlign is zero that means it's safe to destination
1301 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1302 /// means there isn't a need to check it against alignment requirement,
1303 /// probably because the source does not need to be loaded. If
1304 /// 'IsZeroVal' is true, that means it's safe to return a
1305 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1306 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1307 /// constant so it does not need to be loaded.
1308 /// It returns EVT::Other if the type should be determined using generic
1309 /// target-independent logic.
1310 EVT
1311 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1312                                        unsigned DstAlign, unsigned SrcAlign,
1313                                        bool IsZeroVal,
1314                                        bool MemcpyStrSrc,
1315                                        MachineFunction &MF) const {
1316   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1317   // linux.  This is because the stack realignment code can't handle certain
1318   // cases like PR2962.  This should be removed when PR2962 is fixed.
1319   const Function *F = MF.getFunction();
1320   if (IsZeroVal &&
1321       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1322     if (Size >= 16 &&
1323         (Subtarget->isUnalignedMemAccessFast() ||
1324          ((DstAlign == 0 || DstAlign >= 16) &&
1325           (SrcAlign == 0 || SrcAlign >= 16))) &&
1326         Subtarget->getStackAlignment() >= 16) {
1327       if (Subtarget->getStackAlignment() >= 32) {
1328         if (Subtarget->hasAVX2())
1329           return MVT::v8i32;
1330         if (Subtarget->hasAVX())
1331           return MVT::v8f32;
1332       }
1333       if (Subtarget->hasSSE2())
1334         return MVT::v4i32;
1335       if (Subtarget->hasSSE1())
1336         return MVT::v4f32;
1337     } else if (!MemcpyStrSrc && Size >= 8 &&
1338                !Subtarget->is64Bit() &&
1339                Subtarget->getStackAlignment() >= 8 &&
1340                Subtarget->hasSSE2()) {
1341       // Do not use f64 to lower memcpy if source is string constant. It's
1342       // better to use i32 to avoid the loads.
1343       return MVT::f64;
1344     }
1345   }
1346   if (Subtarget->is64Bit() && Size >= 8)
1347     return MVT::i64;
1348   return MVT::i32;
1349 }
1350
1351 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1352 /// current function.  The returned value is a member of the
1353 /// MachineJumpTableInfo::JTEntryKind enum.
1354 unsigned X86TargetLowering::getJumpTableEncoding() const {
1355   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1356   // symbol.
1357   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1358       Subtarget->isPICStyleGOT())
1359     return MachineJumpTableInfo::EK_Custom32;
1360
1361   // Otherwise, use the normal jump table encoding heuristics.
1362   return TargetLowering::getJumpTableEncoding();
1363 }
1364
1365 const MCExpr *
1366 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1367                                              const MachineBasicBlock *MBB,
1368                                              unsigned uid,MCContext &Ctx) const{
1369   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1370          Subtarget->isPICStyleGOT());
1371   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1372   // entries.
1373   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1374                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1375 }
1376
1377 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1378 /// jumptable.
1379 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1380                                                     SelectionDAG &DAG) const {
1381   if (!Subtarget->is64Bit())
1382     // This doesn't have DebugLoc associated with it, but is not really the
1383     // same as a Register.
1384     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1385   return Table;
1386 }
1387
1388 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1389 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1390 /// MCExpr.
1391 const MCExpr *X86TargetLowering::
1392 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1393                              MCContext &Ctx) const {
1394   // X86-64 uses RIP relative addressing based on the jump table label.
1395   if (Subtarget->isPICStyleRIPRel())
1396     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1397
1398   // Otherwise, the reference is relative to the PIC base.
1399   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1400 }
1401
1402 // FIXME: Why this routine is here? Move to RegInfo!
1403 std::pair<const TargetRegisterClass*, uint8_t>
1404 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1405   const TargetRegisterClass *RRC = 0;
1406   uint8_t Cost = 1;
1407   switch (VT.getSimpleVT().SimpleTy) {
1408   default:
1409     return TargetLowering::findRepresentativeClass(VT);
1410   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1411     RRC = Subtarget->is64Bit() ?
1412       (const TargetRegisterClass*)&X86::GR64RegClass :
1413       (const TargetRegisterClass*)&X86::GR32RegClass;
1414     break;
1415   case MVT::x86mmx:
1416     RRC = &X86::VR64RegClass;
1417     break;
1418   case MVT::f32: case MVT::f64:
1419   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1420   case MVT::v4f32: case MVT::v2f64:
1421   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1422   case MVT::v4f64:
1423     RRC = &X86::VR128RegClass;
1424     break;
1425   }
1426   return std::make_pair(RRC, Cost);
1427 }
1428
1429 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1430                                                unsigned &Offset) const {
1431   if (!Subtarget->isTargetLinux())
1432     return false;
1433
1434   if (Subtarget->is64Bit()) {
1435     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1436     Offset = 0x28;
1437     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1438       AddressSpace = 256;
1439     else
1440       AddressSpace = 257;
1441   } else {
1442     // %gs:0x14 on i386
1443     Offset = 0x14;
1444     AddressSpace = 256;
1445   }
1446   return true;
1447 }
1448
1449
1450 //===----------------------------------------------------------------------===//
1451 //               Return Value Calling Convention Implementation
1452 //===----------------------------------------------------------------------===//
1453
1454 #include "X86GenCallingConv.inc"
1455
1456 bool
1457 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1458                                   MachineFunction &MF, bool isVarArg,
1459                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1460                         LLVMContext &Context) const {
1461   SmallVector<CCValAssign, 16> RVLocs;
1462   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1463                  RVLocs, Context);
1464   return CCInfo.CheckReturn(Outs, RetCC_X86);
1465 }
1466
1467 SDValue
1468 X86TargetLowering::LowerReturn(SDValue Chain,
1469                                CallingConv::ID CallConv, bool isVarArg,
1470                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1471                                const SmallVectorImpl<SDValue> &OutVals,
1472                                DebugLoc dl, SelectionDAG &DAG) const {
1473   MachineFunction &MF = DAG.getMachineFunction();
1474   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1475
1476   SmallVector<CCValAssign, 16> RVLocs;
1477   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1478                  RVLocs, *DAG.getContext());
1479   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1480
1481   // Add the regs to the liveout set for the function.
1482   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1483   for (unsigned i = 0; i != RVLocs.size(); ++i)
1484     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1485       MRI.addLiveOut(RVLocs[i].getLocReg());
1486
1487   SDValue Flag;
1488
1489   SmallVector<SDValue, 6> RetOps;
1490   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1491   // Operand #1 = Bytes To Pop
1492   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1493                    MVT::i16));
1494
1495   // Copy the result values into the output registers.
1496   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1497     CCValAssign &VA = RVLocs[i];
1498     assert(VA.isRegLoc() && "Can only return in registers!");
1499     SDValue ValToCopy = OutVals[i];
1500     EVT ValVT = ValToCopy.getValueType();
1501
1502     // Promote values to the appropriate types
1503     if (VA.getLocInfo() == CCValAssign::SExt)
1504       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1505     else if (VA.getLocInfo() == CCValAssign::ZExt)
1506       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1507     else if (VA.getLocInfo() == CCValAssign::AExt)
1508       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1509     else if (VA.getLocInfo() == CCValAssign::BCvt)
1510       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1511
1512     // If this is x86-64, and we disabled SSE, we can't return FP values,
1513     // or SSE or MMX vectors.
1514     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1515          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1516           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1517       report_fatal_error("SSE register return with SSE disabled");
1518     }
1519     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1520     // llvm-gcc has never done it right and no one has noticed, so this
1521     // should be OK for now.
1522     if (ValVT == MVT::f64 &&
1523         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1524       report_fatal_error("SSE2 register return with SSE2 disabled");
1525
1526     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1527     // the RET instruction and handled by the FP Stackifier.
1528     if (VA.getLocReg() == X86::ST0 ||
1529         VA.getLocReg() == X86::ST1) {
1530       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1531       // change the value to the FP stack register class.
1532       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1533         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1534       RetOps.push_back(ValToCopy);
1535       // Don't emit a copytoreg.
1536       continue;
1537     }
1538
1539     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1540     // which is returned in RAX / RDX.
1541     if (Subtarget->is64Bit()) {
1542       if (ValVT == MVT::x86mmx) {
1543         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1544           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1545           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1546                                   ValToCopy);
1547           // If we don't have SSE2 available, convert to v4f32 so the generated
1548           // register is legal.
1549           if (!Subtarget->hasSSE2())
1550             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1551         }
1552       }
1553     }
1554
1555     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1556     Flag = Chain.getValue(1);
1557   }
1558
1559   // The x86-64 ABI for returning structs by value requires that we copy
1560   // the sret argument into %rax for the return. We saved the argument into
1561   // a virtual register in the entry block, so now we copy the value out
1562   // and into %rax.
1563   if (Subtarget->is64Bit() &&
1564       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1565     MachineFunction &MF = DAG.getMachineFunction();
1566     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1567     unsigned Reg = FuncInfo->getSRetReturnReg();
1568     assert(Reg &&
1569            "SRetReturnReg should have been set in LowerFormalArguments().");
1570     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1571
1572     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1573     Flag = Chain.getValue(1);
1574
1575     // RAX now acts like a return value.
1576     MRI.addLiveOut(X86::RAX);
1577   }
1578
1579   RetOps[0] = Chain;  // Update chain.
1580
1581   // Add the flag if we have it.
1582   if (Flag.getNode())
1583     RetOps.push_back(Flag);
1584
1585   return DAG.getNode(X86ISD::RET_FLAG, dl,
1586                      MVT::Other, &RetOps[0], RetOps.size());
1587 }
1588
1589 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1590   if (N->getNumValues() != 1)
1591     return false;
1592   if (!N->hasNUsesOfValue(1, 0))
1593     return false;
1594
1595   SDValue TCChain = Chain;
1596   SDNode *Copy = *N->use_begin();
1597   if (Copy->getOpcode() == ISD::CopyToReg) {
1598     // If the copy has a glue operand, we conservatively assume it isn't safe to
1599     // perform a tail call.
1600     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1601       return false;
1602     TCChain = Copy->getOperand(0);
1603   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1604     return false;
1605
1606   bool HasRet = false;
1607   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1608        UI != UE; ++UI) {
1609     if (UI->getOpcode() != X86ISD::RET_FLAG)
1610       return false;
1611     HasRet = true;
1612   }
1613
1614   if (!HasRet)
1615     return false;
1616
1617   Chain = TCChain;
1618   return true;
1619 }
1620
1621 EVT
1622 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1623                                             ISD::NodeType ExtendKind) const {
1624   MVT ReturnMVT;
1625   // TODO: Is this also valid on 32-bit?
1626   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1627     ReturnMVT = MVT::i8;
1628   else
1629     ReturnMVT = MVT::i32;
1630
1631   EVT MinVT = getRegisterType(Context, ReturnMVT);
1632   return VT.bitsLT(MinVT) ? MinVT : VT;
1633 }
1634
1635 /// LowerCallResult - Lower the result values of a call into the
1636 /// appropriate copies out of appropriate physical registers.
1637 ///
1638 SDValue
1639 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1640                                    CallingConv::ID CallConv, bool isVarArg,
1641                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1642                                    DebugLoc dl, SelectionDAG &DAG,
1643                                    SmallVectorImpl<SDValue> &InVals) const {
1644
1645   // Assign locations to each value returned by this call.
1646   SmallVector<CCValAssign, 16> RVLocs;
1647   bool Is64Bit = Subtarget->is64Bit();
1648   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1649                  getTargetMachine(), RVLocs, *DAG.getContext());
1650   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1651
1652   // Copy all of the result registers out of their specified physreg.
1653   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1654     CCValAssign &VA = RVLocs[i];
1655     EVT CopyVT = VA.getValVT();
1656
1657     // If this is x86-64, and we disabled SSE, we can't return FP values
1658     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1659         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1660       report_fatal_error("SSE register return with SSE disabled");
1661     }
1662
1663     SDValue Val;
1664
1665     // If this is a call to a function that returns an fp value on the floating
1666     // point stack, we must guarantee the value is popped from the stack, so
1667     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1668     // if the return value is not used. We use the FpPOP_RETVAL instruction
1669     // instead.
1670     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1671       // If we prefer to use the value in xmm registers, copy it out as f80 and
1672       // use a truncate to move it from fp stack reg to xmm reg.
1673       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1674       SDValue Ops[] = { Chain, InFlag };
1675       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1676                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1677       Val = Chain.getValue(0);
1678
1679       // Round the f80 to the right size, which also moves it to the appropriate
1680       // xmm register.
1681       if (CopyVT != VA.getValVT())
1682         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1683                           // This truncation won't change the value.
1684                           DAG.getIntPtrConstant(1));
1685     } else {
1686       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1687                                  CopyVT, InFlag).getValue(1);
1688       Val = Chain.getValue(0);
1689     }
1690     InFlag = Chain.getValue(2);
1691     InVals.push_back(Val);
1692   }
1693
1694   return Chain;
1695 }
1696
1697
1698 //===----------------------------------------------------------------------===//
1699 //                C & StdCall & Fast Calling Convention implementation
1700 //===----------------------------------------------------------------------===//
1701 //  StdCall calling convention seems to be standard for many Windows' API
1702 //  routines and around. It differs from C calling convention just a little:
1703 //  callee should clean up the stack, not caller. Symbols should be also
1704 //  decorated in some fancy way :) It doesn't support any vector arguments.
1705 //  For info on fast calling convention see Fast Calling Convention (tail call)
1706 //  implementation LowerX86_32FastCCCallTo.
1707
1708 /// CallIsStructReturn - Determines whether a call uses struct return
1709 /// semantics.
1710 enum StructReturnType {
1711   NotStructReturn,
1712   RegStructReturn,
1713   StackStructReturn
1714 };
1715 static StructReturnType
1716 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1717   if (Outs.empty())
1718     return NotStructReturn;
1719
1720   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1721   if (!Flags.isSRet())
1722     return NotStructReturn;
1723   if (Flags.isInReg())
1724     return RegStructReturn;
1725   return StackStructReturn;
1726 }
1727
1728 /// ArgsAreStructReturn - Determines whether a function uses struct
1729 /// return semantics.
1730 static StructReturnType
1731 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1732   if (Ins.empty())
1733     return NotStructReturn;
1734
1735   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1736   if (!Flags.isSRet())
1737     return NotStructReturn;
1738   if (Flags.isInReg())
1739     return RegStructReturn;
1740   return StackStructReturn;
1741 }
1742
1743 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1744 /// by "Src" to address "Dst" with size and alignment information specified by
1745 /// the specific parameter attribute. The copy will be passed as a byval
1746 /// function parameter.
1747 static SDValue
1748 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1749                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1750                           DebugLoc dl) {
1751   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1752
1753   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1754                        /*isVolatile*/false, /*AlwaysInline=*/true,
1755                        MachinePointerInfo(), MachinePointerInfo());
1756 }
1757
1758 /// IsTailCallConvention - Return true if the calling convention is one that
1759 /// supports tail call optimization.
1760 static bool IsTailCallConvention(CallingConv::ID CC) {
1761   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1762 }
1763
1764 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1765   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1766     return false;
1767
1768   CallSite CS(CI);
1769   CallingConv::ID CalleeCC = CS.getCallingConv();
1770   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1771     return false;
1772
1773   return true;
1774 }
1775
1776 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1777 /// a tailcall target by changing its ABI.
1778 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1779                                    bool GuaranteedTailCallOpt) {
1780   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1781 }
1782
1783 SDValue
1784 X86TargetLowering::LowerMemArgument(SDValue Chain,
1785                                     CallingConv::ID CallConv,
1786                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1787                                     DebugLoc dl, SelectionDAG &DAG,
1788                                     const CCValAssign &VA,
1789                                     MachineFrameInfo *MFI,
1790                                     unsigned i) const {
1791   // Create the nodes corresponding to a load from this parameter slot.
1792   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1793   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1794                               getTargetMachine().Options.GuaranteedTailCallOpt);
1795   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1796   EVT ValVT;
1797
1798   // If value is passed by pointer we have address passed instead of the value
1799   // itself.
1800   if (VA.getLocInfo() == CCValAssign::Indirect)
1801     ValVT = VA.getLocVT();
1802   else
1803     ValVT = VA.getValVT();
1804
1805   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1806   // changed with more analysis.
1807   // In case of tail call optimization mark all arguments mutable. Since they
1808   // could be overwritten by lowering of arguments in case of a tail call.
1809   if (Flags.isByVal()) {
1810     unsigned Bytes = Flags.getByValSize();
1811     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1812     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1813     return DAG.getFrameIndex(FI, getPointerTy());
1814   } else {
1815     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1816                                     VA.getLocMemOffset(), isImmutable);
1817     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1818     return DAG.getLoad(ValVT, dl, Chain, FIN,
1819                        MachinePointerInfo::getFixedStack(FI),
1820                        false, false, false, 0);
1821   }
1822 }
1823
1824 SDValue
1825 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1826                                         CallingConv::ID CallConv,
1827                                         bool isVarArg,
1828                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1829                                         DebugLoc dl,
1830                                         SelectionDAG &DAG,
1831                                         SmallVectorImpl<SDValue> &InVals)
1832                                           const {
1833   MachineFunction &MF = DAG.getMachineFunction();
1834   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1835
1836   const Function* Fn = MF.getFunction();
1837   if (Fn->hasExternalLinkage() &&
1838       Subtarget->isTargetCygMing() &&
1839       Fn->getName() == "main")
1840     FuncInfo->setForceFramePointer(true);
1841
1842   MachineFrameInfo *MFI = MF.getFrameInfo();
1843   bool Is64Bit = Subtarget->is64Bit();
1844   bool IsWindows = Subtarget->isTargetWindows();
1845   bool IsWin64 = Subtarget->isTargetWin64();
1846
1847   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1848          "Var args not supported with calling convention fastcc or ghc");
1849
1850   // Assign locations to all of the incoming arguments.
1851   SmallVector<CCValAssign, 16> ArgLocs;
1852   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1853                  ArgLocs, *DAG.getContext());
1854
1855   // Allocate shadow area for Win64
1856   if (IsWin64) {
1857     CCInfo.AllocateStack(32, 8);
1858   }
1859
1860   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1861
1862   unsigned LastVal = ~0U;
1863   SDValue ArgValue;
1864   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1865     CCValAssign &VA = ArgLocs[i];
1866     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1867     // places.
1868     assert(VA.getValNo() != LastVal &&
1869            "Don't support value assigned to multiple locs yet");
1870     (void)LastVal;
1871     LastVal = VA.getValNo();
1872
1873     if (VA.isRegLoc()) {
1874       EVT RegVT = VA.getLocVT();
1875       const TargetRegisterClass *RC;
1876       if (RegVT == MVT::i32)
1877         RC = &X86::GR32RegClass;
1878       else if (Is64Bit && RegVT == MVT::i64)
1879         RC = &X86::GR64RegClass;
1880       else if (RegVT == MVT::f32)
1881         RC = &X86::FR32RegClass;
1882       else if (RegVT == MVT::f64)
1883         RC = &X86::FR64RegClass;
1884       else if (RegVT.is256BitVector())
1885         RC = &X86::VR256RegClass;
1886       else if (RegVT.is128BitVector())
1887         RC = &X86::VR128RegClass;
1888       else if (RegVT == MVT::x86mmx)
1889         RC = &X86::VR64RegClass;
1890       else
1891         llvm_unreachable("Unknown argument type!");
1892
1893       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1894       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1895
1896       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1897       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1898       // right size.
1899       if (VA.getLocInfo() == CCValAssign::SExt)
1900         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1901                                DAG.getValueType(VA.getValVT()));
1902       else if (VA.getLocInfo() == CCValAssign::ZExt)
1903         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1904                                DAG.getValueType(VA.getValVT()));
1905       else if (VA.getLocInfo() == CCValAssign::BCvt)
1906         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1907
1908       if (VA.isExtInLoc()) {
1909         // Handle MMX values passed in XMM regs.
1910         if (RegVT.isVector()) {
1911           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1912                                  ArgValue);
1913         } else
1914           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1915       }
1916     } else {
1917       assert(VA.isMemLoc());
1918       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1919     }
1920
1921     // If value is passed via pointer - do a load.
1922     if (VA.getLocInfo() == CCValAssign::Indirect)
1923       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1924                              MachinePointerInfo(), false, false, false, 0);
1925
1926     InVals.push_back(ArgValue);
1927   }
1928
1929   // The x86-64 ABI for returning structs by value requires that we copy
1930   // the sret argument into %rax for the return. Save the argument into
1931   // a virtual register so that we can access it from the return points.
1932   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1933     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1934     unsigned Reg = FuncInfo->getSRetReturnReg();
1935     if (!Reg) {
1936       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1937       FuncInfo->setSRetReturnReg(Reg);
1938     }
1939     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1940     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1941   }
1942
1943   unsigned StackSize = CCInfo.getNextStackOffset();
1944   // Align stack specially for tail calls.
1945   if (FuncIsMadeTailCallSafe(CallConv,
1946                              MF.getTarget().Options.GuaranteedTailCallOpt))
1947     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1948
1949   // If the function takes variable number of arguments, make a frame index for
1950   // the start of the first vararg value... for expansion of llvm.va_start.
1951   if (isVarArg) {
1952     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1953                     CallConv != CallingConv::X86_ThisCall)) {
1954       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1955     }
1956     if (Is64Bit) {
1957       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1958
1959       // FIXME: We should really autogenerate these arrays
1960       static const uint16_t GPR64ArgRegsWin64[] = {
1961         X86::RCX, X86::RDX, X86::R8,  X86::R9
1962       };
1963       static const uint16_t GPR64ArgRegs64Bit[] = {
1964         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1965       };
1966       static const uint16_t XMMArgRegs64Bit[] = {
1967         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1968         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1969       };
1970       const uint16_t *GPR64ArgRegs;
1971       unsigned NumXMMRegs = 0;
1972
1973       if (IsWin64) {
1974         // The XMM registers which might contain var arg parameters are shadowed
1975         // in their paired GPR.  So we only need to save the GPR to their home
1976         // slots.
1977         TotalNumIntRegs = 4;
1978         GPR64ArgRegs = GPR64ArgRegsWin64;
1979       } else {
1980         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1981         GPR64ArgRegs = GPR64ArgRegs64Bit;
1982
1983         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1984                                                 TotalNumXMMRegs);
1985       }
1986       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1987                                                        TotalNumIntRegs);
1988
1989       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1990       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1991              "SSE register cannot be used when SSE is disabled!");
1992       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1993                NoImplicitFloatOps) &&
1994              "SSE register cannot be used when SSE is disabled!");
1995       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1996           !Subtarget->hasSSE1())
1997         // Kernel mode asks for SSE to be disabled, so don't push them
1998         // on the stack.
1999         TotalNumXMMRegs = 0;
2000
2001       if (IsWin64) {
2002         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2003         // Get to the caller-allocated home save location.  Add 8 to account
2004         // for the return address.
2005         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2006         FuncInfo->setRegSaveFrameIndex(
2007           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2008         // Fixup to set vararg frame on shadow area (4 x i64).
2009         if (NumIntRegs < 4)
2010           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2011       } else {
2012         // For X86-64, if there are vararg parameters that are passed via
2013         // registers, then we must store them to their spots on the stack so
2014         // they may be loaded by deferencing the result of va_next.
2015         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2016         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2017         FuncInfo->setRegSaveFrameIndex(
2018           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2019                                false));
2020       }
2021
2022       // Store the integer parameter registers.
2023       SmallVector<SDValue, 8> MemOps;
2024       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2025                                         getPointerTy());
2026       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2027       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2028         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2029                                   DAG.getIntPtrConstant(Offset));
2030         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2031                                      &X86::GR64RegClass);
2032         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2033         SDValue Store =
2034           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2035                        MachinePointerInfo::getFixedStack(
2036                          FuncInfo->getRegSaveFrameIndex(), Offset),
2037                        false, false, 0);
2038         MemOps.push_back(Store);
2039         Offset += 8;
2040       }
2041
2042       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2043         // Now store the XMM (fp + vector) parameter registers.
2044         SmallVector<SDValue, 11> SaveXMMOps;
2045         SaveXMMOps.push_back(Chain);
2046
2047         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2048         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2049         SaveXMMOps.push_back(ALVal);
2050
2051         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2052                                FuncInfo->getRegSaveFrameIndex()));
2053         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2054                                FuncInfo->getVarArgsFPOffset()));
2055
2056         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2057           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2058                                        &X86::VR128RegClass);
2059           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2060           SaveXMMOps.push_back(Val);
2061         }
2062         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2063                                      MVT::Other,
2064                                      &SaveXMMOps[0], SaveXMMOps.size()));
2065       }
2066
2067       if (!MemOps.empty())
2068         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2069                             &MemOps[0], MemOps.size());
2070     }
2071   }
2072
2073   // Some CCs need callee pop.
2074   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2075                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2076     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2077   } else {
2078     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2079     // If this is an sret function, the return should pop the hidden pointer.
2080     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2081         argsAreStructReturn(Ins) == StackStructReturn)
2082       FuncInfo->setBytesToPopOnReturn(4);
2083   }
2084
2085   if (!Is64Bit) {
2086     // RegSaveFrameIndex is X86-64 only.
2087     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2088     if (CallConv == CallingConv::X86_FastCall ||
2089         CallConv == CallingConv::X86_ThisCall)
2090       // fastcc functions can't have varargs.
2091       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2092   }
2093
2094   FuncInfo->setArgumentStackSize(StackSize);
2095
2096   return Chain;
2097 }
2098
2099 SDValue
2100 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2101                                     SDValue StackPtr, SDValue Arg,
2102                                     DebugLoc dl, SelectionDAG &DAG,
2103                                     const CCValAssign &VA,
2104                                     ISD::ArgFlagsTy Flags) const {
2105   unsigned LocMemOffset = VA.getLocMemOffset();
2106   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2107   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2108   if (Flags.isByVal())
2109     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2110
2111   return DAG.getStore(Chain, dl, Arg, PtrOff,
2112                       MachinePointerInfo::getStack(LocMemOffset),
2113                       false, false, 0);
2114 }
2115
2116 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2117 /// optimization is performed and it is required.
2118 SDValue
2119 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2120                                            SDValue &OutRetAddr, SDValue Chain,
2121                                            bool IsTailCall, bool Is64Bit,
2122                                            int FPDiff, DebugLoc dl) const {
2123   // Adjust the Return address stack slot.
2124   EVT VT = getPointerTy();
2125   OutRetAddr = getReturnAddressFrameIndex(DAG);
2126
2127   // Load the "old" Return address.
2128   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2129                            false, false, false, 0);
2130   return SDValue(OutRetAddr.getNode(), 1);
2131 }
2132
2133 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2134 /// optimization is performed and it is required (FPDiff!=0).
2135 static SDValue
2136 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2137                          SDValue Chain, SDValue RetAddrFrIdx,
2138                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2139   // Store the return address to the appropriate stack slot.
2140   if (!FPDiff) return Chain;
2141   // Calculate the new stack slot for the return address.
2142   int SlotSize = Is64Bit ? 8 : 4;
2143   int NewReturnAddrFI =
2144     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2145   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2146   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2147   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2148                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2149                        false, false, 0);
2150   return Chain;
2151 }
2152
2153 SDValue
2154 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2155                              SmallVectorImpl<SDValue> &InVals) const {
2156   SelectionDAG &DAG                     = CLI.DAG;
2157   DebugLoc &dl                          = CLI.DL;
2158   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2159   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2160   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2161   SDValue Chain                         = CLI.Chain;
2162   SDValue Callee                        = CLI.Callee;
2163   CallingConv::ID CallConv              = CLI.CallConv;
2164   bool &isTailCall                      = CLI.IsTailCall;
2165   bool isVarArg                         = CLI.IsVarArg;
2166
2167   MachineFunction &MF = DAG.getMachineFunction();
2168   bool Is64Bit        = Subtarget->is64Bit();
2169   bool IsWin64        = Subtarget->isTargetWin64();
2170   bool IsWindows      = Subtarget->isTargetWindows();
2171   StructReturnType SR = callIsStructReturn(Outs);
2172   bool IsSibcall      = false;
2173
2174   if (MF.getTarget().Options.DisableTailCalls)
2175     isTailCall = false;
2176
2177   if (isTailCall) {
2178     // Check if it's really possible to do a tail call.
2179     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2180                     isVarArg, SR != NotStructReturn,
2181                     MF.getFunction()->hasStructRetAttr(),
2182                     Outs, OutVals, Ins, DAG);
2183
2184     // Sibcalls are automatically detected tailcalls which do not require
2185     // ABI changes.
2186     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2187       IsSibcall = true;
2188
2189     if (isTailCall)
2190       ++NumTailCalls;
2191   }
2192
2193   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2194          "Var args not supported with calling convention fastcc or ghc");
2195
2196   // Analyze operands of the call, assigning locations to each operand.
2197   SmallVector<CCValAssign, 16> ArgLocs;
2198   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2199                  ArgLocs, *DAG.getContext());
2200
2201   // Allocate shadow area for Win64
2202   if (IsWin64) {
2203     CCInfo.AllocateStack(32, 8);
2204   }
2205
2206   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2207
2208   // Get a count of how many bytes are to be pushed on the stack.
2209   unsigned NumBytes = CCInfo.getNextStackOffset();
2210   if (IsSibcall)
2211     // This is a sibcall. The memory operands are available in caller's
2212     // own caller's stack.
2213     NumBytes = 0;
2214   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2215            IsTailCallConvention(CallConv))
2216     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2217
2218   int FPDiff = 0;
2219   if (isTailCall && !IsSibcall) {
2220     // Lower arguments at fp - stackoffset + fpdiff.
2221     unsigned NumBytesCallerPushed =
2222       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2223     FPDiff = NumBytesCallerPushed - NumBytes;
2224
2225     // Set the delta of movement of the returnaddr stackslot.
2226     // But only set if delta is greater than previous delta.
2227     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2228       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2229   }
2230
2231   if (!IsSibcall)
2232     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2233
2234   SDValue RetAddrFrIdx;
2235   // Load return address for tail calls.
2236   if (isTailCall && FPDiff)
2237     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2238                                     Is64Bit, FPDiff, dl);
2239
2240   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2241   SmallVector<SDValue, 8> MemOpChains;
2242   SDValue StackPtr;
2243
2244   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2245   // of tail call optimization arguments are handle later.
2246   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2247     CCValAssign &VA = ArgLocs[i];
2248     EVT RegVT = VA.getLocVT();
2249     SDValue Arg = OutVals[i];
2250     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2251     bool isByVal = Flags.isByVal();
2252
2253     // Promote the value if needed.
2254     switch (VA.getLocInfo()) {
2255     default: llvm_unreachable("Unknown loc info!");
2256     case CCValAssign::Full: break;
2257     case CCValAssign::SExt:
2258       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2259       break;
2260     case CCValAssign::ZExt:
2261       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2262       break;
2263     case CCValAssign::AExt:
2264       if (RegVT.is128BitVector()) {
2265         // Special case: passing MMX values in XMM registers.
2266         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2267         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2268         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2269       } else
2270         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2271       break;
2272     case CCValAssign::BCvt:
2273       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2274       break;
2275     case CCValAssign::Indirect: {
2276       // Store the argument.
2277       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2278       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2279       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2280                            MachinePointerInfo::getFixedStack(FI),
2281                            false, false, 0);
2282       Arg = SpillSlot;
2283       break;
2284     }
2285     }
2286
2287     if (VA.isRegLoc()) {
2288       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2289       if (isVarArg && IsWin64) {
2290         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2291         // shadow reg if callee is a varargs function.
2292         unsigned ShadowReg = 0;
2293         switch (VA.getLocReg()) {
2294         case X86::XMM0: ShadowReg = X86::RCX; break;
2295         case X86::XMM1: ShadowReg = X86::RDX; break;
2296         case X86::XMM2: ShadowReg = X86::R8; break;
2297         case X86::XMM3: ShadowReg = X86::R9; break;
2298         }
2299         if (ShadowReg)
2300           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2301       }
2302     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2303       assert(VA.isMemLoc());
2304       if (StackPtr.getNode() == 0)
2305         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2306       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2307                                              dl, DAG, VA, Flags));
2308     }
2309   }
2310
2311   if (!MemOpChains.empty())
2312     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2313                         &MemOpChains[0], MemOpChains.size());
2314
2315   if (Subtarget->isPICStyleGOT()) {
2316     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2317     // GOT pointer.
2318     if (!isTailCall) {
2319       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2320                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2321     } else {
2322       // If we are tail calling and generating PIC/GOT style code load the
2323       // address of the callee into ECX. The value in ecx is used as target of
2324       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2325       // for tail calls on PIC/GOT architectures. Normally we would just put the
2326       // address of GOT into ebx and then call target@PLT. But for tail calls
2327       // ebx would be restored (since ebx is callee saved) before jumping to the
2328       // target@PLT.
2329
2330       // Note: The actual moving to ECX is done further down.
2331       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2332       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2333           !G->getGlobal()->hasProtectedVisibility())
2334         Callee = LowerGlobalAddress(Callee, DAG);
2335       else if (isa<ExternalSymbolSDNode>(Callee))
2336         Callee = LowerExternalSymbol(Callee, DAG);
2337     }
2338   }
2339
2340   if (Is64Bit && isVarArg && !IsWin64) {
2341     // From AMD64 ABI document:
2342     // For calls that may call functions that use varargs or stdargs
2343     // (prototype-less calls or calls to functions containing ellipsis (...) in
2344     // the declaration) %al is used as hidden argument to specify the number
2345     // of SSE registers used. The contents of %al do not need to match exactly
2346     // the number of registers, but must be an ubound on the number of SSE
2347     // registers used and is in the range 0 - 8 inclusive.
2348
2349     // Count the number of XMM registers allocated.
2350     static const uint16_t XMMArgRegs[] = {
2351       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2352       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2353     };
2354     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2355     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2356            && "SSE registers cannot be used when SSE is disabled");
2357
2358     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2359                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2360   }
2361
2362   // For tail calls lower the arguments to the 'real' stack slot.
2363   if (isTailCall) {
2364     // Force all the incoming stack arguments to be loaded from the stack
2365     // before any new outgoing arguments are stored to the stack, because the
2366     // outgoing stack slots may alias the incoming argument stack slots, and
2367     // the alias isn't otherwise explicit. This is slightly more conservative
2368     // than necessary, because it means that each store effectively depends
2369     // on every argument instead of just those arguments it would clobber.
2370     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2371
2372     SmallVector<SDValue, 8> MemOpChains2;
2373     SDValue FIN;
2374     int FI = 0;
2375     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2376       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2377         CCValAssign &VA = ArgLocs[i];
2378         if (VA.isRegLoc())
2379           continue;
2380         assert(VA.isMemLoc());
2381         SDValue Arg = OutVals[i];
2382         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2383         // Create frame index.
2384         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2385         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2386         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2387         FIN = DAG.getFrameIndex(FI, getPointerTy());
2388
2389         if (Flags.isByVal()) {
2390           // Copy relative to framepointer.
2391           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2392           if (StackPtr.getNode() == 0)
2393             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2394                                           getPointerTy());
2395           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2396
2397           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2398                                                            ArgChain,
2399                                                            Flags, DAG, dl));
2400         } else {
2401           // Store relative to framepointer.
2402           MemOpChains2.push_back(
2403             DAG.getStore(ArgChain, dl, Arg, FIN,
2404                          MachinePointerInfo::getFixedStack(FI),
2405                          false, false, 0));
2406         }
2407       }
2408     }
2409
2410     if (!MemOpChains2.empty())
2411       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2412                           &MemOpChains2[0], MemOpChains2.size());
2413
2414     // Store the return address to the appropriate stack slot.
2415     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2416                                      FPDiff, dl);
2417   }
2418
2419   // Build a sequence of copy-to-reg nodes chained together with token chain
2420   // and flag operands which copy the outgoing args into registers.
2421   SDValue InFlag;
2422   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2423     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2424                              RegsToPass[i].second, InFlag);
2425     InFlag = Chain.getValue(1);
2426   }
2427
2428   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2429     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2430     // In the 64-bit large code model, we have to make all calls
2431     // through a register, since the call instruction's 32-bit
2432     // pc-relative offset may not be large enough to hold the whole
2433     // address.
2434   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2435     // If the callee is a GlobalAddress node (quite common, every direct call
2436     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2437     // it.
2438
2439     // We should use extra load for direct calls to dllimported functions in
2440     // non-JIT mode.
2441     const GlobalValue *GV = G->getGlobal();
2442     if (!GV->hasDLLImportLinkage()) {
2443       unsigned char OpFlags = 0;
2444       bool ExtraLoad = false;
2445       unsigned WrapperKind = ISD::DELETED_NODE;
2446
2447       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2448       // external symbols most go through the PLT in PIC mode.  If the symbol
2449       // has hidden or protected visibility, or if it is static or local, then
2450       // we don't need to use the PLT - we can directly call it.
2451       if (Subtarget->isTargetELF() &&
2452           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2453           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2454         OpFlags = X86II::MO_PLT;
2455       } else if (Subtarget->isPICStyleStubAny() &&
2456                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2457                  (!Subtarget->getTargetTriple().isMacOSX() ||
2458                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2459         // PC-relative references to external symbols should go through $stub,
2460         // unless we're building with the leopard linker or later, which
2461         // automatically synthesizes these stubs.
2462         OpFlags = X86II::MO_DARWIN_STUB;
2463       } else if (Subtarget->isPICStyleRIPRel() &&
2464                  isa<Function>(GV) &&
2465                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2466         // If the function is marked as non-lazy, generate an indirect call
2467         // which loads from the GOT directly. This avoids runtime overhead
2468         // at the cost of eager binding (and one extra byte of encoding).
2469         OpFlags = X86II::MO_GOTPCREL;
2470         WrapperKind = X86ISD::WrapperRIP;
2471         ExtraLoad = true;
2472       }
2473
2474       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2475                                           G->getOffset(), OpFlags);
2476
2477       // Add a wrapper if needed.
2478       if (WrapperKind != ISD::DELETED_NODE)
2479         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2480       // Add extra indirection if needed.
2481       if (ExtraLoad)
2482         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2483                              MachinePointerInfo::getGOT(),
2484                              false, false, false, 0);
2485     }
2486   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2487     unsigned char OpFlags = 0;
2488
2489     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2490     // external symbols should go through the PLT.
2491     if (Subtarget->isTargetELF() &&
2492         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2493       OpFlags = X86II::MO_PLT;
2494     } else if (Subtarget->isPICStyleStubAny() &&
2495                (!Subtarget->getTargetTriple().isMacOSX() ||
2496                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2497       // PC-relative references to external symbols should go through $stub,
2498       // unless we're building with the leopard linker or later, which
2499       // automatically synthesizes these stubs.
2500       OpFlags = X86II::MO_DARWIN_STUB;
2501     }
2502
2503     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2504                                          OpFlags);
2505   }
2506
2507   // Returns a chain & a flag for retval copy to use.
2508   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2509   SmallVector<SDValue, 8> Ops;
2510
2511   if (!IsSibcall && isTailCall) {
2512     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2513                            DAG.getIntPtrConstant(0, true), InFlag);
2514     InFlag = Chain.getValue(1);
2515   }
2516
2517   Ops.push_back(Chain);
2518   Ops.push_back(Callee);
2519
2520   if (isTailCall)
2521     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2522
2523   // Add argument registers to the end of the list so that they are known live
2524   // into the call.
2525   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2526     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2527                                   RegsToPass[i].second.getValueType()));
2528
2529   // Add a register mask operand representing the call-preserved registers.
2530   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2531   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2532   assert(Mask && "Missing call preserved mask for calling convention");
2533   Ops.push_back(DAG.getRegisterMask(Mask));
2534
2535   if (InFlag.getNode())
2536     Ops.push_back(InFlag);
2537
2538   if (isTailCall) {
2539     // We used to do:
2540     //// If this is the first return lowered for this function, add the regs
2541     //// to the liveout set for the function.
2542     // This isn't right, although it's probably harmless on x86; liveouts
2543     // should be computed from returns not tail calls.  Consider a void
2544     // function making a tail call to a function returning int.
2545     return DAG.getNode(X86ISD::TC_RETURN, dl,
2546                        NodeTys, &Ops[0], Ops.size());
2547   }
2548
2549   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2550   InFlag = Chain.getValue(1);
2551
2552   // Create the CALLSEQ_END node.
2553   unsigned NumBytesForCalleeToPush;
2554   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2555                        getTargetMachine().Options.GuaranteedTailCallOpt))
2556     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2557   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2558            SR == StackStructReturn)
2559     // If this is a call to a struct-return function, the callee
2560     // pops the hidden struct pointer, so we have to push it back.
2561     // This is common for Darwin/X86, Linux & Mingw32 targets.
2562     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2563     NumBytesForCalleeToPush = 4;
2564   else
2565     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2566
2567   // Returns a flag for retval copy to use.
2568   if (!IsSibcall) {
2569     Chain = DAG.getCALLSEQ_END(Chain,
2570                                DAG.getIntPtrConstant(NumBytes, true),
2571                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2572                                                      true),
2573                                InFlag);
2574     InFlag = Chain.getValue(1);
2575   }
2576
2577   // Handle result values, copying them out of physregs into vregs that we
2578   // return.
2579   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2580                          Ins, dl, DAG, InVals);
2581 }
2582
2583
2584 //===----------------------------------------------------------------------===//
2585 //                Fast Calling Convention (tail call) implementation
2586 //===----------------------------------------------------------------------===//
2587
2588 //  Like std call, callee cleans arguments, convention except that ECX is
2589 //  reserved for storing the tail called function address. Only 2 registers are
2590 //  free for argument passing (inreg). Tail call optimization is performed
2591 //  provided:
2592 //                * tailcallopt is enabled
2593 //                * caller/callee are fastcc
2594 //  On X86_64 architecture with GOT-style position independent code only local
2595 //  (within module) calls are supported at the moment.
2596 //  To keep the stack aligned according to platform abi the function
2597 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2598 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2599 //  If a tail called function callee has more arguments than the caller the
2600 //  caller needs to make sure that there is room to move the RETADDR to. This is
2601 //  achieved by reserving an area the size of the argument delta right after the
2602 //  original REtADDR, but before the saved framepointer or the spilled registers
2603 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2604 //  stack layout:
2605 //    arg1
2606 //    arg2
2607 //    RETADDR
2608 //    [ new RETADDR
2609 //      move area ]
2610 //    (possible EBP)
2611 //    ESI
2612 //    EDI
2613 //    local1 ..
2614
2615 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2616 /// for a 16 byte align requirement.
2617 unsigned
2618 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2619                                                SelectionDAG& DAG) const {
2620   MachineFunction &MF = DAG.getMachineFunction();
2621   const TargetMachine &TM = MF.getTarget();
2622   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2623   unsigned StackAlignment = TFI.getStackAlignment();
2624   uint64_t AlignMask = StackAlignment - 1;
2625   int64_t Offset = StackSize;
2626   uint64_t SlotSize = TD->getPointerSize();
2627   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2628     // Number smaller than 12 so just add the difference.
2629     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2630   } else {
2631     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2632     Offset = ((~AlignMask) & Offset) + StackAlignment +
2633       (StackAlignment-SlotSize);
2634   }
2635   return Offset;
2636 }
2637
2638 /// MatchingStackOffset - Return true if the given stack call argument is
2639 /// already available in the same position (relatively) of the caller's
2640 /// incoming argument stack.
2641 static
2642 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2643                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2644                          const X86InstrInfo *TII) {
2645   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2646   int FI = INT_MAX;
2647   if (Arg.getOpcode() == ISD::CopyFromReg) {
2648     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2649     if (!TargetRegisterInfo::isVirtualRegister(VR))
2650       return false;
2651     MachineInstr *Def = MRI->getVRegDef(VR);
2652     if (!Def)
2653       return false;
2654     if (!Flags.isByVal()) {
2655       if (!TII->isLoadFromStackSlot(Def, FI))
2656         return false;
2657     } else {
2658       unsigned Opcode = Def->getOpcode();
2659       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2660           Def->getOperand(1).isFI()) {
2661         FI = Def->getOperand(1).getIndex();
2662         Bytes = Flags.getByValSize();
2663       } else
2664         return false;
2665     }
2666   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2667     if (Flags.isByVal())
2668       // ByVal argument is passed in as a pointer but it's now being
2669       // dereferenced. e.g.
2670       // define @foo(%struct.X* %A) {
2671       //   tail call @bar(%struct.X* byval %A)
2672       // }
2673       return false;
2674     SDValue Ptr = Ld->getBasePtr();
2675     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2676     if (!FINode)
2677       return false;
2678     FI = FINode->getIndex();
2679   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2680     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2681     FI = FINode->getIndex();
2682     Bytes = Flags.getByValSize();
2683   } else
2684     return false;
2685
2686   assert(FI != INT_MAX);
2687   if (!MFI->isFixedObjectIndex(FI))
2688     return false;
2689   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2690 }
2691
2692 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2693 /// for tail call optimization. Targets which want to do tail call
2694 /// optimization should implement this function.
2695 bool
2696 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2697                                                      CallingConv::ID CalleeCC,
2698                                                      bool isVarArg,
2699                                                      bool isCalleeStructRet,
2700                                                      bool isCallerStructRet,
2701                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2702                                     const SmallVectorImpl<SDValue> &OutVals,
2703                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2704                                                      SelectionDAG& DAG) const {
2705   if (!IsTailCallConvention(CalleeCC) &&
2706       CalleeCC != CallingConv::C)
2707     return false;
2708
2709   // If -tailcallopt is specified, make fastcc functions tail-callable.
2710   const MachineFunction &MF = DAG.getMachineFunction();
2711   const Function *CallerF = DAG.getMachineFunction().getFunction();
2712   CallingConv::ID CallerCC = CallerF->getCallingConv();
2713   bool CCMatch = CallerCC == CalleeCC;
2714
2715   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2716     if (IsTailCallConvention(CalleeCC) && CCMatch)
2717       return true;
2718     return false;
2719   }
2720
2721   // Look for obvious safe cases to perform tail call optimization that do not
2722   // require ABI changes. This is what gcc calls sibcall.
2723
2724   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2725   // emit a special epilogue.
2726   if (RegInfo->needsStackRealignment(MF))
2727     return false;
2728
2729   // Also avoid sibcall optimization if either caller or callee uses struct
2730   // return semantics.
2731   if (isCalleeStructRet || isCallerStructRet)
2732     return false;
2733
2734   // An stdcall caller is expected to clean up its arguments; the callee
2735   // isn't going to do that.
2736   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2737     return false;
2738
2739   // Do not sibcall optimize vararg calls unless all arguments are passed via
2740   // registers.
2741   if (isVarArg && !Outs.empty()) {
2742
2743     // Optimizing for varargs on Win64 is unlikely to be safe without
2744     // additional testing.
2745     if (Subtarget->isTargetWin64())
2746       return false;
2747
2748     SmallVector<CCValAssign, 16> ArgLocs;
2749     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2750                    getTargetMachine(), ArgLocs, *DAG.getContext());
2751
2752     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2753     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2754       if (!ArgLocs[i].isRegLoc())
2755         return false;
2756   }
2757
2758   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2759   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2760   // this into a sibcall.
2761   bool Unused = false;
2762   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2763     if (!Ins[i].Used) {
2764       Unused = true;
2765       break;
2766     }
2767   }
2768   if (Unused) {
2769     SmallVector<CCValAssign, 16> RVLocs;
2770     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2771                    getTargetMachine(), RVLocs, *DAG.getContext());
2772     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2773     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2774       CCValAssign &VA = RVLocs[i];
2775       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2776         return false;
2777     }
2778   }
2779
2780   // If the calling conventions do not match, then we'd better make sure the
2781   // results are returned in the same way as what the caller expects.
2782   if (!CCMatch) {
2783     SmallVector<CCValAssign, 16> RVLocs1;
2784     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2785                     getTargetMachine(), RVLocs1, *DAG.getContext());
2786     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2787
2788     SmallVector<CCValAssign, 16> RVLocs2;
2789     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2790                     getTargetMachine(), RVLocs2, *DAG.getContext());
2791     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2792
2793     if (RVLocs1.size() != RVLocs2.size())
2794       return false;
2795     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2796       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2797         return false;
2798       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2799         return false;
2800       if (RVLocs1[i].isRegLoc()) {
2801         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2802           return false;
2803       } else {
2804         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2805           return false;
2806       }
2807     }
2808   }
2809
2810   // If the callee takes no arguments then go on to check the results of the
2811   // call.
2812   if (!Outs.empty()) {
2813     // Check if stack adjustment is needed. For now, do not do this if any
2814     // argument is passed on the stack.
2815     SmallVector<CCValAssign, 16> ArgLocs;
2816     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2817                    getTargetMachine(), ArgLocs, *DAG.getContext());
2818
2819     // Allocate shadow area for Win64
2820     if (Subtarget->isTargetWin64()) {
2821       CCInfo.AllocateStack(32, 8);
2822     }
2823
2824     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2825     if (CCInfo.getNextStackOffset()) {
2826       MachineFunction &MF = DAG.getMachineFunction();
2827       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2828         return false;
2829
2830       // Check if the arguments are already laid out in the right way as
2831       // the caller's fixed stack objects.
2832       MachineFrameInfo *MFI = MF.getFrameInfo();
2833       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2834       const X86InstrInfo *TII =
2835         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2836       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2837         CCValAssign &VA = ArgLocs[i];
2838         SDValue Arg = OutVals[i];
2839         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2840         if (VA.getLocInfo() == CCValAssign::Indirect)
2841           return false;
2842         if (!VA.isRegLoc()) {
2843           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2844                                    MFI, MRI, TII))
2845             return false;
2846         }
2847       }
2848     }
2849
2850     // If the tailcall address may be in a register, then make sure it's
2851     // possible to register allocate for it. In 32-bit, the call address can
2852     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2853     // callee-saved registers are restored. These happen to be the same
2854     // registers used to pass 'inreg' arguments so watch out for those.
2855     if (!Subtarget->is64Bit() &&
2856         !isa<GlobalAddressSDNode>(Callee) &&
2857         !isa<ExternalSymbolSDNode>(Callee)) {
2858       unsigned NumInRegs = 0;
2859       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2860         CCValAssign &VA = ArgLocs[i];
2861         if (!VA.isRegLoc())
2862           continue;
2863         unsigned Reg = VA.getLocReg();
2864         switch (Reg) {
2865         default: break;
2866         case X86::EAX: case X86::EDX: case X86::ECX:
2867           if (++NumInRegs == 3)
2868             return false;
2869           break;
2870         }
2871       }
2872     }
2873   }
2874
2875   return true;
2876 }
2877
2878 FastISel *
2879 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2880                                   const TargetLibraryInfo *libInfo) const {
2881   return X86::createFastISel(funcInfo, libInfo);
2882 }
2883
2884
2885 //===----------------------------------------------------------------------===//
2886 //                           Other Lowering Hooks
2887 //===----------------------------------------------------------------------===//
2888
2889 static bool MayFoldLoad(SDValue Op) {
2890   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2891 }
2892
2893 static bool MayFoldIntoStore(SDValue Op) {
2894   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2895 }
2896
2897 static bool isTargetShuffle(unsigned Opcode) {
2898   switch(Opcode) {
2899   default: return false;
2900   case X86ISD::PSHUFD:
2901   case X86ISD::PSHUFHW:
2902   case X86ISD::PSHUFLW:
2903   case X86ISD::SHUFP:
2904   case X86ISD::PALIGN:
2905   case X86ISD::MOVLHPS:
2906   case X86ISD::MOVLHPD:
2907   case X86ISD::MOVHLPS:
2908   case X86ISD::MOVLPS:
2909   case X86ISD::MOVLPD:
2910   case X86ISD::MOVSHDUP:
2911   case X86ISD::MOVSLDUP:
2912   case X86ISD::MOVDDUP:
2913   case X86ISD::MOVSS:
2914   case X86ISD::MOVSD:
2915   case X86ISD::UNPCKL:
2916   case X86ISD::UNPCKH:
2917   case X86ISD::VPERMILP:
2918   case X86ISD::VPERM2X128:
2919   case X86ISD::VPERMI:
2920     return true;
2921   }
2922 }
2923
2924 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2925                                     SDValue V1, SelectionDAG &DAG) {
2926   switch(Opc) {
2927   default: llvm_unreachable("Unknown x86 shuffle node");
2928   case X86ISD::MOVSHDUP:
2929   case X86ISD::MOVSLDUP:
2930   case X86ISD::MOVDDUP:
2931     return DAG.getNode(Opc, dl, VT, V1);
2932   }
2933 }
2934
2935 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2936                                     SDValue V1, unsigned TargetMask,
2937                                     SelectionDAG &DAG) {
2938   switch(Opc) {
2939   default: llvm_unreachable("Unknown x86 shuffle node");
2940   case X86ISD::PSHUFD:
2941   case X86ISD::PSHUFHW:
2942   case X86ISD::PSHUFLW:
2943   case X86ISD::VPERMILP:
2944   case X86ISD::VPERMI:
2945     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2946   }
2947 }
2948
2949 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2950                                     SDValue V1, SDValue V2, unsigned TargetMask,
2951                                     SelectionDAG &DAG) {
2952   switch(Opc) {
2953   default: llvm_unreachable("Unknown x86 shuffle node");
2954   case X86ISD::PALIGN:
2955   case X86ISD::SHUFP:
2956   case X86ISD::VPERM2X128:
2957     return DAG.getNode(Opc, dl, VT, V1, V2,
2958                        DAG.getConstant(TargetMask, MVT::i8));
2959   }
2960 }
2961
2962 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2963                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2964   switch(Opc) {
2965   default: llvm_unreachable("Unknown x86 shuffle node");
2966   case X86ISD::MOVLHPS:
2967   case X86ISD::MOVLHPD:
2968   case X86ISD::MOVHLPS:
2969   case X86ISD::MOVLPS:
2970   case X86ISD::MOVLPD:
2971   case X86ISD::MOVSS:
2972   case X86ISD::MOVSD:
2973   case X86ISD::UNPCKL:
2974   case X86ISD::UNPCKH:
2975     return DAG.getNode(Opc, dl, VT, V1, V2);
2976   }
2977 }
2978
2979 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2980   MachineFunction &MF = DAG.getMachineFunction();
2981   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2982   int ReturnAddrIndex = FuncInfo->getRAIndex();
2983
2984   if (ReturnAddrIndex == 0) {
2985     // Set up a frame object for the return address.
2986     uint64_t SlotSize = TD->getPointerSize();
2987     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2988                                                            false);
2989     FuncInfo->setRAIndex(ReturnAddrIndex);
2990   }
2991
2992   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2993 }
2994
2995
2996 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2997                                        bool hasSymbolicDisplacement) {
2998   // Offset should fit into 32 bit immediate field.
2999   if (!isInt<32>(Offset))
3000     return false;
3001
3002   // If we don't have a symbolic displacement - we don't have any extra
3003   // restrictions.
3004   if (!hasSymbolicDisplacement)
3005     return true;
3006
3007   // FIXME: Some tweaks might be needed for medium code model.
3008   if (M != CodeModel::Small && M != CodeModel::Kernel)
3009     return false;
3010
3011   // For small code model we assume that latest object is 16MB before end of 31
3012   // bits boundary. We may also accept pretty large negative constants knowing
3013   // that all objects are in the positive half of address space.
3014   if (M == CodeModel::Small && Offset < 16*1024*1024)
3015     return true;
3016
3017   // For kernel code model we know that all object resist in the negative half
3018   // of 32bits address space. We may not accept negative offsets, since they may
3019   // be just off and we may accept pretty large positive ones.
3020   if (M == CodeModel::Kernel && Offset > 0)
3021     return true;
3022
3023   return false;
3024 }
3025
3026 /// isCalleePop - Determines whether the callee is required to pop its
3027 /// own arguments. Callee pop is necessary to support tail calls.
3028 bool X86::isCalleePop(CallingConv::ID CallingConv,
3029                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3030   if (IsVarArg)
3031     return false;
3032
3033   switch (CallingConv) {
3034   default:
3035     return false;
3036   case CallingConv::X86_StdCall:
3037     return !is64Bit;
3038   case CallingConv::X86_FastCall:
3039     return !is64Bit;
3040   case CallingConv::X86_ThisCall:
3041     return !is64Bit;
3042   case CallingConv::Fast:
3043     return TailCallOpt;
3044   case CallingConv::GHC:
3045     return TailCallOpt;
3046   }
3047 }
3048
3049 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3050 /// specific condition code, returning the condition code and the LHS/RHS of the
3051 /// comparison to make.
3052 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3053                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3054   if (!isFP) {
3055     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3056       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3057         // X > -1   -> X == 0, jump !sign.
3058         RHS = DAG.getConstant(0, RHS.getValueType());
3059         return X86::COND_NS;
3060       }
3061       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3062         // X < 0   -> X == 0, jump on sign.
3063         return X86::COND_S;
3064       }
3065       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3066         // X < 1   -> X <= 0
3067         RHS = DAG.getConstant(0, RHS.getValueType());
3068         return X86::COND_LE;
3069       }
3070     }
3071
3072     switch (SetCCOpcode) {
3073     default: llvm_unreachable("Invalid integer condition!");
3074     case ISD::SETEQ:  return X86::COND_E;
3075     case ISD::SETGT:  return X86::COND_G;
3076     case ISD::SETGE:  return X86::COND_GE;
3077     case ISD::SETLT:  return X86::COND_L;
3078     case ISD::SETLE:  return X86::COND_LE;
3079     case ISD::SETNE:  return X86::COND_NE;
3080     case ISD::SETULT: return X86::COND_B;
3081     case ISD::SETUGT: return X86::COND_A;
3082     case ISD::SETULE: return X86::COND_BE;
3083     case ISD::SETUGE: return X86::COND_AE;
3084     }
3085   }
3086
3087   // First determine if it is required or is profitable to flip the operands.
3088
3089   // If LHS is a foldable load, but RHS is not, flip the condition.
3090   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3091       !ISD::isNON_EXTLoad(RHS.getNode())) {
3092     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3093     std::swap(LHS, RHS);
3094   }
3095
3096   switch (SetCCOpcode) {
3097   default: break;
3098   case ISD::SETOLT:
3099   case ISD::SETOLE:
3100   case ISD::SETUGT:
3101   case ISD::SETUGE:
3102     std::swap(LHS, RHS);
3103     break;
3104   }
3105
3106   // On a floating point condition, the flags are set as follows:
3107   // ZF  PF  CF   op
3108   //  0 | 0 | 0 | X > Y
3109   //  0 | 0 | 1 | X < Y
3110   //  1 | 0 | 0 | X == Y
3111   //  1 | 1 | 1 | unordered
3112   switch (SetCCOpcode) {
3113   default: llvm_unreachable("Condcode should be pre-legalized away");
3114   case ISD::SETUEQ:
3115   case ISD::SETEQ:   return X86::COND_E;
3116   case ISD::SETOLT:              // flipped
3117   case ISD::SETOGT:
3118   case ISD::SETGT:   return X86::COND_A;
3119   case ISD::SETOLE:              // flipped
3120   case ISD::SETOGE:
3121   case ISD::SETGE:   return X86::COND_AE;
3122   case ISD::SETUGT:              // flipped
3123   case ISD::SETULT:
3124   case ISD::SETLT:   return X86::COND_B;
3125   case ISD::SETUGE:              // flipped
3126   case ISD::SETULE:
3127   case ISD::SETLE:   return X86::COND_BE;
3128   case ISD::SETONE:
3129   case ISD::SETNE:   return X86::COND_NE;
3130   case ISD::SETUO:   return X86::COND_P;
3131   case ISD::SETO:    return X86::COND_NP;
3132   case ISD::SETOEQ:
3133   case ISD::SETUNE:  return X86::COND_INVALID;
3134   }
3135 }
3136
3137 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3138 /// code. Current x86 isa includes the following FP cmov instructions:
3139 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3140 static bool hasFPCMov(unsigned X86CC) {
3141   switch (X86CC) {
3142   default:
3143     return false;
3144   case X86::COND_B:
3145   case X86::COND_BE:
3146   case X86::COND_E:
3147   case X86::COND_P:
3148   case X86::COND_A:
3149   case X86::COND_AE:
3150   case X86::COND_NE:
3151   case X86::COND_NP:
3152     return true;
3153   }
3154 }
3155
3156 /// isFPImmLegal - Returns true if the target can instruction select the
3157 /// specified FP immediate natively. If false, the legalizer will
3158 /// materialize the FP immediate as a load from a constant pool.
3159 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3160   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3161     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3162       return true;
3163   }
3164   return false;
3165 }
3166
3167 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3168 /// the specified range (L, H].
3169 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3170   return (Val < 0) || (Val >= Low && Val < Hi);
3171 }
3172
3173 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3174 /// specified value.
3175 static bool isUndefOrEqual(int Val, int CmpVal) {
3176   if (Val < 0 || Val == CmpVal)
3177     return true;
3178   return false;
3179 }
3180
3181 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3182 /// from position Pos and ending in Pos+Size, falls within the specified
3183 /// sequential range (L, L+Pos]. or is undef.
3184 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3185                                        unsigned Pos, unsigned Size, int Low) {
3186   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3187     if (!isUndefOrEqual(Mask[i], Low))
3188       return false;
3189   return true;
3190 }
3191
3192 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3193 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3194 /// the second operand.
3195 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3196   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3197     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3198   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3199     return (Mask[0] < 2 && Mask[1] < 2);
3200   return false;
3201 }
3202
3203 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3204 /// is suitable for input to PSHUFHW.
3205 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3206   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3207     return false;
3208
3209   // Lower quadword copied in order or undef.
3210   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3211     return false;
3212
3213   // Upper quadword shuffled.
3214   for (unsigned i = 4; i != 8; ++i)
3215     if (!isUndefOrInRange(Mask[i], 4, 8))
3216       return false;
3217
3218   if (VT == MVT::v16i16) {
3219     // Lower quadword copied in order or undef.
3220     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3221       return false;
3222
3223     // Upper quadword shuffled.
3224     for (unsigned i = 12; i != 16; ++i)
3225       if (!isUndefOrInRange(Mask[i], 12, 16))
3226         return false;
3227   }
3228
3229   return true;
3230 }
3231
3232 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3233 /// is suitable for input to PSHUFLW.
3234 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3235   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3236     return false;
3237
3238   // Upper quadword copied in order.
3239   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3240     return false;
3241
3242   // Lower quadword shuffled.
3243   for (unsigned i = 0; i != 4; ++i)
3244     if (!isUndefOrInRange(Mask[i], 0, 4))
3245       return false;
3246
3247   if (VT == MVT::v16i16) {
3248     // Upper quadword copied in order.
3249     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3250       return false;
3251
3252     // Lower quadword shuffled.
3253     for (unsigned i = 8; i != 12; ++i)
3254       if (!isUndefOrInRange(Mask[i], 8, 12))
3255         return false;
3256   }
3257
3258   return true;
3259 }
3260
3261 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3262 /// is suitable for input to PALIGNR.
3263 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3264                           const X86Subtarget *Subtarget) {
3265   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3266       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3267     return false;
3268
3269   unsigned NumElts = VT.getVectorNumElements();
3270   unsigned NumLanes = VT.getSizeInBits()/128;
3271   unsigned NumLaneElts = NumElts/NumLanes;
3272
3273   // Do not handle 64-bit element shuffles with palignr.
3274   if (NumLaneElts == 2)
3275     return false;
3276
3277   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3278     unsigned i;
3279     for (i = 0; i != NumLaneElts; ++i) {
3280       if (Mask[i+l] >= 0)
3281         break;
3282     }
3283
3284     // Lane is all undef, go to next lane
3285     if (i == NumLaneElts)
3286       continue;
3287
3288     int Start = Mask[i+l];
3289
3290     // Make sure its in this lane in one of the sources
3291     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3292         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3293       return false;
3294
3295     // If not lane 0, then we must match lane 0
3296     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3297       return false;
3298
3299     // Correct second source to be contiguous with first source
3300     if (Start >= (int)NumElts)
3301       Start -= NumElts - NumLaneElts;
3302
3303     // Make sure we're shifting in the right direction.
3304     if (Start <= (int)(i+l))
3305       return false;
3306
3307     Start -= i;
3308
3309     // Check the rest of the elements to see if they are consecutive.
3310     for (++i; i != NumLaneElts; ++i) {
3311       int Idx = Mask[i+l];
3312
3313       // Make sure its in this lane
3314       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3315           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3316         return false;
3317
3318       // If not lane 0, then we must match lane 0
3319       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3320         return false;
3321
3322       if (Idx >= (int)NumElts)
3323         Idx -= NumElts - NumLaneElts;
3324
3325       if (!isUndefOrEqual(Idx, Start+i))
3326         return false;
3327
3328     }
3329   }
3330
3331   return true;
3332 }
3333
3334 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3335 /// the two vector operands have swapped position.
3336 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3337                                      unsigned NumElems) {
3338   for (unsigned i = 0; i != NumElems; ++i) {
3339     int idx = Mask[i];
3340     if (idx < 0)
3341       continue;
3342     else if (idx < (int)NumElems)
3343       Mask[i] = idx + NumElems;
3344     else
3345       Mask[i] = idx - NumElems;
3346   }
3347 }
3348
3349 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3350 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3351 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3352 /// reverse of what x86 shuffles want.
3353 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3354                         bool Commuted = false) {
3355   if (!HasAVX && VT.getSizeInBits() == 256)
3356     return false;
3357
3358   unsigned NumElems = VT.getVectorNumElements();
3359   unsigned NumLanes = VT.getSizeInBits()/128;
3360   unsigned NumLaneElems = NumElems/NumLanes;
3361
3362   if (NumLaneElems != 2 && NumLaneElems != 4)
3363     return false;
3364
3365   // VSHUFPSY divides the resulting vector into 4 chunks.
3366   // The sources are also splitted into 4 chunks, and each destination
3367   // chunk must come from a different source chunk.
3368   //
3369   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3370   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3371   //
3372   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3373   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3374   //
3375   // VSHUFPDY divides the resulting vector into 4 chunks.
3376   // The sources are also splitted into 4 chunks, and each destination
3377   // chunk must come from a different source chunk.
3378   //
3379   //  SRC1 =>      X3       X2       X1       X0
3380   //  SRC2 =>      Y3       Y2       Y1       Y0
3381   //
3382   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3383   //
3384   unsigned HalfLaneElems = NumLaneElems/2;
3385   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3386     for (unsigned i = 0; i != NumLaneElems; ++i) {
3387       int Idx = Mask[i+l];
3388       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3389       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3390         return false;
3391       // For VSHUFPSY, the mask of the second half must be the same as the
3392       // first but with the appropriate offsets. This works in the same way as
3393       // VPERMILPS works with masks.
3394       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3395         continue;
3396       if (!isUndefOrEqual(Idx, Mask[i]+l))
3397         return false;
3398     }
3399   }
3400
3401   return true;
3402 }
3403
3404 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3405 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3406 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3407   if (!VT.is128BitVector())
3408     return false;
3409
3410   unsigned NumElems = VT.getVectorNumElements();
3411
3412   if (NumElems != 4)
3413     return false;
3414
3415   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3416   return isUndefOrEqual(Mask[0], 6) &&
3417          isUndefOrEqual(Mask[1], 7) &&
3418          isUndefOrEqual(Mask[2], 2) &&
3419          isUndefOrEqual(Mask[3], 3);
3420 }
3421
3422 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3423 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3424 /// <2, 3, 2, 3>
3425 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3426   if (!VT.is128BitVector())
3427     return false;
3428
3429   unsigned NumElems = VT.getVectorNumElements();
3430
3431   if (NumElems != 4)
3432     return false;
3433
3434   return isUndefOrEqual(Mask[0], 2) &&
3435          isUndefOrEqual(Mask[1], 3) &&
3436          isUndefOrEqual(Mask[2], 2) &&
3437          isUndefOrEqual(Mask[3], 3);
3438 }
3439
3440 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3441 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3442 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3443   if (!VT.is128BitVector())
3444     return false;
3445
3446   unsigned NumElems = VT.getVectorNumElements();
3447
3448   if (NumElems != 2 && NumElems != 4)
3449     return false;
3450
3451   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3452     if (!isUndefOrEqual(Mask[i], i + NumElems))
3453       return false;
3454
3455   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3456     if (!isUndefOrEqual(Mask[i], i))
3457       return false;
3458
3459   return true;
3460 }
3461
3462 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3463 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3464 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3465   if (!VT.is128BitVector())
3466     return false;
3467
3468   unsigned NumElems = VT.getVectorNumElements();
3469
3470   if (NumElems != 2 && NumElems != 4)
3471     return false;
3472
3473   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3474     if (!isUndefOrEqual(Mask[i], i))
3475       return false;
3476
3477   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3478     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3479       return false;
3480
3481   return true;
3482 }
3483
3484 //
3485 // Some special combinations that can be optimized.
3486 //
3487 static
3488 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3489                                SelectionDAG &DAG) {
3490   EVT VT = SVOp->getValueType(0);
3491   DebugLoc dl = SVOp->getDebugLoc();
3492
3493   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3494     return SDValue();
3495
3496   ArrayRef<int> Mask = SVOp->getMask();
3497
3498   // These are the special masks that may be optimized.
3499   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3500   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3501   bool MatchEvenMask = true;
3502   bool MatchOddMask  = true;
3503   for (int i=0; i<8; ++i) {
3504     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3505       MatchEvenMask = false;
3506     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3507       MatchOddMask = false;
3508   }
3509   static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1};
3510   static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1};
3511
3512   const int *CompactionMask;
3513   if (MatchEvenMask)
3514     CompactionMask = CompactionMaskEven;
3515   else if (MatchOddMask)
3516     CompactionMask = CompactionMaskOdd;
3517   else
3518     return SDValue();
3519
3520   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3521
3522   SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0),
3523                                      UndefNode, CompactionMask);
3524   SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1),
3525                                      UndefNode, CompactionMask);
3526   static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13};
3527   return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask);
3528 }
3529
3530 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3531 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3532 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3533                          bool HasAVX2, bool V2IsSplat = false) {
3534   unsigned NumElts = VT.getVectorNumElements();
3535
3536   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3537          "Unsupported vector type for unpckh");
3538
3539   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3540       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3541     return false;
3542
3543   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3544   // independently on 128-bit lanes.
3545   unsigned NumLanes = VT.getSizeInBits()/128;
3546   unsigned NumLaneElts = NumElts/NumLanes;
3547
3548   for (unsigned l = 0; l != NumLanes; ++l) {
3549     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3550          i != (l+1)*NumLaneElts;
3551          i += 2, ++j) {
3552       int BitI  = Mask[i];
3553       int BitI1 = Mask[i+1];
3554       if (!isUndefOrEqual(BitI, j))
3555         return false;
3556       if (V2IsSplat) {
3557         if (!isUndefOrEqual(BitI1, NumElts))
3558           return false;
3559       } else {
3560         if (!isUndefOrEqual(BitI1, j + NumElts))
3561           return false;
3562       }
3563     }
3564   }
3565
3566   return true;
3567 }
3568
3569 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3570 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3571 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3572                          bool HasAVX2, bool V2IsSplat = false) {
3573   unsigned NumElts = VT.getVectorNumElements();
3574
3575   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3576          "Unsupported vector type for unpckh");
3577
3578   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3579       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3580     return false;
3581
3582   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3583   // independently on 128-bit lanes.
3584   unsigned NumLanes = VT.getSizeInBits()/128;
3585   unsigned NumLaneElts = NumElts/NumLanes;
3586
3587   for (unsigned l = 0; l != NumLanes; ++l) {
3588     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3589          i != (l+1)*NumLaneElts; i += 2, ++j) {
3590       int BitI  = Mask[i];
3591       int BitI1 = Mask[i+1];
3592       if (!isUndefOrEqual(BitI, j))
3593         return false;
3594       if (V2IsSplat) {
3595         if (isUndefOrEqual(BitI1, NumElts))
3596           return false;
3597       } else {
3598         if (!isUndefOrEqual(BitI1, j+NumElts))
3599           return false;
3600       }
3601     }
3602   }
3603   return true;
3604 }
3605
3606 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3607 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3608 /// <0, 0, 1, 1>
3609 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3610                                   bool HasAVX2) {
3611   unsigned NumElts = VT.getVectorNumElements();
3612
3613   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3614          "Unsupported vector type for unpckh");
3615
3616   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3617       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3618     return false;
3619
3620   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3621   // FIXME: Need a better way to get rid of this, there's no latency difference
3622   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3623   // the former later. We should also remove the "_undef" special mask.
3624   if (NumElts == 4 && VT.getSizeInBits() == 256)
3625     return false;
3626
3627   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3628   // independently on 128-bit lanes.
3629   unsigned NumLanes = VT.getSizeInBits()/128;
3630   unsigned NumLaneElts = NumElts/NumLanes;
3631
3632   for (unsigned l = 0; l != NumLanes; ++l) {
3633     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3634          i != (l+1)*NumLaneElts;
3635          i += 2, ++j) {
3636       int BitI  = Mask[i];
3637       int BitI1 = Mask[i+1];
3638
3639       if (!isUndefOrEqual(BitI, j))
3640         return false;
3641       if (!isUndefOrEqual(BitI1, j))
3642         return false;
3643     }
3644   }
3645
3646   return true;
3647 }
3648
3649 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3650 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3651 /// <2, 2, 3, 3>
3652 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3653   unsigned NumElts = VT.getVectorNumElements();
3654
3655   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3656          "Unsupported vector type for unpckh");
3657
3658   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3659       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3660     return false;
3661
3662   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3663   // independently on 128-bit lanes.
3664   unsigned NumLanes = VT.getSizeInBits()/128;
3665   unsigned NumLaneElts = NumElts/NumLanes;
3666
3667   for (unsigned l = 0; l != NumLanes; ++l) {
3668     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3669          i != (l+1)*NumLaneElts; i += 2, ++j) {
3670       int BitI  = Mask[i];
3671       int BitI1 = Mask[i+1];
3672       if (!isUndefOrEqual(BitI, j))
3673         return false;
3674       if (!isUndefOrEqual(BitI1, j))
3675         return false;
3676     }
3677   }
3678   return true;
3679 }
3680
3681 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3682 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3683 /// MOVSD, and MOVD, i.e. setting the lowest element.
3684 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3685   if (VT.getVectorElementType().getSizeInBits() < 32)
3686     return false;
3687   if (!VT.is128BitVector())
3688     return false;
3689
3690   unsigned NumElts = VT.getVectorNumElements();
3691
3692   if (!isUndefOrEqual(Mask[0], NumElts))
3693     return false;
3694
3695   for (unsigned i = 1; i != NumElts; ++i)
3696     if (!isUndefOrEqual(Mask[i], i))
3697       return false;
3698
3699   return true;
3700 }
3701
3702 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3703 /// as permutations between 128-bit chunks or halves. As an example: this
3704 /// shuffle bellow:
3705 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3706 /// The first half comes from the second half of V1 and the second half from the
3707 /// the second half of V2.
3708 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3709   if (!HasAVX || !VT.is256BitVector())
3710     return false;
3711
3712   // The shuffle result is divided into half A and half B. In total the two
3713   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3714   // B must come from C, D, E or F.
3715   unsigned HalfSize = VT.getVectorNumElements()/2;
3716   bool MatchA = false, MatchB = false;
3717
3718   // Check if A comes from one of C, D, E, F.
3719   for (unsigned Half = 0; Half != 4; ++Half) {
3720     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3721       MatchA = true;
3722       break;
3723     }
3724   }
3725
3726   // Check if B comes from one of C, D, E, F.
3727   for (unsigned Half = 0; Half != 4; ++Half) {
3728     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3729       MatchB = true;
3730       break;
3731     }
3732   }
3733
3734   return MatchA && MatchB;
3735 }
3736
3737 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3738 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3739 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3740   EVT VT = SVOp->getValueType(0);
3741
3742   unsigned HalfSize = VT.getVectorNumElements()/2;
3743
3744   unsigned FstHalf = 0, SndHalf = 0;
3745   for (unsigned i = 0; i < HalfSize; ++i) {
3746     if (SVOp->getMaskElt(i) > 0) {
3747       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3748       break;
3749     }
3750   }
3751   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3752     if (SVOp->getMaskElt(i) > 0) {
3753       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3754       break;
3755     }
3756   }
3757
3758   return (FstHalf | (SndHalf << 4));
3759 }
3760
3761 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3762 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3763 /// Note that VPERMIL mask matching is different depending whether theunderlying
3764 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3765 /// to the same elements of the low, but to the higher half of the source.
3766 /// In VPERMILPD the two lanes could be shuffled independently of each other
3767 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3768 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3769   if (!HasAVX)
3770     return false;
3771
3772   unsigned NumElts = VT.getVectorNumElements();
3773   // Only match 256-bit with 32/64-bit types
3774   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3775     return false;
3776
3777   unsigned NumLanes = VT.getSizeInBits()/128;
3778   unsigned LaneSize = NumElts/NumLanes;
3779   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3780     for (unsigned i = 0; i != LaneSize; ++i) {
3781       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3782         return false;
3783       if (NumElts != 8 || l == 0)
3784         continue;
3785       // VPERMILPS handling
3786       if (Mask[i] < 0)
3787         continue;
3788       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3789         return false;
3790     }
3791   }
3792
3793   return true;
3794 }
3795
3796 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3797 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3798 /// element of vector 2 and the other elements to come from vector 1 in order.
3799 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3800                                bool V2IsSplat = false, bool V2IsUndef = false) {
3801   if (!VT.is128BitVector())
3802     return false;
3803
3804   unsigned NumOps = VT.getVectorNumElements();
3805   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3806     return false;
3807
3808   if (!isUndefOrEqual(Mask[0], 0))
3809     return false;
3810
3811   for (unsigned i = 1; i != NumOps; ++i)
3812     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3813           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3814           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3815       return false;
3816
3817   return true;
3818 }
3819
3820 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3821 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3822 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3823 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3824                            const X86Subtarget *Subtarget) {
3825   if (!Subtarget->hasSSE3())
3826     return false;
3827
3828   unsigned NumElems = VT.getVectorNumElements();
3829
3830   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3831       (VT.getSizeInBits() == 256 && NumElems != 8))
3832     return false;
3833
3834   // "i+1" is the value the indexed mask element must have
3835   for (unsigned i = 0; i != NumElems; i += 2)
3836     if (!isUndefOrEqual(Mask[i], i+1) ||
3837         !isUndefOrEqual(Mask[i+1], i+1))
3838       return false;
3839
3840   return true;
3841 }
3842
3843 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3844 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3845 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3846 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3847                            const X86Subtarget *Subtarget) {
3848   if (!Subtarget->hasSSE3())
3849     return false;
3850
3851   unsigned NumElems = VT.getVectorNumElements();
3852
3853   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3854       (VT.getSizeInBits() == 256 && NumElems != 8))
3855     return false;
3856
3857   // "i" is the value the indexed mask element must have
3858   for (unsigned i = 0; i != NumElems; i += 2)
3859     if (!isUndefOrEqual(Mask[i], i) ||
3860         !isUndefOrEqual(Mask[i+1], i))
3861       return false;
3862
3863   return true;
3864 }
3865
3866 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3867 /// specifies a shuffle of elements that is suitable for input to 256-bit
3868 /// version of MOVDDUP.
3869 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3870   if (!HasAVX || !VT.is256BitVector())
3871     return false;
3872
3873   unsigned NumElts = VT.getVectorNumElements();
3874   if (NumElts != 4)
3875     return false;
3876
3877   for (unsigned i = 0; i != NumElts/2; ++i)
3878     if (!isUndefOrEqual(Mask[i], 0))
3879       return false;
3880   for (unsigned i = NumElts/2; i != NumElts; ++i)
3881     if (!isUndefOrEqual(Mask[i], NumElts/2))
3882       return false;
3883   return true;
3884 }
3885
3886 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3887 /// specifies a shuffle of elements that is suitable for input to 128-bit
3888 /// version of MOVDDUP.
3889 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3890   if (!VT.is128BitVector())
3891     return false;
3892
3893   unsigned e = VT.getVectorNumElements() / 2;
3894   for (unsigned i = 0; i != e; ++i)
3895     if (!isUndefOrEqual(Mask[i], i))
3896       return false;
3897   for (unsigned i = 0; i != e; ++i)
3898     if (!isUndefOrEqual(Mask[e+i], i))
3899       return false;
3900   return true;
3901 }
3902
3903 /// isVEXTRACTF128Index - Return true if the specified
3904 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3905 /// suitable for input to VEXTRACTF128.
3906 bool X86::isVEXTRACTF128Index(SDNode *N) {
3907   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3908     return false;
3909
3910   // The index should be aligned on a 128-bit boundary.
3911   uint64_t Index =
3912     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3913
3914   unsigned VL = N->getValueType(0).getVectorNumElements();
3915   unsigned VBits = N->getValueType(0).getSizeInBits();
3916   unsigned ElSize = VBits / VL;
3917   bool Result = (Index * ElSize) % 128 == 0;
3918
3919   return Result;
3920 }
3921
3922 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3923 /// operand specifies a subvector insert that is suitable for input to
3924 /// VINSERTF128.
3925 bool X86::isVINSERTF128Index(SDNode *N) {
3926   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3927     return false;
3928
3929   // The index should be aligned on a 128-bit boundary.
3930   uint64_t Index =
3931     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3932
3933   unsigned VL = N->getValueType(0).getVectorNumElements();
3934   unsigned VBits = N->getValueType(0).getSizeInBits();
3935   unsigned ElSize = VBits / VL;
3936   bool Result = (Index * ElSize) % 128 == 0;
3937
3938   return Result;
3939 }
3940
3941 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3942 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3943 /// Handles 128-bit and 256-bit.
3944 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3945   EVT VT = N->getValueType(0);
3946
3947   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3948          "Unsupported vector type for PSHUF/SHUFP");
3949
3950   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3951   // independently on 128-bit lanes.
3952   unsigned NumElts = VT.getVectorNumElements();
3953   unsigned NumLanes = VT.getSizeInBits()/128;
3954   unsigned NumLaneElts = NumElts/NumLanes;
3955
3956   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3957          "Only supports 2 or 4 elements per lane");
3958
3959   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3960   unsigned Mask = 0;
3961   for (unsigned i = 0; i != NumElts; ++i) {
3962     int Elt = N->getMaskElt(i);
3963     if (Elt < 0) continue;
3964     Elt &= NumLaneElts - 1;
3965     unsigned ShAmt = (i << Shift) % 8;
3966     Mask |= Elt << ShAmt;
3967   }
3968
3969   return Mask;
3970 }
3971
3972 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3973 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3974 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3975   EVT VT = N->getValueType(0);
3976
3977   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3978          "Unsupported vector type for PSHUFHW");
3979
3980   unsigned NumElts = VT.getVectorNumElements();
3981
3982   unsigned Mask = 0;
3983   for (unsigned l = 0; l != NumElts; l += 8) {
3984     // 8 nodes per lane, but we only care about the last 4.
3985     for (unsigned i = 0; i < 4; ++i) {
3986       int Elt = N->getMaskElt(l+i+4);
3987       if (Elt < 0) continue;
3988       Elt &= 0x3; // only 2-bits.
3989       Mask |= Elt << (i * 2);
3990     }
3991   }
3992
3993   return Mask;
3994 }
3995
3996 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3997 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3998 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
3999   EVT VT = N->getValueType(0);
4000
4001   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4002          "Unsupported vector type for PSHUFHW");
4003
4004   unsigned NumElts = VT.getVectorNumElements();
4005
4006   unsigned Mask = 0;
4007   for (unsigned l = 0; l != NumElts; l += 8) {
4008     // 8 nodes per lane, but we only care about the first 4.
4009     for (unsigned i = 0; i < 4; ++i) {
4010       int Elt = N->getMaskElt(l+i);
4011       if (Elt < 0) continue;
4012       Elt &= 0x3; // only 2-bits
4013       Mask |= Elt << (i * 2);
4014     }
4015   }
4016
4017   return Mask;
4018 }
4019
4020 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4021 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4022 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4023   EVT VT = SVOp->getValueType(0);
4024   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4025
4026   unsigned NumElts = VT.getVectorNumElements();
4027   unsigned NumLanes = VT.getSizeInBits()/128;
4028   unsigned NumLaneElts = NumElts/NumLanes;
4029
4030   int Val = 0;
4031   unsigned i;
4032   for (i = 0; i != NumElts; ++i) {
4033     Val = SVOp->getMaskElt(i);
4034     if (Val >= 0)
4035       break;
4036   }
4037   if (Val >= (int)NumElts)
4038     Val -= NumElts - NumLaneElts;
4039
4040   assert(Val - i > 0 && "PALIGNR imm should be positive");
4041   return (Val - i) * EltSize;
4042 }
4043
4044 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4045 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4046 /// instructions.
4047 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4048   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4049     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4050
4051   uint64_t Index =
4052     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4053
4054   EVT VecVT = N->getOperand(0).getValueType();
4055   EVT ElVT = VecVT.getVectorElementType();
4056
4057   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4058   return Index / NumElemsPerChunk;
4059 }
4060
4061 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4062 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4063 /// instructions.
4064 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4065   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4066     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4067
4068   uint64_t Index =
4069     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4070
4071   EVT VecVT = N->getValueType(0);
4072   EVT ElVT = VecVT.getVectorElementType();
4073
4074   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4075   return Index / NumElemsPerChunk;
4076 }
4077
4078 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4079 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4080 /// Handles 256-bit.
4081 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4082   EVT VT = N->getValueType(0);
4083
4084   unsigned NumElts = VT.getVectorNumElements();
4085
4086   assert((VT.is256BitVector() && NumElts == 4) &&
4087          "Unsupported vector type for VPERMQ/VPERMPD");
4088
4089   unsigned Mask = 0;
4090   for (unsigned i = 0; i != NumElts; ++i) {
4091     int Elt = N->getMaskElt(i);
4092     if (Elt < 0)
4093       continue;
4094     Mask |= Elt << (i*2);
4095   }
4096
4097   return Mask;
4098 }
4099 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4100 /// constant +0.0.
4101 bool X86::isZeroNode(SDValue Elt) {
4102   return ((isa<ConstantSDNode>(Elt) &&
4103            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4104           (isa<ConstantFPSDNode>(Elt) &&
4105            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4106 }
4107
4108 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4109 /// their permute mask.
4110 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4111                                     SelectionDAG &DAG) {
4112   EVT VT = SVOp->getValueType(0);
4113   unsigned NumElems = VT.getVectorNumElements();
4114   SmallVector<int, 8> MaskVec;
4115
4116   for (unsigned i = 0; i != NumElems; ++i) {
4117     int Idx = SVOp->getMaskElt(i);
4118     if (Idx >= 0) {
4119       if (Idx < (int)NumElems)
4120         Idx += NumElems;
4121       else
4122         Idx -= NumElems;
4123     }
4124     MaskVec.push_back(Idx);
4125   }
4126   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4127                               SVOp->getOperand(0), &MaskVec[0]);
4128 }
4129
4130 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4131 /// match movhlps. The lower half elements should come from upper half of
4132 /// V1 (and in order), and the upper half elements should come from the upper
4133 /// half of V2 (and in order).
4134 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4135   if (!VT.is128BitVector())
4136     return false;
4137   if (VT.getVectorNumElements() != 4)
4138     return false;
4139   for (unsigned i = 0, e = 2; i != e; ++i)
4140     if (!isUndefOrEqual(Mask[i], i+2))
4141       return false;
4142   for (unsigned i = 2; i != 4; ++i)
4143     if (!isUndefOrEqual(Mask[i], i+4))
4144       return false;
4145   return true;
4146 }
4147
4148 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4149 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4150 /// required.
4151 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4152   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4153     return false;
4154   N = N->getOperand(0).getNode();
4155   if (!ISD::isNON_EXTLoad(N))
4156     return false;
4157   if (LD)
4158     *LD = cast<LoadSDNode>(N);
4159   return true;
4160 }
4161
4162 // Test whether the given value is a vector value which will be legalized
4163 // into a load.
4164 static bool WillBeConstantPoolLoad(SDNode *N) {
4165   if (N->getOpcode() != ISD::BUILD_VECTOR)
4166     return false;
4167
4168   // Check for any non-constant elements.
4169   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4170     switch (N->getOperand(i).getNode()->getOpcode()) {
4171     case ISD::UNDEF:
4172     case ISD::ConstantFP:
4173     case ISD::Constant:
4174       break;
4175     default:
4176       return false;
4177     }
4178
4179   // Vectors of all-zeros and all-ones are materialized with special
4180   // instructions rather than being loaded.
4181   return !ISD::isBuildVectorAllZeros(N) &&
4182          !ISD::isBuildVectorAllOnes(N);
4183 }
4184
4185 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4186 /// match movlp{s|d}. The lower half elements should come from lower half of
4187 /// V1 (and in order), and the upper half elements should come from the upper
4188 /// half of V2 (and in order). And since V1 will become the source of the
4189 /// MOVLP, it must be either a vector load or a scalar load to vector.
4190 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4191                                ArrayRef<int> Mask, EVT VT) {
4192   if (!VT.is128BitVector())
4193     return false;
4194
4195   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4196     return false;
4197   // Is V2 is a vector load, don't do this transformation. We will try to use
4198   // load folding shufps op.
4199   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4200     return false;
4201
4202   unsigned NumElems = VT.getVectorNumElements();
4203
4204   if (NumElems != 2 && NumElems != 4)
4205     return false;
4206   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4207     if (!isUndefOrEqual(Mask[i], i))
4208       return false;
4209   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4210     if (!isUndefOrEqual(Mask[i], i+NumElems))
4211       return false;
4212   return true;
4213 }
4214
4215 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4216 /// all the same.
4217 static bool isSplatVector(SDNode *N) {
4218   if (N->getOpcode() != ISD::BUILD_VECTOR)
4219     return false;
4220
4221   SDValue SplatValue = N->getOperand(0);
4222   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4223     if (N->getOperand(i) != SplatValue)
4224       return false;
4225   return true;
4226 }
4227
4228 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4229 /// to an zero vector.
4230 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4231 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4232   SDValue V1 = N->getOperand(0);
4233   SDValue V2 = N->getOperand(1);
4234   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4235   for (unsigned i = 0; i != NumElems; ++i) {
4236     int Idx = N->getMaskElt(i);
4237     if (Idx >= (int)NumElems) {
4238       unsigned Opc = V2.getOpcode();
4239       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4240         continue;
4241       if (Opc != ISD::BUILD_VECTOR ||
4242           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4243         return false;
4244     } else if (Idx >= 0) {
4245       unsigned Opc = V1.getOpcode();
4246       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4247         continue;
4248       if (Opc != ISD::BUILD_VECTOR ||
4249           !X86::isZeroNode(V1.getOperand(Idx)))
4250         return false;
4251     }
4252   }
4253   return true;
4254 }
4255
4256 /// getZeroVector - Returns a vector of specified type with all zero elements.
4257 ///
4258 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4259                              SelectionDAG &DAG, DebugLoc dl) {
4260   assert(VT.isVector() && "Expected a vector type");
4261   unsigned Size = VT.getSizeInBits();
4262
4263   // Always build SSE zero vectors as <4 x i32> bitcasted
4264   // to their dest type. This ensures they get CSE'd.
4265   SDValue Vec;
4266   if (Size == 128) {  // SSE
4267     if (Subtarget->hasSSE2()) {  // SSE2
4268       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4269       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4270     } else { // SSE1
4271       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4272       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4273     }
4274   } else if (Size == 256) { // AVX
4275     if (Subtarget->hasAVX2()) { // AVX2
4276       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4277       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4278       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4279     } else {
4280       // 256-bit logic and arithmetic instructions in AVX are all
4281       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4282       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4283       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4284       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4285     }
4286   } else
4287     llvm_unreachable("Unexpected vector type");
4288
4289   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4290 }
4291
4292 /// getOnesVector - Returns a vector of specified type with all bits set.
4293 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4294 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4295 /// Then bitcast to their original type, ensuring they get CSE'd.
4296 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4297                              DebugLoc dl) {
4298   assert(VT.isVector() && "Expected a vector type");
4299   unsigned Size = VT.getSizeInBits();
4300
4301   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4302   SDValue Vec;
4303   if (Size == 256) {
4304     if (HasAVX2) { // AVX2
4305       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4306       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4307     } else { // AVX
4308       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4309       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4310     }
4311   } else if (Size == 128) {
4312     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4313   } else
4314     llvm_unreachable("Unexpected vector type");
4315
4316   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4317 }
4318
4319 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4320 /// that point to V2 points to its first element.
4321 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4322   for (unsigned i = 0; i != NumElems; ++i) {
4323     if (Mask[i] > (int)NumElems) {
4324       Mask[i] = NumElems;
4325     }
4326   }
4327 }
4328
4329 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4330 /// operation of specified width.
4331 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4332                        SDValue V2) {
4333   unsigned NumElems = VT.getVectorNumElements();
4334   SmallVector<int, 8> Mask;
4335   Mask.push_back(NumElems);
4336   for (unsigned i = 1; i != NumElems; ++i)
4337     Mask.push_back(i);
4338   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4339 }
4340
4341 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4342 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4343                           SDValue V2) {
4344   unsigned NumElems = VT.getVectorNumElements();
4345   SmallVector<int, 8> Mask;
4346   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4347     Mask.push_back(i);
4348     Mask.push_back(i + NumElems);
4349   }
4350   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4351 }
4352
4353 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4354 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4355                           SDValue V2) {
4356   unsigned NumElems = VT.getVectorNumElements();
4357   SmallVector<int, 8> Mask;
4358   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4359     Mask.push_back(i + Half);
4360     Mask.push_back(i + NumElems + Half);
4361   }
4362   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4363 }
4364
4365 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4366 // a generic shuffle instruction because the target has no such instructions.
4367 // Generate shuffles which repeat i16 and i8 several times until they can be
4368 // represented by v4f32 and then be manipulated by target suported shuffles.
4369 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4370   EVT VT = V.getValueType();
4371   int NumElems = VT.getVectorNumElements();
4372   DebugLoc dl = V.getDebugLoc();
4373
4374   while (NumElems > 4) {
4375     if (EltNo < NumElems/2) {
4376       V = getUnpackl(DAG, dl, VT, V, V);
4377     } else {
4378       V = getUnpackh(DAG, dl, VT, V, V);
4379       EltNo -= NumElems/2;
4380     }
4381     NumElems >>= 1;
4382   }
4383   return V;
4384 }
4385
4386 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4387 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4388   EVT VT = V.getValueType();
4389   DebugLoc dl = V.getDebugLoc();
4390   unsigned Size = VT.getSizeInBits();
4391
4392   if (Size == 128) {
4393     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4394     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4395     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4396                              &SplatMask[0]);
4397   } else if (Size == 256) {
4398     // To use VPERMILPS to splat scalars, the second half of indicies must
4399     // refer to the higher part, which is a duplication of the lower one,
4400     // because VPERMILPS can only handle in-lane permutations.
4401     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4402                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4403
4404     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4405     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4406                              &SplatMask[0]);
4407   } else
4408     llvm_unreachable("Vector size not supported");
4409
4410   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4411 }
4412
4413 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4414 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4415   EVT SrcVT = SV->getValueType(0);
4416   SDValue V1 = SV->getOperand(0);
4417   DebugLoc dl = SV->getDebugLoc();
4418
4419   int EltNo = SV->getSplatIndex();
4420   int NumElems = SrcVT.getVectorNumElements();
4421   unsigned Size = SrcVT.getSizeInBits();
4422
4423   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4424           "Unknown how to promote splat for type");
4425
4426   // Extract the 128-bit part containing the splat element and update
4427   // the splat element index when it refers to the higher register.
4428   if (Size == 256) {
4429     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4430     if (EltNo >= NumElems/2)
4431       EltNo -= NumElems/2;
4432   }
4433
4434   // All i16 and i8 vector types can't be used directly by a generic shuffle
4435   // instruction because the target has no such instruction. Generate shuffles
4436   // which repeat i16 and i8 several times until they fit in i32, and then can
4437   // be manipulated by target suported shuffles.
4438   EVT EltVT = SrcVT.getVectorElementType();
4439   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4440     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4441
4442   // Recreate the 256-bit vector and place the same 128-bit vector
4443   // into the low and high part. This is necessary because we want
4444   // to use VPERM* to shuffle the vectors
4445   if (Size == 256) {
4446     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4447   }
4448
4449   return getLegalSplat(DAG, V1, EltNo);
4450 }
4451
4452 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4453 /// vector of zero or undef vector.  This produces a shuffle where the low
4454 /// element of V2 is swizzled into the zero/undef vector, landing at element
4455 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4456 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4457                                            bool IsZero,
4458                                            const X86Subtarget *Subtarget,
4459                                            SelectionDAG &DAG) {
4460   EVT VT = V2.getValueType();
4461   SDValue V1 = IsZero
4462     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4463   unsigned NumElems = VT.getVectorNumElements();
4464   SmallVector<int, 16> MaskVec;
4465   for (unsigned i = 0; i != NumElems; ++i)
4466     // If this is the insertion idx, put the low elt of V2 here.
4467     MaskVec.push_back(i == Idx ? NumElems : i);
4468   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4469 }
4470
4471 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4472 /// target specific opcode. Returns true if the Mask could be calculated.
4473 /// Sets IsUnary to true if only uses one source.
4474 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4475                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4476   unsigned NumElems = VT.getVectorNumElements();
4477   SDValue ImmN;
4478
4479   IsUnary = false;
4480   switch(N->getOpcode()) {
4481   case X86ISD::SHUFP:
4482     ImmN = N->getOperand(N->getNumOperands()-1);
4483     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4484     break;
4485   case X86ISD::UNPCKH:
4486     DecodeUNPCKHMask(VT, Mask);
4487     break;
4488   case X86ISD::UNPCKL:
4489     DecodeUNPCKLMask(VT, Mask);
4490     break;
4491   case X86ISD::MOVHLPS:
4492     DecodeMOVHLPSMask(NumElems, Mask);
4493     break;
4494   case X86ISD::MOVLHPS:
4495     DecodeMOVLHPSMask(NumElems, Mask);
4496     break;
4497   case X86ISD::PSHUFD:
4498   case X86ISD::VPERMILP:
4499     ImmN = N->getOperand(N->getNumOperands()-1);
4500     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4501     IsUnary = true;
4502     break;
4503   case X86ISD::PSHUFHW:
4504     ImmN = N->getOperand(N->getNumOperands()-1);
4505     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4506     IsUnary = true;
4507     break;
4508   case X86ISD::PSHUFLW:
4509     ImmN = N->getOperand(N->getNumOperands()-1);
4510     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4511     IsUnary = true;
4512     break;
4513   case X86ISD::VPERMI:
4514     ImmN = N->getOperand(N->getNumOperands()-1);
4515     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4516     IsUnary = true;
4517     break;
4518   case X86ISD::MOVSS:
4519   case X86ISD::MOVSD: {
4520     // The index 0 always comes from the first element of the second source,
4521     // this is why MOVSS and MOVSD are used in the first place. The other
4522     // elements come from the other positions of the first source vector
4523     Mask.push_back(NumElems);
4524     for (unsigned i = 1; i != NumElems; ++i) {
4525       Mask.push_back(i);
4526     }
4527     break;
4528   }
4529   case X86ISD::VPERM2X128:
4530     ImmN = N->getOperand(N->getNumOperands()-1);
4531     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4532     if (Mask.empty()) return false;
4533     break;
4534   case X86ISD::MOVDDUP:
4535   case X86ISD::MOVLHPD:
4536   case X86ISD::MOVLPD:
4537   case X86ISD::MOVLPS:
4538   case X86ISD::MOVSHDUP:
4539   case X86ISD::MOVSLDUP:
4540   case X86ISD::PALIGN:
4541     // Not yet implemented
4542     return false;
4543   default: llvm_unreachable("unknown target shuffle node");
4544   }
4545
4546   return true;
4547 }
4548
4549 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4550 /// element of the result of the vector shuffle.
4551 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4552                                    unsigned Depth) {
4553   if (Depth == 6)
4554     return SDValue();  // Limit search depth.
4555
4556   SDValue V = SDValue(N, 0);
4557   EVT VT = V.getValueType();
4558   unsigned Opcode = V.getOpcode();
4559
4560   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4561   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4562     int Elt = SV->getMaskElt(Index);
4563
4564     if (Elt < 0)
4565       return DAG.getUNDEF(VT.getVectorElementType());
4566
4567     unsigned NumElems = VT.getVectorNumElements();
4568     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4569                                          : SV->getOperand(1);
4570     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4571   }
4572
4573   // Recurse into target specific vector shuffles to find scalars.
4574   if (isTargetShuffle(Opcode)) {
4575     MVT ShufVT = V.getValueType().getSimpleVT();
4576     unsigned NumElems = ShufVT.getVectorNumElements();
4577     SmallVector<int, 16> ShuffleMask;
4578     SDValue ImmN;
4579     bool IsUnary;
4580
4581     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4582       return SDValue();
4583
4584     int Elt = ShuffleMask[Index];
4585     if (Elt < 0)
4586       return DAG.getUNDEF(ShufVT.getVectorElementType());
4587
4588     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4589                                          : N->getOperand(1);
4590     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4591                                Depth+1);
4592   }
4593
4594   // Actual nodes that may contain scalar elements
4595   if (Opcode == ISD::BITCAST) {
4596     V = V.getOperand(0);
4597     EVT SrcVT = V.getValueType();
4598     unsigned NumElems = VT.getVectorNumElements();
4599
4600     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4601       return SDValue();
4602   }
4603
4604   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4605     return (Index == 0) ? V.getOperand(0)
4606                         : DAG.getUNDEF(VT.getVectorElementType());
4607
4608   if (V.getOpcode() == ISD::BUILD_VECTOR)
4609     return V.getOperand(Index);
4610
4611   return SDValue();
4612 }
4613
4614 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4615 /// shuffle operation which come from a consecutively from a zero. The
4616 /// search can start in two different directions, from left or right.
4617 static
4618 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4619                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4620   unsigned i;
4621   for (i = 0; i != NumElems; ++i) {
4622     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4623     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4624     if (!(Elt.getNode() &&
4625          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4626       break;
4627   }
4628
4629   return i;
4630 }
4631
4632 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4633 /// correspond consecutively to elements from one of the vector operands,
4634 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4635 static
4636 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4637                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4638                               unsigned NumElems, unsigned &OpNum) {
4639   bool SeenV1 = false;
4640   bool SeenV2 = false;
4641
4642   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4643     int Idx = SVOp->getMaskElt(i);
4644     // Ignore undef indicies
4645     if (Idx < 0)
4646       continue;
4647
4648     if (Idx < (int)NumElems)
4649       SeenV1 = true;
4650     else
4651       SeenV2 = true;
4652
4653     // Only accept consecutive elements from the same vector
4654     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4655       return false;
4656   }
4657
4658   OpNum = SeenV1 ? 0 : 1;
4659   return true;
4660 }
4661
4662 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4663 /// logical left shift of a vector.
4664 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4665                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4666   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4667   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4668               false /* check zeros from right */, DAG);
4669   unsigned OpSrc;
4670
4671   if (!NumZeros)
4672     return false;
4673
4674   // Considering the elements in the mask that are not consecutive zeros,
4675   // check if they consecutively come from only one of the source vectors.
4676   //
4677   //               V1 = {X, A, B, C}     0
4678   //                         \  \  \    /
4679   //   vector_shuffle V1, V2 <1, 2, 3, X>
4680   //
4681   if (!isShuffleMaskConsecutive(SVOp,
4682             0,                   // Mask Start Index
4683             NumElems-NumZeros,   // Mask End Index(exclusive)
4684             NumZeros,            // Where to start looking in the src vector
4685             NumElems,            // Number of elements in vector
4686             OpSrc))              // Which source operand ?
4687     return false;
4688
4689   isLeft = false;
4690   ShAmt = NumZeros;
4691   ShVal = SVOp->getOperand(OpSrc);
4692   return true;
4693 }
4694
4695 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4696 /// logical left shift of a vector.
4697 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4698                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4699   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4700   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4701               true /* check zeros from left */, DAG);
4702   unsigned OpSrc;
4703
4704   if (!NumZeros)
4705     return false;
4706
4707   // Considering the elements in the mask that are not consecutive zeros,
4708   // check if they consecutively come from only one of the source vectors.
4709   //
4710   //                           0    { A, B, X, X } = V2
4711   //                          / \    /  /
4712   //   vector_shuffle V1, V2 <X, X, 4, 5>
4713   //
4714   if (!isShuffleMaskConsecutive(SVOp,
4715             NumZeros,     // Mask Start Index
4716             NumElems,     // Mask End Index(exclusive)
4717             0,            // Where to start looking in the src vector
4718             NumElems,     // Number of elements in vector
4719             OpSrc))       // Which source operand ?
4720     return false;
4721
4722   isLeft = true;
4723   ShAmt = NumZeros;
4724   ShVal = SVOp->getOperand(OpSrc);
4725   return true;
4726 }
4727
4728 /// isVectorShift - Returns true if the shuffle can be implemented as a
4729 /// logical left or right shift of a vector.
4730 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4731                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4732   // Although the logic below support any bitwidth size, there are no
4733   // shift instructions which handle more than 128-bit vectors.
4734   if (!SVOp->getValueType(0).is128BitVector())
4735     return false;
4736
4737   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4738       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4739     return true;
4740
4741   return false;
4742 }
4743
4744 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4745 ///
4746 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4747                                        unsigned NumNonZero, unsigned NumZero,
4748                                        SelectionDAG &DAG,
4749                                        const X86Subtarget* Subtarget,
4750                                        const TargetLowering &TLI) {
4751   if (NumNonZero > 8)
4752     return SDValue();
4753
4754   DebugLoc dl = Op.getDebugLoc();
4755   SDValue V(0, 0);
4756   bool First = true;
4757   for (unsigned i = 0; i < 16; ++i) {
4758     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4759     if (ThisIsNonZero && First) {
4760       if (NumZero)
4761         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4762       else
4763         V = DAG.getUNDEF(MVT::v8i16);
4764       First = false;
4765     }
4766
4767     if ((i & 1) != 0) {
4768       SDValue ThisElt(0, 0), LastElt(0, 0);
4769       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4770       if (LastIsNonZero) {
4771         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4772                               MVT::i16, Op.getOperand(i-1));
4773       }
4774       if (ThisIsNonZero) {
4775         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4776         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4777                               ThisElt, DAG.getConstant(8, MVT::i8));
4778         if (LastIsNonZero)
4779           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4780       } else
4781         ThisElt = LastElt;
4782
4783       if (ThisElt.getNode())
4784         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4785                         DAG.getIntPtrConstant(i/2));
4786     }
4787   }
4788
4789   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4790 }
4791
4792 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4793 ///
4794 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4795                                      unsigned NumNonZero, unsigned NumZero,
4796                                      SelectionDAG &DAG,
4797                                      const X86Subtarget* Subtarget,
4798                                      const TargetLowering &TLI) {
4799   if (NumNonZero > 4)
4800     return SDValue();
4801
4802   DebugLoc dl = Op.getDebugLoc();
4803   SDValue V(0, 0);
4804   bool First = true;
4805   for (unsigned i = 0; i < 8; ++i) {
4806     bool isNonZero = (NonZeros & (1 << i)) != 0;
4807     if (isNonZero) {
4808       if (First) {
4809         if (NumZero)
4810           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4811         else
4812           V = DAG.getUNDEF(MVT::v8i16);
4813         First = false;
4814       }
4815       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4816                       MVT::v8i16, V, Op.getOperand(i),
4817                       DAG.getIntPtrConstant(i));
4818     }
4819   }
4820
4821   return V;
4822 }
4823
4824 /// getVShift - Return a vector logical shift node.
4825 ///
4826 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4827                          unsigned NumBits, SelectionDAG &DAG,
4828                          const TargetLowering &TLI, DebugLoc dl) {
4829   assert(VT.is128BitVector() && "Unknown type for VShift");
4830   EVT ShVT = MVT::v2i64;
4831   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4832   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4833   return DAG.getNode(ISD::BITCAST, dl, VT,
4834                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4835                              DAG.getConstant(NumBits,
4836                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4837 }
4838
4839 SDValue
4840 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4841                                           SelectionDAG &DAG) const {
4842
4843   // Check if the scalar load can be widened into a vector load. And if
4844   // the address is "base + cst" see if the cst can be "absorbed" into
4845   // the shuffle mask.
4846   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4847     SDValue Ptr = LD->getBasePtr();
4848     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4849       return SDValue();
4850     EVT PVT = LD->getValueType(0);
4851     if (PVT != MVT::i32 && PVT != MVT::f32)
4852       return SDValue();
4853
4854     int FI = -1;
4855     int64_t Offset = 0;
4856     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4857       FI = FINode->getIndex();
4858       Offset = 0;
4859     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4860                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4861       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4862       Offset = Ptr.getConstantOperandVal(1);
4863       Ptr = Ptr.getOperand(0);
4864     } else {
4865       return SDValue();
4866     }
4867
4868     // FIXME: 256-bit vector instructions don't require a strict alignment,
4869     // improve this code to support it better.
4870     unsigned RequiredAlign = VT.getSizeInBits()/8;
4871     SDValue Chain = LD->getChain();
4872     // Make sure the stack object alignment is at least 16 or 32.
4873     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4874     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4875       if (MFI->isFixedObjectIndex(FI)) {
4876         // Can't change the alignment. FIXME: It's possible to compute
4877         // the exact stack offset and reference FI + adjust offset instead.
4878         // If someone *really* cares about this. That's the way to implement it.
4879         return SDValue();
4880       } else {
4881         MFI->setObjectAlignment(FI, RequiredAlign);
4882       }
4883     }
4884
4885     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4886     // Ptr + (Offset & ~15).
4887     if (Offset < 0)
4888       return SDValue();
4889     if ((Offset % RequiredAlign) & 3)
4890       return SDValue();
4891     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4892     if (StartOffset)
4893       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4894                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4895
4896     int EltNo = (Offset - StartOffset) >> 2;
4897     unsigned NumElems = VT.getVectorNumElements();
4898
4899     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4900     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4901                              LD->getPointerInfo().getWithOffset(StartOffset),
4902                              false, false, false, 0);
4903
4904     SmallVector<int, 8> Mask;
4905     for (unsigned i = 0; i != NumElems; ++i)
4906       Mask.push_back(EltNo);
4907
4908     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4909   }
4910
4911   return SDValue();
4912 }
4913
4914 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4915 /// vector of type 'VT', see if the elements can be replaced by a single large
4916 /// load which has the same value as a build_vector whose operands are 'elts'.
4917 ///
4918 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4919 ///
4920 /// FIXME: we'd also like to handle the case where the last elements are zero
4921 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4922 /// There's even a handy isZeroNode for that purpose.
4923 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4924                                         DebugLoc &DL, SelectionDAG &DAG) {
4925   EVT EltVT = VT.getVectorElementType();
4926   unsigned NumElems = Elts.size();
4927
4928   LoadSDNode *LDBase = NULL;
4929   unsigned LastLoadedElt = -1U;
4930
4931   // For each element in the initializer, see if we've found a load or an undef.
4932   // If we don't find an initial load element, or later load elements are
4933   // non-consecutive, bail out.
4934   for (unsigned i = 0; i < NumElems; ++i) {
4935     SDValue Elt = Elts[i];
4936
4937     if (!Elt.getNode() ||
4938         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4939       return SDValue();
4940     if (!LDBase) {
4941       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4942         return SDValue();
4943       LDBase = cast<LoadSDNode>(Elt.getNode());
4944       LastLoadedElt = i;
4945       continue;
4946     }
4947     if (Elt.getOpcode() == ISD::UNDEF)
4948       continue;
4949
4950     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4951     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4952       return SDValue();
4953     LastLoadedElt = i;
4954   }
4955
4956   // If we have found an entire vector of loads and undefs, then return a large
4957   // load of the entire vector width starting at the base pointer.  If we found
4958   // consecutive loads for the low half, generate a vzext_load node.
4959   if (LastLoadedElt == NumElems - 1) {
4960     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4961       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4962                          LDBase->getPointerInfo(),
4963                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4964                          LDBase->isInvariant(), 0);
4965     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4966                        LDBase->getPointerInfo(),
4967                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4968                        LDBase->isInvariant(), LDBase->getAlignment());
4969   }
4970   if (NumElems == 4 && LastLoadedElt == 1 &&
4971       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4972     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4973     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4974     SDValue ResNode =
4975         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4976                                 LDBase->getPointerInfo(),
4977                                 LDBase->getAlignment(),
4978                                 false/*isVolatile*/, true/*ReadMem*/,
4979                                 false/*WriteMem*/);
4980     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4981   }
4982   return SDValue();
4983 }
4984
4985 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4986 /// to generate a splat value for the following cases:
4987 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4988 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4989 /// a scalar load, or a constant.
4990 /// The VBROADCAST node is returned when a pattern is found,
4991 /// or SDValue() otherwise.
4992 SDValue
4993 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
4994   if (!Subtarget->hasAVX())
4995     return SDValue();
4996
4997   EVT VT = Op.getValueType();
4998   DebugLoc dl = Op.getDebugLoc();
4999
5000   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5001          "Unsupported vector type for broadcast.");
5002
5003   SDValue Ld;
5004   bool ConstSplatVal;
5005
5006   switch (Op.getOpcode()) {
5007     default:
5008       // Unknown pattern found.
5009       return SDValue();
5010
5011     case ISD::BUILD_VECTOR: {
5012       // The BUILD_VECTOR node must be a splat.
5013       if (!isSplatVector(Op.getNode()))
5014         return SDValue();
5015
5016       Ld = Op.getOperand(0);
5017       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5018                      Ld.getOpcode() == ISD::ConstantFP);
5019
5020       // The suspected load node has several users. Make sure that all
5021       // of its users are from the BUILD_VECTOR node.
5022       // Constants may have multiple users.
5023       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5024         return SDValue();
5025       break;
5026     }
5027
5028     case ISD::VECTOR_SHUFFLE: {
5029       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5030
5031       // Shuffles must have a splat mask where the first element is
5032       // broadcasted.
5033       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5034         return SDValue();
5035
5036       SDValue Sc = Op.getOperand(0);
5037       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5038           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5039
5040         if (!Subtarget->hasAVX2())
5041           return SDValue();
5042
5043         // Use the register form of the broadcast instruction available on AVX2.
5044         if (VT.is256BitVector())
5045           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5046         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5047       }
5048
5049       Ld = Sc.getOperand(0);
5050       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5051                        Ld.getOpcode() == ISD::ConstantFP);
5052
5053       // The scalar_to_vector node and the suspected
5054       // load node must have exactly one user.
5055       // Constants may have multiple users.
5056       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5057         return SDValue();
5058       break;
5059     }
5060   }
5061
5062   bool Is256 = VT.is256BitVector();
5063
5064   // Handle the broadcasting a single constant scalar from the constant pool
5065   // into a vector. On Sandybridge it is still better to load a constant vector
5066   // from the constant pool and not to broadcast it from a scalar.
5067   if (ConstSplatVal && Subtarget->hasAVX2()) {
5068     EVT CVT = Ld.getValueType();
5069     assert(!CVT.isVector() && "Must not broadcast a vector type");
5070     unsigned ScalarSize = CVT.getSizeInBits();
5071
5072     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5073       const Constant *C = 0;
5074       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5075         C = CI->getConstantIntValue();
5076       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5077         C = CF->getConstantFPValue();
5078
5079       assert(C && "Invalid constant type");
5080
5081       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5082       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5083       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5084                        MachinePointerInfo::getConstantPool(),
5085                        false, false, false, Alignment);
5086
5087       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5088     }
5089   }
5090
5091   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5092   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5093
5094   // Handle AVX2 in-register broadcasts.
5095   if (!IsLoad && Subtarget->hasAVX2() &&
5096       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5097     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5098
5099   // The scalar source must be a normal load.
5100   if (!IsLoad)
5101     return SDValue();
5102
5103   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5104     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5105
5106   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5107   // double since there is no vbroadcastsd xmm
5108   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5109     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5110       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5111   }
5112
5113   // Unsupported broadcast.
5114   return SDValue();
5115 }
5116
5117 SDValue
5118 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5119   DebugLoc dl = Op.getDebugLoc();
5120
5121   EVT VT = Op.getValueType();
5122   EVT ExtVT = VT.getVectorElementType();
5123   unsigned NumElems = Op.getNumOperands();
5124
5125   // Vectors containing all zeros can be matched by pxor and xorps later
5126   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5127     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5128     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5129     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5130       return Op;
5131
5132     return getZeroVector(VT, Subtarget, DAG, dl);
5133   }
5134
5135   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5136   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5137   // vpcmpeqd on 256-bit vectors.
5138   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5139     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5140       return Op;
5141
5142     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5143   }
5144
5145   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5146   if (Broadcast.getNode())
5147     return Broadcast;
5148
5149   unsigned EVTBits = ExtVT.getSizeInBits();
5150
5151   unsigned NumZero  = 0;
5152   unsigned NumNonZero = 0;
5153   unsigned NonZeros = 0;
5154   bool IsAllConstants = true;
5155   SmallSet<SDValue, 8> Values;
5156   for (unsigned i = 0; i < NumElems; ++i) {
5157     SDValue Elt = Op.getOperand(i);
5158     if (Elt.getOpcode() == ISD::UNDEF)
5159       continue;
5160     Values.insert(Elt);
5161     if (Elt.getOpcode() != ISD::Constant &&
5162         Elt.getOpcode() != ISD::ConstantFP)
5163       IsAllConstants = false;
5164     if (X86::isZeroNode(Elt))
5165       NumZero++;
5166     else {
5167       NonZeros |= (1 << i);
5168       NumNonZero++;
5169     }
5170   }
5171
5172   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5173   if (NumNonZero == 0)
5174     return DAG.getUNDEF(VT);
5175
5176   // Special case for single non-zero, non-undef, element.
5177   if (NumNonZero == 1) {
5178     unsigned Idx = CountTrailingZeros_32(NonZeros);
5179     SDValue Item = Op.getOperand(Idx);
5180
5181     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5182     // the value are obviously zero, truncate the value to i32 and do the
5183     // insertion that way.  Only do this if the value is non-constant or if the
5184     // value is a constant being inserted into element 0.  It is cheaper to do
5185     // a constant pool load than it is to do a movd + shuffle.
5186     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5187         (!IsAllConstants || Idx == 0)) {
5188       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5189         // Handle SSE only.
5190         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5191         EVT VecVT = MVT::v4i32;
5192         unsigned VecElts = 4;
5193
5194         // Truncate the value (which may itself be a constant) to i32, and
5195         // convert it to a vector with movd (S2V+shuffle to zero extend).
5196         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5197         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5198         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5199
5200         // Now we have our 32-bit value zero extended in the low element of
5201         // a vector.  If Idx != 0, swizzle it into place.
5202         if (Idx != 0) {
5203           SmallVector<int, 4> Mask;
5204           Mask.push_back(Idx);
5205           for (unsigned i = 1; i != VecElts; ++i)
5206             Mask.push_back(i);
5207           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5208                                       &Mask[0]);
5209         }
5210         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5211       }
5212     }
5213
5214     // If we have a constant or non-constant insertion into the low element of
5215     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5216     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5217     // depending on what the source datatype is.
5218     if (Idx == 0) {
5219       if (NumZero == 0)
5220         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5221
5222       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5223           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5224         if (VT.is256BitVector()) {
5225           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5226           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5227                              Item, DAG.getIntPtrConstant(0));
5228         }
5229         assert(VT.is128BitVector() && "Expected an SSE value type!");
5230         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5231         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5232         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5233       }
5234
5235       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5236         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5237         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5238         if (VT.is256BitVector()) {
5239           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5240           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5241         } else {
5242           assert(VT.is128BitVector() && "Expected an SSE value type!");
5243           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5244         }
5245         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5246       }
5247     }
5248
5249     // Is it a vector logical left shift?
5250     if (NumElems == 2 && Idx == 1 &&
5251         X86::isZeroNode(Op.getOperand(0)) &&
5252         !X86::isZeroNode(Op.getOperand(1))) {
5253       unsigned NumBits = VT.getSizeInBits();
5254       return getVShift(true, VT,
5255                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5256                                    VT, Op.getOperand(1)),
5257                        NumBits/2, DAG, *this, dl);
5258     }
5259
5260     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5261       return SDValue();
5262
5263     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5264     // is a non-constant being inserted into an element other than the low one,
5265     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5266     // movd/movss) to move this into the low element, then shuffle it into
5267     // place.
5268     if (EVTBits == 32) {
5269       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5270
5271       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5272       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5273       SmallVector<int, 8> MaskVec;
5274       for (unsigned i = 0; i != NumElems; ++i)
5275         MaskVec.push_back(i == Idx ? 0 : 1);
5276       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5277     }
5278   }
5279
5280   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5281   if (Values.size() == 1) {
5282     if (EVTBits == 32) {
5283       // Instead of a shuffle like this:
5284       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5285       // Check if it's possible to issue this instead.
5286       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5287       unsigned Idx = CountTrailingZeros_32(NonZeros);
5288       SDValue Item = Op.getOperand(Idx);
5289       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5290         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5291     }
5292     return SDValue();
5293   }
5294
5295   // A vector full of immediates; various special cases are already
5296   // handled, so this is best done with a single constant-pool load.
5297   if (IsAllConstants)
5298     return SDValue();
5299
5300   // For AVX-length vectors, build the individual 128-bit pieces and use
5301   // shuffles to put them in place.
5302   if (VT.is256BitVector()) {
5303     SmallVector<SDValue, 32> V;
5304     for (unsigned i = 0; i != NumElems; ++i)
5305       V.push_back(Op.getOperand(i));
5306
5307     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5308
5309     // Build both the lower and upper subvector.
5310     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5311     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5312                                 NumElems/2);
5313
5314     // Recreate the wider vector with the lower and upper part.
5315     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5316   }
5317
5318   // Let legalizer expand 2-wide build_vectors.
5319   if (EVTBits == 64) {
5320     if (NumNonZero == 1) {
5321       // One half is zero or undef.
5322       unsigned Idx = CountTrailingZeros_32(NonZeros);
5323       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5324                                  Op.getOperand(Idx));
5325       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5326     }
5327     return SDValue();
5328   }
5329
5330   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5331   if (EVTBits == 8 && NumElems == 16) {
5332     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5333                                         Subtarget, *this);
5334     if (V.getNode()) return V;
5335   }
5336
5337   if (EVTBits == 16 && NumElems == 8) {
5338     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5339                                       Subtarget, *this);
5340     if (V.getNode()) return V;
5341   }
5342
5343   // If element VT is == 32 bits, turn it into a number of shuffles.
5344   SmallVector<SDValue, 8> V(NumElems);
5345   if (NumElems == 4 && NumZero > 0) {
5346     for (unsigned i = 0; i < 4; ++i) {
5347       bool isZero = !(NonZeros & (1 << i));
5348       if (isZero)
5349         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5350       else
5351         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5352     }
5353
5354     for (unsigned i = 0; i < 2; ++i) {
5355       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5356         default: break;
5357         case 0:
5358           V[i] = V[i*2];  // Must be a zero vector.
5359           break;
5360         case 1:
5361           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5362           break;
5363         case 2:
5364           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5365           break;
5366         case 3:
5367           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5368           break;
5369       }
5370     }
5371
5372     bool Reverse1 = (NonZeros & 0x3) == 2;
5373     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5374     int MaskVec[] = {
5375       Reverse1 ? 1 : 0,
5376       Reverse1 ? 0 : 1,
5377       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5378       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5379     };
5380     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5381   }
5382
5383   if (Values.size() > 1 && VT.is128BitVector()) {
5384     // Check for a build vector of consecutive loads.
5385     for (unsigned i = 0; i < NumElems; ++i)
5386       V[i] = Op.getOperand(i);
5387
5388     // Check for elements which are consecutive loads.
5389     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5390     if (LD.getNode())
5391       return LD;
5392
5393     // For SSE 4.1, use insertps to put the high elements into the low element.
5394     if (getSubtarget()->hasSSE41()) {
5395       SDValue Result;
5396       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5397         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5398       else
5399         Result = DAG.getUNDEF(VT);
5400
5401       for (unsigned i = 1; i < NumElems; ++i) {
5402         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5403         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5404                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5405       }
5406       return Result;
5407     }
5408
5409     // Otherwise, expand into a number of unpckl*, start by extending each of
5410     // our (non-undef) elements to the full vector width with the element in the
5411     // bottom slot of the vector (which generates no code for SSE).
5412     for (unsigned i = 0; i < NumElems; ++i) {
5413       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5414         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5415       else
5416         V[i] = DAG.getUNDEF(VT);
5417     }
5418
5419     // Next, we iteratively mix elements, e.g. for v4f32:
5420     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5421     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5422     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5423     unsigned EltStride = NumElems >> 1;
5424     while (EltStride != 0) {
5425       for (unsigned i = 0; i < EltStride; ++i) {
5426         // If V[i+EltStride] is undef and this is the first round of mixing,
5427         // then it is safe to just drop this shuffle: V[i] is already in the
5428         // right place, the one element (since it's the first round) being
5429         // inserted as undef can be dropped.  This isn't safe for successive
5430         // rounds because they will permute elements within both vectors.
5431         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5432             EltStride == NumElems/2)
5433           continue;
5434
5435         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5436       }
5437       EltStride >>= 1;
5438     }
5439     return V[0];
5440   }
5441   return SDValue();
5442 }
5443
5444 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5445 // to create 256-bit vectors from two other 128-bit ones.
5446 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5447   DebugLoc dl = Op.getDebugLoc();
5448   EVT ResVT = Op.getValueType();
5449
5450   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5451
5452   SDValue V1 = Op.getOperand(0);
5453   SDValue V2 = Op.getOperand(1);
5454   unsigned NumElems = ResVT.getVectorNumElements();
5455
5456   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5457 }
5458
5459 SDValue
5460 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5461   assert(Op.getNumOperands() == 2);
5462
5463   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5464   // from two other 128-bit ones.
5465   return LowerAVXCONCAT_VECTORS(Op, DAG);
5466 }
5467
5468 // Try to lower a shuffle node into a simple blend instruction.
5469 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5470                                           const X86Subtarget *Subtarget,
5471                                           SelectionDAG &DAG) {
5472   SDValue V1 = SVOp->getOperand(0);
5473   SDValue V2 = SVOp->getOperand(1);
5474   DebugLoc dl = SVOp->getDebugLoc();
5475   MVT VT = SVOp->getValueType(0).getSimpleVT();
5476   unsigned NumElems = VT.getVectorNumElements();
5477
5478   if (!Subtarget->hasSSE41())
5479     return SDValue();
5480
5481   unsigned ISDNo = 0;
5482   MVT OpTy;
5483
5484   switch (VT.SimpleTy) {
5485   default: return SDValue();
5486   case MVT::v8i16:
5487     ISDNo = X86ISD::BLENDPW;
5488     OpTy = MVT::v8i16;
5489     break;
5490   case MVT::v4i32:
5491   case MVT::v4f32:
5492     ISDNo = X86ISD::BLENDPS;
5493     OpTy = MVT::v4f32;
5494     break;
5495   case MVT::v2i64:
5496   case MVT::v2f64:
5497     ISDNo = X86ISD::BLENDPD;
5498     OpTy = MVT::v2f64;
5499     break;
5500   case MVT::v8i32:
5501   case MVT::v8f32:
5502     if (!Subtarget->hasAVX())
5503       return SDValue();
5504     ISDNo = X86ISD::BLENDPS;
5505     OpTy = MVT::v8f32;
5506     break;
5507   case MVT::v4i64:
5508   case MVT::v4f64:
5509     if (!Subtarget->hasAVX())
5510       return SDValue();
5511     ISDNo = X86ISD::BLENDPD;
5512     OpTy = MVT::v4f64;
5513     break;
5514   }
5515   assert(ISDNo && "Invalid Op Number");
5516
5517   unsigned MaskVals = 0;
5518
5519   for (unsigned i = 0; i != NumElems; ++i) {
5520     int EltIdx = SVOp->getMaskElt(i);
5521     if (EltIdx == (int)i || EltIdx < 0)
5522       MaskVals |= (1<<i);
5523     else if (EltIdx == (int)(i + NumElems))
5524       continue; // Bit is set to zero;
5525     else
5526       return SDValue();
5527   }
5528
5529   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5530   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5531   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5532                              DAG.getConstant(MaskVals, MVT::i32));
5533   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5534 }
5535
5536 // v8i16 shuffles - Prefer shuffles in the following order:
5537 // 1. [all]   pshuflw, pshufhw, optional move
5538 // 2. [ssse3] 1 x pshufb
5539 // 3. [ssse3] 2 x pshufb + 1 x por
5540 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5541 SDValue
5542 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5543                                             SelectionDAG &DAG) const {
5544   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5545   SDValue V1 = SVOp->getOperand(0);
5546   SDValue V2 = SVOp->getOperand(1);
5547   DebugLoc dl = SVOp->getDebugLoc();
5548   SmallVector<int, 8> MaskVals;
5549
5550   // Determine if more than 1 of the words in each of the low and high quadwords
5551   // of the result come from the same quadword of one of the two inputs.  Undef
5552   // mask values count as coming from any quadword, for better codegen.
5553   unsigned LoQuad[] = { 0, 0, 0, 0 };
5554   unsigned HiQuad[] = { 0, 0, 0, 0 };
5555   std::bitset<4> InputQuads;
5556   for (unsigned i = 0; i < 8; ++i) {
5557     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5558     int EltIdx = SVOp->getMaskElt(i);
5559     MaskVals.push_back(EltIdx);
5560     if (EltIdx < 0) {
5561       ++Quad[0];
5562       ++Quad[1];
5563       ++Quad[2];
5564       ++Quad[3];
5565       continue;
5566     }
5567     ++Quad[EltIdx / 4];
5568     InputQuads.set(EltIdx / 4);
5569   }
5570
5571   int BestLoQuad = -1;
5572   unsigned MaxQuad = 1;
5573   for (unsigned i = 0; i < 4; ++i) {
5574     if (LoQuad[i] > MaxQuad) {
5575       BestLoQuad = i;
5576       MaxQuad = LoQuad[i];
5577     }
5578   }
5579
5580   int BestHiQuad = -1;
5581   MaxQuad = 1;
5582   for (unsigned i = 0; i < 4; ++i) {
5583     if (HiQuad[i] > MaxQuad) {
5584       BestHiQuad = i;
5585       MaxQuad = HiQuad[i];
5586     }
5587   }
5588
5589   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5590   // of the two input vectors, shuffle them into one input vector so only a
5591   // single pshufb instruction is necessary. If There are more than 2 input
5592   // quads, disable the next transformation since it does not help SSSE3.
5593   bool V1Used = InputQuads[0] || InputQuads[1];
5594   bool V2Used = InputQuads[2] || InputQuads[3];
5595   if (Subtarget->hasSSSE3()) {
5596     if (InputQuads.count() == 2 && V1Used && V2Used) {
5597       BestLoQuad = InputQuads[0] ? 0 : 1;
5598       BestHiQuad = InputQuads[2] ? 2 : 3;
5599     }
5600     if (InputQuads.count() > 2) {
5601       BestLoQuad = -1;
5602       BestHiQuad = -1;
5603     }
5604   }
5605
5606   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5607   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5608   // words from all 4 input quadwords.
5609   SDValue NewV;
5610   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5611     int MaskV[] = {
5612       BestLoQuad < 0 ? 0 : BestLoQuad,
5613       BestHiQuad < 0 ? 1 : BestHiQuad
5614     };
5615     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5616                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5617                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5618     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5619
5620     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5621     // source words for the shuffle, to aid later transformations.
5622     bool AllWordsInNewV = true;
5623     bool InOrder[2] = { true, true };
5624     for (unsigned i = 0; i != 8; ++i) {
5625       int idx = MaskVals[i];
5626       if (idx != (int)i)
5627         InOrder[i/4] = false;
5628       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5629         continue;
5630       AllWordsInNewV = false;
5631       break;
5632     }
5633
5634     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5635     if (AllWordsInNewV) {
5636       for (int i = 0; i != 8; ++i) {
5637         int idx = MaskVals[i];
5638         if (idx < 0)
5639           continue;
5640         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5641         if ((idx != i) && idx < 4)
5642           pshufhw = false;
5643         if ((idx != i) && idx > 3)
5644           pshuflw = false;
5645       }
5646       V1 = NewV;
5647       V2Used = false;
5648       BestLoQuad = 0;
5649       BestHiQuad = 1;
5650     }
5651
5652     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5653     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5654     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5655       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5656       unsigned TargetMask = 0;
5657       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5658                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5659       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5660       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5661                              getShufflePSHUFLWImmediate(SVOp);
5662       V1 = NewV.getOperand(0);
5663       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5664     }
5665   }
5666
5667   // If we have SSSE3, and all words of the result are from 1 input vector,
5668   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5669   // is present, fall back to case 4.
5670   if (Subtarget->hasSSSE3()) {
5671     SmallVector<SDValue,16> pshufbMask;
5672
5673     // If we have elements from both input vectors, set the high bit of the
5674     // shuffle mask element to zero out elements that come from V2 in the V1
5675     // mask, and elements that come from V1 in the V2 mask, so that the two
5676     // results can be OR'd together.
5677     bool TwoInputs = V1Used && V2Used;
5678     for (unsigned i = 0; i != 8; ++i) {
5679       int EltIdx = MaskVals[i] * 2;
5680       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5681       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5682       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5683       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5684     }
5685     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5686     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5687                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5688                                  MVT::v16i8, &pshufbMask[0], 16));
5689     if (!TwoInputs)
5690       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5691
5692     // Calculate the shuffle mask for the second input, shuffle it, and
5693     // OR it with the first shuffled input.
5694     pshufbMask.clear();
5695     for (unsigned i = 0; i != 8; ++i) {
5696       int EltIdx = MaskVals[i] * 2;
5697       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5698       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5699       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5700       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5701     }
5702     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5703     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5704                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5705                                  MVT::v16i8, &pshufbMask[0], 16));
5706     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5707     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5708   }
5709
5710   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5711   // and update MaskVals with new element order.
5712   std::bitset<8> InOrder;
5713   if (BestLoQuad >= 0) {
5714     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5715     for (int i = 0; i != 4; ++i) {
5716       int idx = MaskVals[i];
5717       if (idx < 0) {
5718         InOrder.set(i);
5719       } else if ((idx / 4) == BestLoQuad) {
5720         MaskV[i] = idx & 3;
5721         InOrder.set(i);
5722       }
5723     }
5724     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5725                                 &MaskV[0]);
5726
5727     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5728       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5729       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5730                                   NewV.getOperand(0),
5731                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5732     }
5733   }
5734
5735   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5736   // and update MaskVals with the new element order.
5737   if (BestHiQuad >= 0) {
5738     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5739     for (unsigned i = 4; i != 8; ++i) {
5740       int idx = MaskVals[i];
5741       if (idx < 0) {
5742         InOrder.set(i);
5743       } else if ((idx / 4) == BestHiQuad) {
5744         MaskV[i] = (idx & 3) + 4;
5745         InOrder.set(i);
5746       }
5747     }
5748     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5749                                 &MaskV[0]);
5750
5751     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5752       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5753       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5754                                   NewV.getOperand(0),
5755                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5756     }
5757   }
5758
5759   // In case BestHi & BestLo were both -1, which means each quadword has a word
5760   // from each of the four input quadwords, calculate the InOrder bitvector now
5761   // before falling through to the insert/extract cleanup.
5762   if (BestLoQuad == -1 && BestHiQuad == -1) {
5763     NewV = V1;
5764     for (int i = 0; i != 8; ++i)
5765       if (MaskVals[i] < 0 || MaskVals[i] == i)
5766         InOrder.set(i);
5767   }
5768
5769   // The other elements are put in the right place using pextrw and pinsrw.
5770   for (unsigned i = 0; i != 8; ++i) {
5771     if (InOrder[i])
5772       continue;
5773     int EltIdx = MaskVals[i];
5774     if (EltIdx < 0)
5775       continue;
5776     SDValue ExtOp = (EltIdx < 8) ?
5777       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5778                   DAG.getIntPtrConstant(EltIdx)) :
5779       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5780                   DAG.getIntPtrConstant(EltIdx - 8));
5781     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5782                        DAG.getIntPtrConstant(i));
5783   }
5784   return NewV;
5785 }
5786
5787 // v16i8 shuffles - Prefer shuffles in the following order:
5788 // 1. [ssse3] 1 x pshufb
5789 // 2. [ssse3] 2 x pshufb + 1 x por
5790 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5791 static
5792 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5793                                  SelectionDAG &DAG,
5794                                  const X86TargetLowering &TLI) {
5795   SDValue V1 = SVOp->getOperand(0);
5796   SDValue V2 = SVOp->getOperand(1);
5797   DebugLoc dl = SVOp->getDebugLoc();
5798   ArrayRef<int> MaskVals = SVOp->getMask();
5799
5800   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5801
5802   // If we have SSSE3, case 1 is generated when all result bytes come from
5803   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5804   // present, fall back to case 3.
5805
5806   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5807   if (TLI.getSubtarget()->hasSSSE3()) {
5808     SmallVector<SDValue,16> pshufbMask;
5809
5810     // If all result elements are from one input vector, then only translate
5811     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5812     //
5813     // Otherwise, we have elements from both input vectors, and must zero out
5814     // elements that come from V2 in the first mask, and V1 in the second mask
5815     // so that we can OR them together.
5816     for (unsigned i = 0; i != 16; ++i) {
5817       int EltIdx = MaskVals[i];
5818       if (EltIdx < 0 || EltIdx >= 16)
5819         EltIdx = 0x80;
5820       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5821     }
5822     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5823                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5824                                  MVT::v16i8, &pshufbMask[0], 16));
5825     if (V2IsUndef)
5826       return V1;
5827
5828     // Calculate the shuffle mask for the second input, shuffle it, and
5829     // OR it with the first shuffled input.
5830     pshufbMask.clear();
5831     for (unsigned i = 0; i != 16; ++i) {
5832       int EltIdx = MaskVals[i];
5833       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5834       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5835     }
5836     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5837                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5838                                  MVT::v16i8, &pshufbMask[0], 16));
5839     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5840   }
5841
5842   // No SSSE3 - Calculate in place words and then fix all out of place words
5843   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5844   // the 16 different words that comprise the two doublequadword input vectors.
5845   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5846   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5847   SDValue NewV = V1;
5848   for (int i = 0; i != 8; ++i) {
5849     int Elt0 = MaskVals[i*2];
5850     int Elt1 = MaskVals[i*2+1];
5851
5852     // This word of the result is all undef, skip it.
5853     if (Elt0 < 0 && Elt1 < 0)
5854       continue;
5855
5856     // This word of the result is already in the correct place, skip it.
5857     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5858       continue;
5859
5860     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5861     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5862     SDValue InsElt;
5863
5864     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5865     // using a single extract together, load it and store it.
5866     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5867       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5868                            DAG.getIntPtrConstant(Elt1 / 2));
5869       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5870                         DAG.getIntPtrConstant(i));
5871       continue;
5872     }
5873
5874     // If Elt1 is defined, extract it from the appropriate source.  If the
5875     // source byte is not also odd, shift the extracted word left 8 bits
5876     // otherwise clear the bottom 8 bits if we need to do an or.
5877     if (Elt1 >= 0) {
5878       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5879                            DAG.getIntPtrConstant(Elt1 / 2));
5880       if ((Elt1 & 1) == 0)
5881         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5882                              DAG.getConstant(8,
5883                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5884       else if (Elt0 >= 0)
5885         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5886                              DAG.getConstant(0xFF00, MVT::i16));
5887     }
5888     // If Elt0 is defined, extract it from the appropriate source.  If the
5889     // source byte is not also even, shift the extracted word right 8 bits. If
5890     // Elt1 was also defined, OR the extracted values together before
5891     // inserting them in the result.
5892     if (Elt0 >= 0) {
5893       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5894                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5895       if ((Elt0 & 1) != 0)
5896         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5897                               DAG.getConstant(8,
5898                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5899       else if (Elt1 >= 0)
5900         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5901                              DAG.getConstant(0x00FF, MVT::i16));
5902       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5903                          : InsElt0;
5904     }
5905     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5906                        DAG.getIntPtrConstant(i));
5907   }
5908   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5909 }
5910
5911 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5912 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5913 /// done when every pair / quad of shuffle mask elements point to elements in
5914 /// the right sequence. e.g.
5915 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5916 static
5917 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5918                                  SelectionDAG &DAG, DebugLoc dl) {
5919   MVT VT = SVOp->getValueType(0).getSimpleVT();
5920   unsigned NumElems = VT.getVectorNumElements();
5921   MVT NewVT;
5922   unsigned Scale;
5923   switch (VT.SimpleTy) {
5924   default: llvm_unreachable("Unexpected!");
5925   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
5926   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
5927   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
5928   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
5929   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5930   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
5931   }
5932
5933   SmallVector<int, 8> MaskVec;
5934   for (unsigned i = 0; i != NumElems; i += Scale) {
5935     int StartIdx = -1;
5936     for (unsigned j = 0; j != Scale; ++j) {
5937       int EltIdx = SVOp->getMaskElt(i+j);
5938       if (EltIdx < 0)
5939         continue;
5940       if (StartIdx < 0)
5941         StartIdx = (EltIdx / Scale);
5942       if (EltIdx != (int)(StartIdx*Scale + j))
5943         return SDValue();
5944     }
5945     MaskVec.push_back(StartIdx);
5946   }
5947
5948   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
5949   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
5950   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5951 }
5952
5953 /// getVZextMovL - Return a zero-extending vector move low node.
5954 ///
5955 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5956                             SDValue SrcOp, SelectionDAG &DAG,
5957                             const X86Subtarget *Subtarget, DebugLoc dl) {
5958   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5959     LoadSDNode *LD = NULL;
5960     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5961       LD = dyn_cast<LoadSDNode>(SrcOp);
5962     if (!LD) {
5963       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5964       // instead.
5965       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5966       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5967           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5968           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5969           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5970         // PR2108
5971         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5972         return DAG.getNode(ISD::BITCAST, dl, VT,
5973                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5974                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5975                                                    OpVT,
5976                                                    SrcOp.getOperand(0)
5977                                                           .getOperand(0))));
5978       }
5979     }
5980   }
5981
5982   return DAG.getNode(ISD::BITCAST, dl, VT,
5983                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5984                                  DAG.getNode(ISD::BITCAST, dl,
5985                                              OpVT, SrcOp)));
5986 }
5987
5988 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5989 /// which could not be matched by any known target speficic shuffle
5990 static SDValue
5991 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5992
5993   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
5994   if (NewOp.getNode())
5995     return NewOp;
5996
5997   EVT VT = SVOp->getValueType(0);
5998
5999   unsigned NumElems = VT.getVectorNumElements();
6000   unsigned NumLaneElems = NumElems / 2;
6001
6002   DebugLoc dl = SVOp->getDebugLoc();
6003   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6004   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6005   SDValue Output[2];
6006
6007   SmallVector<int, 16> Mask;
6008   for (unsigned l = 0; l < 2; ++l) {
6009     // Build a shuffle mask for the output, discovering on the fly which
6010     // input vectors to use as shuffle operands (recorded in InputUsed).
6011     // If building a suitable shuffle vector proves too hard, then bail
6012     // out with UseBuildVector set.
6013     bool UseBuildVector = false;
6014     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6015     unsigned LaneStart = l * NumLaneElems;
6016     for (unsigned i = 0; i != NumLaneElems; ++i) {
6017       // The mask element.  This indexes into the input.
6018       int Idx = SVOp->getMaskElt(i+LaneStart);
6019       if (Idx < 0) {
6020         // the mask element does not index into any input vector.
6021         Mask.push_back(-1);
6022         continue;
6023       }
6024
6025       // The input vector this mask element indexes into.
6026       int Input = Idx / NumLaneElems;
6027
6028       // Turn the index into an offset from the start of the input vector.
6029       Idx -= Input * NumLaneElems;
6030
6031       // Find or create a shuffle vector operand to hold this input.
6032       unsigned OpNo;
6033       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6034         if (InputUsed[OpNo] == Input)
6035           // This input vector is already an operand.
6036           break;
6037         if (InputUsed[OpNo] < 0) {
6038           // Create a new operand for this input vector.
6039           InputUsed[OpNo] = Input;
6040           break;
6041         }
6042       }
6043
6044       if (OpNo >= array_lengthof(InputUsed)) {
6045         // More than two input vectors used!  Give up on trying to create a
6046         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6047         UseBuildVector = true;
6048         break;
6049       }
6050
6051       // Add the mask index for the new shuffle vector.
6052       Mask.push_back(Idx + OpNo * NumLaneElems);
6053     }
6054
6055     if (UseBuildVector) {
6056       SmallVector<SDValue, 16> SVOps;
6057       for (unsigned i = 0; i != NumLaneElems; ++i) {
6058         // The mask element.  This indexes into the input.
6059         int Idx = SVOp->getMaskElt(i+LaneStart);
6060         if (Idx < 0) {
6061           SVOps.push_back(DAG.getUNDEF(EltVT));
6062           continue;
6063         }
6064
6065         // The input vector this mask element indexes into.
6066         int Input = Idx / NumElems;
6067
6068         // Turn the index into an offset from the start of the input vector.
6069         Idx -= Input * NumElems;
6070
6071         // Extract the vector element by hand.
6072         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6073                                     SVOp->getOperand(Input),
6074                                     DAG.getIntPtrConstant(Idx)));
6075       }
6076
6077       // Construct the output using a BUILD_VECTOR.
6078       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6079                               SVOps.size());
6080     } else if (InputUsed[0] < 0) {
6081       // No input vectors were used! The result is undefined.
6082       Output[l] = DAG.getUNDEF(NVT);
6083     } else {
6084       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6085                                         (InputUsed[0] % 2) * NumLaneElems,
6086                                         DAG, dl);
6087       // If only one input was used, use an undefined vector for the other.
6088       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6089         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6090                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6091       // At least one input vector was used. Create a new shuffle vector.
6092       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6093     }
6094
6095     Mask.clear();
6096   }
6097
6098   // Concatenate the result back
6099   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6100 }
6101
6102 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6103 /// 4 elements, and match them with several different shuffle types.
6104 static SDValue
6105 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6106   SDValue V1 = SVOp->getOperand(0);
6107   SDValue V2 = SVOp->getOperand(1);
6108   DebugLoc dl = SVOp->getDebugLoc();
6109   EVT VT = SVOp->getValueType(0);
6110
6111   assert(VT.is128BitVector() && "Unsupported vector size");
6112
6113   std::pair<int, int> Locs[4];
6114   int Mask1[] = { -1, -1, -1, -1 };
6115   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6116
6117   unsigned NumHi = 0;
6118   unsigned NumLo = 0;
6119   for (unsigned i = 0; i != 4; ++i) {
6120     int Idx = PermMask[i];
6121     if (Idx < 0) {
6122       Locs[i] = std::make_pair(-1, -1);
6123     } else {
6124       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6125       if (Idx < 4) {
6126         Locs[i] = std::make_pair(0, NumLo);
6127         Mask1[NumLo] = Idx;
6128         NumLo++;
6129       } else {
6130         Locs[i] = std::make_pair(1, NumHi);
6131         if (2+NumHi < 4)
6132           Mask1[2+NumHi] = Idx;
6133         NumHi++;
6134       }
6135     }
6136   }
6137
6138   if (NumLo <= 2 && NumHi <= 2) {
6139     // If no more than two elements come from either vector. This can be
6140     // implemented with two shuffles. First shuffle gather the elements.
6141     // The second shuffle, which takes the first shuffle as both of its
6142     // vector operands, put the elements into the right order.
6143     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6144
6145     int Mask2[] = { -1, -1, -1, -1 };
6146
6147     for (unsigned i = 0; i != 4; ++i)
6148       if (Locs[i].first != -1) {
6149         unsigned Idx = (i < 2) ? 0 : 4;
6150         Idx += Locs[i].first * 2 + Locs[i].second;
6151         Mask2[i] = Idx;
6152       }
6153
6154     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6155   }
6156
6157   if (NumLo == 3 || NumHi == 3) {
6158     // Otherwise, we must have three elements from one vector, call it X, and
6159     // one element from the other, call it Y.  First, use a shufps to build an
6160     // intermediate vector with the one element from Y and the element from X
6161     // that will be in the same half in the final destination (the indexes don't
6162     // matter). Then, use a shufps to build the final vector, taking the half
6163     // containing the element from Y from the intermediate, and the other half
6164     // from X.
6165     if (NumHi == 3) {
6166       // Normalize it so the 3 elements come from V1.
6167       CommuteVectorShuffleMask(PermMask, 4);
6168       std::swap(V1, V2);
6169     }
6170
6171     // Find the element from V2.
6172     unsigned HiIndex;
6173     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6174       int Val = PermMask[HiIndex];
6175       if (Val < 0)
6176         continue;
6177       if (Val >= 4)
6178         break;
6179     }
6180
6181     Mask1[0] = PermMask[HiIndex];
6182     Mask1[1] = -1;
6183     Mask1[2] = PermMask[HiIndex^1];
6184     Mask1[3] = -1;
6185     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6186
6187     if (HiIndex >= 2) {
6188       Mask1[0] = PermMask[0];
6189       Mask1[1] = PermMask[1];
6190       Mask1[2] = HiIndex & 1 ? 6 : 4;
6191       Mask1[3] = HiIndex & 1 ? 4 : 6;
6192       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6193     }
6194
6195     Mask1[0] = HiIndex & 1 ? 2 : 0;
6196     Mask1[1] = HiIndex & 1 ? 0 : 2;
6197     Mask1[2] = PermMask[2];
6198     Mask1[3] = PermMask[3];
6199     if (Mask1[2] >= 0)
6200       Mask1[2] += 4;
6201     if (Mask1[3] >= 0)
6202       Mask1[3] += 4;
6203     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6204   }
6205
6206   // Break it into (shuffle shuffle_hi, shuffle_lo).
6207   int LoMask[] = { -1, -1, -1, -1 };
6208   int HiMask[] = { -1, -1, -1, -1 };
6209
6210   int *MaskPtr = LoMask;
6211   unsigned MaskIdx = 0;
6212   unsigned LoIdx = 0;
6213   unsigned HiIdx = 2;
6214   for (unsigned i = 0; i != 4; ++i) {
6215     if (i == 2) {
6216       MaskPtr = HiMask;
6217       MaskIdx = 1;
6218       LoIdx = 0;
6219       HiIdx = 2;
6220     }
6221     int Idx = PermMask[i];
6222     if (Idx < 0) {
6223       Locs[i] = std::make_pair(-1, -1);
6224     } else if (Idx < 4) {
6225       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6226       MaskPtr[LoIdx] = Idx;
6227       LoIdx++;
6228     } else {
6229       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6230       MaskPtr[HiIdx] = Idx;
6231       HiIdx++;
6232     }
6233   }
6234
6235   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6236   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6237   int MaskOps[] = { -1, -1, -1, -1 };
6238   for (unsigned i = 0; i != 4; ++i)
6239     if (Locs[i].first != -1)
6240       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6241   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6242 }
6243
6244 static bool MayFoldVectorLoad(SDValue V) {
6245   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6246     V = V.getOperand(0);
6247   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6248     V = V.getOperand(0);
6249   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6250       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6251     // BUILD_VECTOR (load), undef
6252     V = V.getOperand(0);
6253   if (MayFoldLoad(V))
6254     return true;
6255   return false;
6256 }
6257
6258 // FIXME: the version above should always be used. Since there's
6259 // a bug where several vector shuffles can't be folded because the
6260 // DAG is not updated during lowering and a node claims to have two
6261 // uses while it only has one, use this version, and let isel match
6262 // another instruction if the load really happens to have more than
6263 // one use. Remove this version after this bug get fixed.
6264 // rdar://8434668, PR8156
6265 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6266   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6267     V = V.getOperand(0);
6268   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6269     V = V.getOperand(0);
6270   if (ISD::isNormalLoad(V.getNode()))
6271     return true;
6272   return false;
6273 }
6274
6275 static
6276 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6277   EVT VT = Op.getValueType();
6278
6279   // Canonizalize to v2f64.
6280   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6281   return DAG.getNode(ISD::BITCAST, dl, VT,
6282                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6283                                           V1, DAG));
6284 }
6285
6286 static
6287 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6288                         bool HasSSE2) {
6289   SDValue V1 = Op.getOperand(0);
6290   SDValue V2 = Op.getOperand(1);
6291   EVT VT = Op.getValueType();
6292
6293   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6294
6295   if (HasSSE2 && VT == MVT::v2f64)
6296     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6297
6298   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6299   return DAG.getNode(ISD::BITCAST, dl, VT,
6300                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6301                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6302                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6303 }
6304
6305 static
6306 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6307   SDValue V1 = Op.getOperand(0);
6308   SDValue V2 = Op.getOperand(1);
6309   EVT VT = Op.getValueType();
6310
6311   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6312          "unsupported shuffle type");
6313
6314   if (V2.getOpcode() == ISD::UNDEF)
6315     V2 = V1;
6316
6317   // v4i32 or v4f32
6318   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6319 }
6320
6321 static
6322 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6323   SDValue V1 = Op.getOperand(0);
6324   SDValue V2 = Op.getOperand(1);
6325   EVT VT = Op.getValueType();
6326   unsigned NumElems = VT.getVectorNumElements();
6327
6328   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6329   // operand of these instructions is only memory, so check if there's a
6330   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6331   // same masks.
6332   bool CanFoldLoad = false;
6333
6334   // Trivial case, when V2 comes from a load.
6335   if (MayFoldVectorLoad(V2))
6336     CanFoldLoad = true;
6337
6338   // When V1 is a load, it can be folded later into a store in isel, example:
6339   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6340   //    turns into:
6341   //  (MOVLPSmr addr:$src1, VR128:$src2)
6342   // So, recognize this potential and also use MOVLPS or MOVLPD
6343   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6344     CanFoldLoad = true;
6345
6346   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6347   if (CanFoldLoad) {
6348     if (HasSSE2 && NumElems == 2)
6349       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6350
6351     if (NumElems == 4)
6352       // If we don't care about the second element, proceed to use movss.
6353       if (SVOp->getMaskElt(1) != -1)
6354         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6355   }
6356
6357   // movl and movlp will both match v2i64, but v2i64 is never matched by
6358   // movl earlier because we make it strict to avoid messing with the movlp load
6359   // folding logic (see the code above getMOVLP call). Match it here then,
6360   // this is horrible, but will stay like this until we move all shuffle
6361   // matching to x86 specific nodes. Note that for the 1st condition all
6362   // types are matched with movsd.
6363   if (HasSSE2) {
6364     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6365     // as to remove this logic from here, as much as possible
6366     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6367       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6368     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6369   }
6370
6371   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6372
6373   // Invert the operand order and use SHUFPS to match it.
6374   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6375                               getShuffleSHUFImmediate(SVOp), DAG);
6376 }
6377
6378 SDValue
6379 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6380   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6381   EVT VT = Op.getValueType();
6382   DebugLoc dl = Op.getDebugLoc();
6383   SDValue V1 = Op.getOperand(0);
6384   SDValue V2 = Op.getOperand(1);
6385
6386   if (isZeroShuffle(SVOp))
6387     return getZeroVector(VT, Subtarget, DAG, dl);
6388
6389   // Handle splat operations
6390   if (SVOp->isSplat()) {
6391     unsigned NumElem = VT.getVectorNumElements();
6392     int Size = VT.getSizeInBits();
6393
6394     // Use vbroadcast whenever the splat comes from a foldable load
6395     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6396     if (Broadcast.getNode())
6397       return Broadcast;
6398
6399     // Handle splats by matching through known shuffle masks
6400     if ((Size == 128 && NumElem <= 4) ||
6401         (Size == 256 && NumElem < 8))
6402       return SDValue();
6403
6404     // All remaning splats are promoted to target supported vector shuffles.
6405     return PromoteSplat(SVOp, DAG);
6406   }
6407
6408   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6409   // do it!
6410   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6411       VT == MVT::v16i16 || VT == MVT::v32i8) {
6412     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6413     if (NewOp.getNode())
6414       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6415   } else if ((VT == MVT::v4i32 ||
6416              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6417     // FIXME: Figure out a cleaner way to do this.
6418     // Try to make use of movq to zero out the top part.
6419     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6420       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6421       if (NewOp.getNode()) {
6422         EVT NewVT = NewOp.getValueType();
6423         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6424                                NewVT, true, false))
6425           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6426                               DAG, Subtarget, dl);
6427       }
6428     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6429       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6430       if (NewOp.getNode()) {
6431         EVT NewVT = NewOp.getValueType();
6432         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6433           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6434                               DAG, Subtarget, dl);
6435       }
6436     }
6437   }
6438   return SDValue();
6439 }
6440
6441 SDValue
6442 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6443   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6444   SDValue V1 = Op.getOperand(0);
6445   SDValue V2 = Op.getOperand(1);
6446   EVT VT = Op.getValueType();
6447   DebugLoc dl = Op.getDebugLoc();
6448   unsigned NumElems = VT.getVectorNumElements();
6449   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6450   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6451   bool V1IsSplat = false;
6452   bool V2IsSplat = false;
6453   bool HasSSE2 = Subtarget->hasSSE2();
6454   bool HasAVX    = Subtarget->hasAVX();
6455   bool HasAVX2   = Subtarget->hasAVX2();
6456   MachineFunction &MF = DAG.getMachineFunction();
6457   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6458
6459   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6460
6461   if (V1IsUndef && V2IsUndef)
6462     return DAG.getUNDEF(VT);
6463
6464   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6465
6466   // Vector shuffle lowering takes 3 steps:
6467   //
6468   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6469   //    narrowing and commutation of operands should be handled.
6470   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6471   //    shuffle nodes.
6472   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6473   //    so the shuffle can be broken into other shuffles and the legalizer can
6474   //    try the lowering again.
6475   //
6476   // The general idea is that no vector_shuffle operation should be left to
6477   // be matched during isel, all of them must be converted to a target specific
6478   // node here.
6479
6480   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6481   // narrowing and commutation of operands should be handled. The actual code
6482   // doesn't include all of those, work in progress...
6483   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6484   if (NewOp.getNode())
6485     return NewOp;
6486
6487   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6488
6489   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6490   // unpckh_undef). Only use pshufd if speed is more important than size.
6491   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6492     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6493   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6494     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6495
6496   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6497       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6498     return getMOVDDup(Op, dl, V1, DAG);
6499
6500   if (isMOVHLPS_v_undef_Mask(M, VT))
6501     return getMOVHighToLow(Op, dl, DAG);
6502
6503   // Use to match splats
6504   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6505       (VT == MVT::v2f64 || VT == MVT::v2i64))
6506     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6507
6508   if (isPSHUFDMask(M, VT)) {
6509     // The actual implementation will match the mask in the if above and then
6510     // during isel it can match several different instructions, not only pshufd
6511     // as its name says, sad but true, emulate the behavior for now...
6512     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6513       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6514
6515     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6516
6517     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6518       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6519
6520     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6521       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6522
6523     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6524                                 TargetMask, DAG);
6525   }
6526
6527   // Check if this can be converted into a logical shift.
6528   bool isLeft = false;
6529   unsigned ShAmt = 0;
6530   SDValue ShVal;
6531   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6532   if (isShift && ShVal.hasOneUse()) {
6533     // If the shifted value has multiple uses, it may be cheaper to use
6534     // v_set0 + movlhps or movhlps, etc.
6535     EVT EltVT = VT.getVectorElementType();
6536     ShAmt *= EltVT.getSizeInBits();
6537     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6538   }
6539
6540   if (isMOVLMask(M, VT)) {
6541     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6542       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6543     if (!isMOVLPMask(M, VT)) {
6544       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6545         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6546
6547       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6548         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6549     }
6550   }
6551
6552   // FIXME: fold these into legal mask.
6553   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6554     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6555
6556   if (isMOVHLPSMask(M, VT))
6557     return getMOVHighToLow(Op, dl, DAG);
6558
6559   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6560     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6561
6562   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6563     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6564
6565   if (isMOVLPMask(M, VT))
6566     return getMOVLP(Op, dl, DAG, HasSSE2);
6567
6568   if (ShouldXformToMOVHLPS(M, VT) ||
6569       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6570     return CommuteVectorShuffle(SVOp, DAG);
6571
6572   if (isShift) {
6573     // No better options. Use a vshldq / vsrldq.
6574     EVT EltVT = VT.getVectorElementType();
6575     ShAmt *= EltVT.getSizeInBits();
6576     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6577   }
6578
6579   bool Commuted = false;
6580   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6581   // 1,1,1,1 -> v8i16 though.
6582   V1IsSplat = isSplatVector(V1.getNode());
6583   V2IsSplat = isSplatVector(V2.getNode());
6584
6585   // Canonicalize the splat or undef, if present, to be on the RHS.
6586   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6587     CommuteVectorShuffleMask(M, NumElems);
6588     std::swap(V1, V2);
6589     std::swap(V1IsSplat, V2IsSplat);
6590     Commuted = true;
6591   }
6592
6593   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6594     // Shuffling low element of v1 into undef, just return v1.
6595     if (V2IsUndef)
6596       return V1;
6597     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6598     // the instruction selector will not match, so get a canonical MOVL with
6599     // swapped operands to undo the commute.
6600     return getMOVL(DAG, dl, VT, V2, V1);
6601   }
6602
6603   if (isUNPCKLMask(M, VT, HasAVX2))
6604     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6605
6606   if (isUNPCKHMask(M, VT, HasAVX2))
6607     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6608
6609   if (V2IsSplat) {
6610     // Normalize mask so all entries that point to V2 points to its first
6611     // element then try to match unpck{h|l} again. If match, return a
6612     // new vector_shuffle with the corrected mask.p
6613     SmallVector<int, 8> NewMask(M.begin(), M.end());
6614     NormalizeMask(NewMask, NumElems);
6615     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6616       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6617     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6618       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6619   }
6620
6621   if (Commuted) {
6622     // Commute is back and try unpck* again.
6623     // FIXME: this seems wrong.
6624     CommuteVectorShuffleMask(M, NumElems);
6625     std::swap(V1, V2);
6626     std::swap(V1IsSplat, V2IsSplat);
6627     Commuted = false;
6628
6629     if (isUNPCKLMask(M, VT, HasAVX2))
6630       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6631
6632     if (isUNPCKHMask(M, VT, HasAVX2))
6633       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6634   }
6635
6636   // Normalize the node to match x86 shuffle ops if needed
6637   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6638     return CommuteVectorShuffle(SVOp, DAG);
6639
6640   // The checks below are all present in isShuffleMaskLegal, but they are
6641   // inlined here right now to enable us to directly emit target specific
6642   // nodes, and remove one by one until they don't return Op anymore.
6643
6644   if (isPALIGNRMask(M, VT, Subtarget))
6645     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6646                                 getShufflePALIGNRImmediate(SVOp),
6647                                 DAG);
6648
6649   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6650       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6651     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6652       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6653   }
6654
6655   if (isPSHUFHWMask(M, VT, HasAVX2))
6656     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6657                                 getShufflePSHUFHWImmediate(SVOp),
6658                                 DAG);
6659
6660   if (isPSHUFLWMask(M, VT, HasAVX2))
6661     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6662                                 getShufflePSHUFLWImmediate(SVOp),
6663                                 DAG);
6664
6665   if (isSHUFPMask(M, VT, HasAVX))
6666     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6667                                 getShuffleSHUFImmediate(SVOp), DAG);
6668
6669   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6670     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6671   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6672     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6673
6674   //===--------------------------------------------------------------------===//
6675   // Generate target specific nodes for 128 or 256-bit shuffles only
6676   // supported in the AVX instruction set.
6677   //
6678
6679   // Handle VMOVDDUPY permutations
6680   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6681     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6682
6683   // Handle VPERMILPS/D* permutations
6684   if (isVPERMILPMask(M, VT, HasAVX)) {
6685     if (HasAVX2 && VT == MVT::v8i32)
6686       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6687                                   getShuffleSHUFImmediate(SVOp), DAG);
6688     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6689                                 getShuffleSHUFImmediate(SVOp), DAG);
6690   }
6691
6692   // Handle VPERM2F128/VPERM2I128 permutations
6693   if (isVPERM2X128Mask(M, VT, HasAVX))
6694     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6695                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6696
6697   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6698   if (BlendOp.getNode())
6699     return BlendOp;
6700
6701   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6702     SmallVector<SDValue, 8> permclMask;
6703     for (unsigned i = 0; i != 8; ++i) {
6704       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6705     }
6706     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6707                                &permclMask[0], 8);
6708     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6709     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6710                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6711   }
6712
6713   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6714     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6715                                 getShuffleCLImmediate(SVOp), DAG);
6716
6717
6718   //===--------------------------------------------------------------------===//
6719   // Since no target specific shuffle was selected for this generic one,
6720   // lower it into other known shuffles. FIXME: this isn't true yet, but
6721   // this is the plan.
6722   //
6723
6724   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6725   if (VT == MVT::v8i16) {
6726     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6727     if (NewOp.getNode())
6728       return NewOp;
6729   }
6730
6731   if (VT == MVT::v16i8) {
6732     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6733     if (NewOp.getNode())
6734       return NewOp;
6735   }
6736
6737   // Handle all 128-bit wide vectors with 4 elements, and match them with
6738   // several different shuffle types.
6739   if (NumElems == 4 && VT.is128BitVector())
6740     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6741
6742   // Handle general 256-bit shuffles
6743   if (VT.is256BitVector())
6744     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6745
6746   return SDValue();
6747 }
6748
6749 SDValue
6750 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6751                                                 SelectionDAG &DAG) const {
6752   EVT VT = Op.getValueType();
6753   DebugLoc dl = Op.getDebugLoc();
6754
6755   if (!Op.getOperand(0).getValueType().is128BitVector())
6756     return SDValue();
6757
6758   if (VT.getSizeInBits() == 8) {
6759     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6760                                     Op.getOperand(0), Op.getOperand(1));
6761     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6762                                     DAG.getValueType(VT));
6763     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6764   }
6765
6766   if (VT.getSizeInBits() == 16) {
6767     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6768     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6769     if (Idx == 0)
6770       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6771                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6772                                      DAG.getNode(ISD::BITCAST, dl,
6773                                                  MVT::v4i32,
6774                                                  Op.getOperand(0)),
6775                                      Op.getOperand(1)));
6776     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6777                                     Op.getOperand(0), Op.getOperand(1));
6778     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6779                                     DAG.getValueType(VT));
6780     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6781   }
6782
6783   if (VT == MVT::f32) {
6784     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6785     // the result back to FR32 register. It's only worth matching if the
6786     // result has a single use which is a store or a bitcast to i32.  And in
6787     // the case of a store, it's not worth it if the index is a constant 0,
6788     // because a MOVSSmr can be used instead, which is smaller and faster.
6789     if (!Op.hasOneUse())
6790       return SDValue();
6791     SDNode *User = *Op.getNode()->use_begin();
6792     if ((User->getOpcode() != ISD::STORE ||
6793          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6794           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6795         (User->getOpcode() != ISD::BITCAST ||
6796          User->getValueType(0) != MVT::i32))
6797       return SDValue();
6798     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6799                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6800                                               Op.getOperand(0)),
6801                                               Op.getOperand(1));
6802     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6803   }
6804
6805   if (VT == MVT::i32 || VT == MVT::i64) {
6806     // ExtractPS/pextrq works with constant index.
6807     if (isa<ConstantSDNode>(Op.getOperand(1)))
6808       return Op;
6809   }
6810   return SDValue();
6811 }
6812
6813
6814 SDValue
6815 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6816                                            SelectionDAG &DAG) const {
6817   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6818     return SDValue();
6819
6820   SDValue Vec = Op.getOperand(0);
6821   EVT VecVT = Vec.getValueType();
6822
6823   // If this is a 256-bit vector result, first extract the 128-bit vector and
6824   // then extract the element from the 128-bit vector.
6825   if (VecVT.is256BitVector()) {
6826     DebugLoc dl = Op.getNode()->getDebugLoc();
6827     unsigned NumElems = VecVT.getVectorNumElements();
6828     SDValue Idx = Op.getOperand(1);
6829     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6830
6831     // Get the 128-bit vector.
6832     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6833
6834     if (IdxVal >= NumElems/2)
6835       IdxVal -= NumElems/2;
6836     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6837                        DAG.getConstant(IdxVal, MVT::i32));
6838   }
6839
6840   assert(VecVT.is128BitVector() && "Unexpected vector length");
6841
6842   if (Subtarget->hasSSE41()) {
6843     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6844     if (Res.getNode())
6845       return Res;
6846   }
6847
6848   EVT VT = Op.getValueType();
6849   DebugLoc dl = Op.getDebugLoc();
6850   // TODO: handle v16i8.
6851   if (VT.getSizeInBits() == 16) {
6852     SDValue Vec = Op.getOperand(0);
6853     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6854     if (Idx == 0)
6855       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6856                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6857                                      DAG.getNode(ISD::BITCAST, dl,
6858                                                  MVT::v4i32, Vec),
6859                                      Op.getOperand(1)));
6860     // Transform it so it match pextrw which produces a 32-bit result.
6861     EVT EltVT = MVT::i32;
6862     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6863                                     Op.getOperand(0), Op.getOperand(1));
6864     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6865                                     DAG.getValueType(VT));
6866     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6867   }
6868
6869   if (VT.getSizeInBits() == 32) {
6870     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6871     if (Idx == 0)
6872       return Op;
6873
6874     // SHUFPS the element to the lowest double word, then movss.
6875     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6876     EVT VVT = Op.getOperand(0).getValueType();
6877     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6878                                        DAG.getUNDEF(VVT), Mask);
6879     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6880                        DAG.getIntPtrConstant(0));
6881   }
6882
6883   if (VT.getSizeInBits() == 64) {
6884     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6885     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6886     //        to match extract_elt for f64.
6887     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6888     if (Idx == 0)
6889       return Op;
6890
6891     // UNPCKHPD the element to the lowest double word, then movsd.
6892     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6893     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6894     int Mask[2] = { 1, -1 };
6895     EVT VVT = Op.getOperand(0).getValueType();
6896     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6897                                        DAG.getUNDEF(VVT), Mask);
6898     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6899                        DAG.getIntPtrConstant(0));
6900   }
6901
6902   return SDValue();
6903 }
6904
6905 SDValue
6906 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6907                                                SelectionDAG &DAG) const {
6908   EVT VT = Op.getValueType();
6909   EVT EltVT = VT.getVectorElementType();
6910   DebugLoc dl = Op.getDebugLoc();
6911
6912   SDValue N0 = Op.getOperand(0);
6913   SDValue N1 = Op.getOperand(1);
6914   SDValue N2 = Op.getOperand(2);
6915
6916   if (!VT.is128BitVector())
6917     return SDValue();
6918
6919   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6920       isa<ConstantSDNode>(N2)) {
6921     unsigned Opc;
6922     if (VT == MVT::v8i16)
6923       Opc = X86ISD::PINSRW;
6924     else if (VT == MVT::v16i8)
6925       Opc = X86ISD::PINSRB;
6926     else
6927       Opc = X86ISD::PINSRB;
6928
6929     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6930     // argument.
6931     if (N1.getValueType() != MVT::i32)
6932       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6933     if (N2.getValueType() != MVT::i32)
6934       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6935     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6936   }
6937
6938   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6939     // Bits [7:6] of the constant are the source select.  This will always be
6940     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6941     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6942     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6943     // Bits [5:4] of the constant are the destination select.  This is the
6944     //  value of the incoming immediate.
6945     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6946     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6947     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6948     // Create this as a scalar to vector..
6949     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6950     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6951   }
6952
6953   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
6954     // PINSR* works with constant index.
6955     return Op;
6956   }
6957   return SDValue();
6958 }
6959
6960 SDValue
6961 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6962   EVT VT = Op.getValueType();
6963   EVT EltVT = VT.getVectorElementType();
6964
6965   DebugLoc dl = Op.getDebugLoc();
6966   SDValue N0 = Op.getOperand(0);
6967   SDValue N1 = Op.getOperand(1);
6968   SDValue N2 = Op.getOperand(2);
6969
6970   // If this is a 256-bit vector result, first extract the 128-bit vector,
6971   // insert the element into the extracted half and then place it back.
6972   if (VT.is256BitVector()) {
6973     if (!isa<ConstantSDNode>(N2))
6974       return SDValue();
6975
6976     // Get the desired 128-bit vector half.
6977     unsigned NumElems = VT.getVectorNumElements();
6978     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6979     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
6980
6981     // Insert the element into the desired half.
6982     bool Upper = IdxVal >= NumElems/2;
6983     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
6984                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
6985
6986     // Insert the changed part back to the 256-bit vector
6987     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
6988   }
6989
6990   if (Subtarget->hasSSE41())
6991     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6992
6993   if (EltVT == MVT::i8)
6994     return SDValue();
6995
6996   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6997     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6998     // as its second argument.
6999     if (N1.getValueType() != MVT::i32)
7000       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7001     if (N2.getValueType() != MVT::i32)
7002       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7003     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7004   }
7005   return SDValue();
7006 }
7007
7008 SDValue
7009 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7010   LLVMContext *Context = DAG.getContext();
7011   DebugLoc dl = Op.getDebugLoc();
7012   EVT OpVT = Op.getValueType();
7013
7014   // If this is a 256-bit vector result, first insert into a 128-bit
7015   // vector and then insert into the 256-bit vector.
7016   if (!OpVT.is128BitVector()) {
7017     // Insert into a 128-bit vector.
7018     EVT VT128 = EVT::getVectorVT(*Context,
7019                                  OpVT.getVectorElementType(),
7020                                  OpVT.getVectorNumElements() / 2);
7021
7022     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7023
7024     // Insert the 128-bit vector.
7025     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7026   }
7027
7028   if (OpVT == MVT::v1i64 &&
7029       Op.getOperand(0).getValueType() == MVT::i64)
7030     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7031
7032   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7033   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7034   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7035                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7036 }
7037
7038 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7039 // a simple subregister reference or explicit instructions to grab
7040 // upper bits of a vector.
7041 SDValue
7042 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7043   if (Subtarget->hasAVX()) {
7044     DebugLoc dl = Op.getNode()->getDebugLoc();
7045     SDValue Vec = Op.getNode()->getOperand(0);
7046     SDValue Idx = Op.getNode()->getOperand(1);
7047
7048     if (Op.getNode()->getValueType(0).is128BitVector() &&
7049         Vec.getNode()->getValueType(0).is256BitVector() &&
7050         isa<ConstantSDNode>(Idx)) {
7051       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7052       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7053     }
7054   }
7055   return SDValue();
7056 }
7057
7058 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7059 // simple superregister reference or explicit instructions to insert
7060 // the upper bits of a vector.
7061 SDValue
7062 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7063   if (Subtarget->hasAVX()) {
7064     DebugLoc dl = Op.getNode()->getDebugLoc();
7065     SDValue Vec = Op.getNode()->getOperand(0);
7066     SDValue SubVec = Op.getNode()->getOperand(1);
7067     SDValue Idx = Op.getNode()->getOperand(2);
7068
7069     if (Op.getNode()->getValueType(0).is256BitVector() &&
7070         SubVec.getNode()->getValueType(0).is128BitVector() &&
7071         isa<ConstantSDNode>(Idx)) {
7072       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7073       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7074     }
7075   }
7076   return SDValue();
7077 }
7078
7079 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7080 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7081 // one of the above mentioned nodes. It has to be wrapped because otherwise
7082 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7083 // be used to form addressing mode. These wrapped nodes will be selected
7084 // into MOV32ri.
7085 SDValue
7086 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7087   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7088
7089   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7090   // global base reg.
7091   unsigned char OpFlag = 0;
7092   unsigned WrapperKind = X86ISD::Wrapper;
7093   CodeModel::Model M = getTargetMachine().getCodeModel();
7094
7095   if (Subtarget->isPICStyleRIPRel() &&
7096       (M == CodeModel::Small || M == CodeModel::Kernel))
7097     WrapperKind = X86ISD::WrapperRIP;
7098   else if (Subtarget->isPICStyleGOT())
7099     OpFlag = X86II::MO_GOTOFF;
7100   else if (Subtarget->isPICStyleStubPIC())
7101     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7102
7103   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7104                                              CP->getAlignment(),
7105                                              CP->getOffset(), OpFlag);
7106   DebugLoc DL = CP->getDebugLoc();
7107   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7108   // With PIC, the address is actually $g + Offset.
7109   if (OpFlag) {
7110     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7111                          DAG.getNode(X86ISD::GlobalBaseReg,
7112                                      DebugLoc(), getPointerTy()),
7113                          Result);
7114   }
7115
7116   return Result;
7117 }
7118
7119 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7120   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7121
7122   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7123   // global base reg.
7124   unsigned char OpFlag = 0;
7125   unsigned WrapperKind = X86ISD::Wrapper;
7126   CodeModel::Model M = getTargetMachine().getCodeModel();
7127
7128   if (Subtarget->isPICStyleRIPRel() &&
7129       (M == CodeModel::Small || M == CodeModel::Kernel))
7130     WrapperKind = X86ISD::WrapperRIP;
7131   else if (Subtarget->isPICStyleGOT())
7132     OpFlag = X86II::MO_GOTOFF;
7133   else if (Subtarget->isPICStyleStubPIC())
7134     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7135
7136   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7137                                           OpFlag);
7138   DebugLoc DL = JT->getDebugLoc();
7139   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7140
7141   // With PIC, the address is actually $g + Offset.
7142   if (OpFlag)
7143     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7144                          DAG.getNode(X86ISD::GlobalBaseReg,
7145                                      DebugLoc(), getPointerTy()),
7146                          Result);
7147
7148   return Result;
7149 }
7150
7151 SDValue
7152 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7153   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7154
7155   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7156   // global base reg.
7157   unsigned char OpFlag = 0;
7158   unsigned WrapperKind = X86ISD::Wrapper;
7159   CodeModel::Model M = getTargetMachine().getCodeModel();
7160
7161   if (Subtarget->isPICStyleRIPRel() &&
7162       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7163     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7164       OpFlag = X86II::MO_GOTPCREL;
7165     WrapperKind = X86ISD::WrapperRIP;
7166   } else if (Subtarget->isPICStyleGOT()) {
7167     OpFlag = X86II::MO_GOT;
7168   } else if (Subtarget->isPICStyleStubPIC()) {
7169     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7170   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7171     OpFlag = X86II::MO_DARWIN_NONLAZY;
7172   }
7173
7174   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7175
7176   DebugLoc DL = Op.getDebugLoc();
7177   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7178
7179
7180   // With PIC, the address is actually $g + Offset.
7181   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7182       !Subtarget->is64Bit()) {
7183     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7184                          DAG.getNode(X86ISD::GlobalBaseReg,
7185                                      DebugLoc(), getPointerTy()),
7186                          Result);
7187   }
7188
7189   // For symbols that require a load from a stub to get the address, emit the
7190   // load.
7191   if (isGlobalStubReference(OpFlag))
7192     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7193                          MachinePointerInfo::getGOT(), false, false, false, 0);
7194
7195   return Result;
7196 }
7197
7198 SDValue
7199 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7200   // Create the TargetBlockAddressAddress node.
7201   unsigned char OpFlags =
7202     Subtarget->ClassifyBlockAddressReference();
7203   CodeModel::Model M = getTargetMachine().getCodeModel();
7204   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7205   DebugLoc dl = Op.getDebugLoc();
7206   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7207                                        /*isTarget=*/true, OpFlags);
7208
7209   if (Subtarget->isPICStyleRIPRel() &&
7210       (M == CodeModel::Small || M == CodeModel::Kernel))
7211     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7212   else
7213     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7214
7215   // With PIC, the address is actually $g + Offset.
7216   if (isGlobalRelativeToPICBase(OpFlags)) {
7217     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7218                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7219                          Result);
7220   }
7221
7222   return Result;
7223 }
7224
7225 SDValue
7226 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7227                                       int64_t Offset,
7228                                       SelectionDAG &DAG) const {
7229   // Create the TargetGlobalAddress node, folding in the constant
7230   // offset if it is legal.
7231   unsigned char OpFlags =
7232     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7233   CodeModel::Model M = getTargetMachine().getCodeModel();
7234   SDValue Result;
7235   if (OpFlags == X86II::MO_NO_FLAG &&
7236       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7237     // A direct static reference to a global.
7238     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7239     Offset = 0;
7240   } else {
7241     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7242   }
7243
7244   if (Subtarget->isPICStyleRIPRel() &&
7245       (M == CodeModel::Small || M == CodeModel::Kernel))
7246     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7247   else
7248     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7249
7250   // With PIC, the address is actually $g + Offset.
7251   if (isGlobalRelativeToPICBase(OpFlags)) {
7252     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7253                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7254                          Result);
7255   }
7256
7257   // For globals that require a load from a stub to get the address, emit the
7258   // load.
7259   if (isGlobalStubReference(OpFlags))
7260     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7261                          MachinePointerInfo::getGOT(), false, false, false, 0);
7262
7263   // If there was a non-zero offset that we didn't fold, create an explicit
7264   // addition for it.
7265   if (Offset != 0)
7266     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7267                          DAG.getConstant(Offset, getPointerTy()));
7268
7269   return Result;
7270 }
7271
7272 SDValue
7273 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7274   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7275   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7276   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7277 }
7278
7279 static SDValue
7280 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7281            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7282            unsigned char OperandFlags, bool LocalDynamic = false) {
7283   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7284   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7285   DebugLoc dl = GA->getDebugLoc();
7286   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7287                                            GA->getValueType(0),
7288                                            GA->getOffset(),
7289                                            OperandFlags);
7290
7291   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7292                                            : X86ISD::TLSADDR;
7293
7294   if (InFlag) {
7295     SDValue Ops[] = { Chain,  TGA, *InFlag };
7296     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7297   } else {
7298     SDValue Ops[]  = { Chain, TGA };
7299     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7300   }
7301
7302   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7303   MFI->setAdjustsStack(true);
7304
7305   SDValue Flag = Chain.getValue(1);
7306   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7307 }
7308
7309 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7310 static SDValue
7311 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7312                                 const EVT PtrVT) {
7313   SDValue InFlag;
7314   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7315   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7316                                      DAG.getNode(X86ISD::GlobalBaseReg,
7317                                                  DebugLoc(), PtrVT), InFlag);
7318   InFlag = Chain.getValue(1);
7319
7320   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7321 }
7322
7323 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7324 static SDValue
7325 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7326                                 const EVT PtrVT) {
7327   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7328                     X86::RAX, X86II::MO_TLSGD);
7329 }
7330
7331 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7332                                            SelectionDAG &DAG,
7333                                            const EVT PtrVT,
7334                                            bool is64Bit) {
7335   DebugLoc dl = GA->getDebugLoc();
7336
7337   // Get the start address of the TLS block for this module.
7338   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7339       .getInfo<X86MachineFunctionInfo>();
7340   MFI->incNumLocalDynamicTLSAccesses();
7341
7342   SDValue Base;
7343   if (is64Bit) {
7344     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7345                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7346   } else {
7347     SDValue InFlag;
7348     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7349         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7350     InFlag = Chain.getValue(1);
7351     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7352                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7353   }
7354
7355   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7356   // of Base.
7357
7358   // Build x@dtpoff.
7359   unsigned char OperandFlags = X86II::MO_DTPOFF;
7360   unsigned WrapperKind = X86ISD::Wrapper;
7361   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7362                                            GA->getValueType(0),
7363                                            GA->getOffset(), OperandFlags);
7364   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7365
7366   // Add x@dtpoff with the base.
7367   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7368 }
7369
7370 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7371 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7372                                    const EVT PtrVT, TLSModel::Model model,
7373                                    bool is64Bit, bool isPIC) {
7374   DebugLoc dl = GA->getDebugLoc();
7375
7376   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7377   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7378                                                          is64Bit ? 257 : 256));
7379
7380   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7381                                       DAG.getIntPtrConstant(0),
7382                                       MachinePointerInfo(Ptr),
7383                                       false, false, false, 0);
7384
7385   unsigned char OperandFlags = 0;
7386   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7387   // initialexec.
7388   unsigned WrapperKind = X86ISD::Wrapper;
7389   if (model == TLSModel::LocalExec) {
7390     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7391   } else if (model == TLSModel::InitialExec) {
7392     if (is64Bit) {
7393       OperandFlags = X86II::MO_GOTTPOFF;
7394       WrapperKind = X86ISD::WrapperRIP;
7395     } else {
7396       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7397     }
7398   } else {
7399     llvm_unreachable("Unexpected model");
7400   }
7401
7402   // emit "addl x@ntpoff,%eax" (local exec)
7403   // or "addl x@indntpoff,%eax" (initial exec)
7404   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7405   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7406                                            GA->getValueType(0),
7407                                            GA->getOffset(), OperandFlags);
7408   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7409
7410   if (model == TLSModel::InitialExec) {
7411     if (isPIC && !is64Bit) {
7412       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7413                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7414                            Offset);
7415     }
7416
7417     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7418                          MachinePointerInfo::getGOT(), false, false, false,
7419                          0);
7420   }
7421
7422   // The address of the thread local variable is the add of the thread
7423   // pointer with the offset of the variable.
7424   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7425 }
7426
7427 SDValue
7428 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7429
7430   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7431   const GlobalValue *GV = GA->getGlobal();
7432
7433   if (Subtarget->isTargetELF()) {
7434     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7435
7436     switch (model) {
7437       case TLSModel::GeneralDynamic:
7438         if (Subtarget->is64Bit())
7439           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7440         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7441       case TLSModel::LocalDynamic:
7442         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7443                                            Subtarget->is64Bit());
7444       case TLSModel::InitialExec:
7445       case TLSModel::LocalExec:
7446         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7447                                    Subtarget->is64Bit(),
7448                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7449     }
7450     llvm_unreachable("Unknown TLS model.");
7451   }
7452
7453   if (Subtarget->isTargetDarwin()) {
7454     // Darwin only has one model of TLS.  Lower to that.
7455     unsigned char OpFlag = 0;
7456     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7457                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7458
7459     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7460     // global base reg.
7461     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7462                   !Subtarget->is64Bit();
7463     if (PIC32)
7464       OpFlag = X86II::MO_TLVP_PIC_BASE;
7465     else
7466       OpFlag = X86II::MO_TLVP;
7467     DebugLoc DL = Op.getDebugLoc();
7468     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7469                                                 GA->getValueType(0),
7470                                                 GA->getOffset(), OpFlag);
7471     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7472
7473     // With PIC32, the address is actually $g + Offset.
7474     if (PIC32)
7475       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7476                            DAG.getNode(X86ISD::GlobalBaseReg,
7477                                        DebugLoc(), getPointerTy()),
7478                            Offset);
7479
7480     // Lowering the machine isd will make sure everything is in the right
7481     // location.
7482     SDValue Chain = DAG.getEntryNode();
7483     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7484     SDValue Args[] = { Chain, Offset };
7485     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7486
7487     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7488     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7489     MFI->setAdjustsStack(true);
7490
7491     // And our return value (tls address) is in the standard call return value
7492     // location.
7493     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7494     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7495                               Chain.getValue(1));
7496   }
7497
7498   if (Subtarget->isTargetWindows()) {
7499     // Just use the implicit TLS architecture
7500     // Need to generate someting similar to:
7501     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7502     //                                  ; from TEB
7503     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7504     //   mov     rcx, qword [rdx+rcx*8]
7505     //   mov     eax, .tls$:tlsvar
7506     //   [rax+rcx] contains the address
7507     // Windows 64bit: gs:0x58
7508     // Windows 32bit: fs:__tls_array
7509
7510     // If GV is an alias then use the aliasee for determining
7511     // thread-localness.
7512     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7513       GV = GA->resolveAliasedGlobal(false);
7514     DebugLoc dl = GA->getDebugLoc();
7515     SDValue Chain = DAG.getEntryNode();
7516
7517     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7518     // %gs:0x58 (64-bit).
7519     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7520                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7521                                                              256)
7522                                         : Type::getInt32PtrTy(*DAG.getContext(),
7523                                                               257));
7524
7525     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7526                                         Subtarget->is64Bit()
7527                                         ? DAG.getIntPtrConstant(0x58)
7528                                         : DAG.getExternalSymbol("_tls_array",
7529                                                                 getPointerTy()),
7530                                         MachinePointerInfo(Ptr),
7531                                         false, false, false, 0);
7532
7533     // Load the _tls_index variable
7534     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7535     if (Subtarget->is64Bit())
7536       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7537                            IDX, MachinePointerInfo(), MVT::i32,
7538                            false, false, 0);
7539     else
7540       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7541                         false, false, false, 0);
7542
7543     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7544                                     getPointerTy());
7545     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7546
7547     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7548     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7549                       false, false, false, 0);
7550
7551     // Get the offset of start of .tls section
7552     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7553                                              GA->getValueType(0),
7554                                              GA->getOffset(), X86II::MO_SECREL);
7555     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7556
7557     // The address of the thread local variable is the add of the thread
7558     // pointer with the offset of the variable.
7559     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7560   }
7561
7562   llvm_unreachable("TLS not implemented for this target.");
7563 }
7564
7565
7566 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7567 /// and take a 2 x i32 value to shift plus a shift amount.
7568 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7569   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7570   EVT VT = Op.getValueType();
7571   unsigned VTBits = VT.getSizeInBits();
7572   DebugLoc dl = Op.getDebugLoc();
7573   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7574   SDValue ShOpLo = Op.getOperand(0);
7575   SDValue ShOpHi = Op.getOperand(1);
7576   SDValue ShAmt  = Op.getOperand(2);
7577   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7578                                      DAG.getConstant(VTBits - 1, MVT::i8))
7579                        : DAG.getConstant(0, VT);
7580
7581   SDValue Tmp2, Tmp3;
7582   if (Op.getOpcode() == ISD::SHL_PARTS) {
7583     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7584     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7585   } else {
7586     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7587     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7588   }
7589
7590   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7591                                 DAG.getConstant(VTBits, MVT::i8));
7592   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7593                              AndNode, DAG.getConstant(0, MVT::i8));
7594
7595   SDValue Hi, Lo;
7596   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7597   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7598   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7599
7600   if (Op.getOpcode() == ISD::SHL_PARTS) {
7601     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7602     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7603   } else {
7604     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7605     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7606   }
7607
7608   SDValue Ops[2] = { Lo, Hi };
7609   return DAG.getMergeValues(Ops, 2, dl);
7610 }
7611
7612 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7613                                            SelectionDAG &DAG) const {
7614   EVT SrcVT = Op.getOperand(0).getValueType();
7615
7616   if (SrcVT.isVector())
7617     return SDValue();
7618
7619   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7620          "Unknown SINT_TO_FP to lower!");
7621
7622   // These are really Legal; return the operand so the caller accepts it as
7623   // Legal.
7624   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7625     return Op;
7626   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7627       Subtarget->is64Bit()) {
7628     return Op;
7629   }
7630
7631   DebugLoc dl = Op.getDebugLoc();
7632   unsigned Size = SrcVT.getSizeInBits()/8;
7633   MachineFunction &MF = DAG.getMachineFunction();
7634   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7635   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7636   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7637                                StackSlot,
7638                                MachinePointerInfo::getFixedStack(SSFI),
7639                                false, false, 0);
7640   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7641 }
7642
7643 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7644                                      SDValue StackSlot,
7645                                      SelectionDAG &DAG) const {
7646   // Build the FILD
7647   DebugLoc DL = Op.getDebugLoc();
7648   SDVTList Tys;
7649   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7650   if (useSSE)
7651     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7652   else
7653     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7654
7655   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7656
7657   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7658   MachineMemOperand *MMO;
7659   if (FI) {
7660     int SSFI = FI->getIndex();
7661     MMO =
7662       DAG.getMachineFunction()
7663       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7664                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7665   } else {
7666     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7667     StackSlot = StackSlot.getOperand(1);
7668   }
7669   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7670   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7671                                            X86ISD::FILD, DL,
7672                                            Tys, Ops, array_lengthof(Ops),
7673                                            SrcVT, MMO);
7674
7675   if (useSSE) {
7676     Chain = Result.getValue(1);
7677     SDValue InFlag = Result.getValue(2);
7678
7679     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7680     // shouldn't be necessary except that RFP cannot be live across
7681     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7682     MachineFunction &MF = DAG.getMachineFunction();
7683     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7684     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7685     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7686     Tys = DAG.getVTList(MVT::Other);
7687     SDValue Ops[] = {
7688       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7689     };
7690     MachineMemOperand *MMO =
7691       DAG.getMachineFunction()
7692       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7693                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7694
7695     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7696                                     Ops, array_lengthof(Ops),
7697                                     Op.getValueType(), MMO);
7698     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7699                          MachinePointerInfo::getFixedStack(SSFI),
7700                          false, false, false, 0);
7701   }
7702
7703   return Result;
7704 }
7705
7706 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7707 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7708                                                SelectionDAG &DAG) const {
7709   // This algorithm is not obvious. Here it is what we're trying to output:
7710   /*
7711      movq       %rax,  %xmm0
7712      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7713      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7714      #ifdef __SSE3__
7715        haddpd   %xmm0, %xmm0
7716      #else
7717        pshufd   $0x4e, %xmm0, %xmm1
7718        addpd    %xmm1, %xmm0
7719      #endif
7720   */
7721
7722   DebugLoc dl = Op.getDebugLoc();
7723   LLVMContext *Context = DAG.getContext();
7724
7725   // Build some magic constants.
7726   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7727   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7728   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7729
7730   SmallVector<Constant*,2> CV1;
7731   CV1.push_back(
7732         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7733   CV1.push_back(
7734         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7735   Constant *C1 = ConstantVector::get(CV1);
7736   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7737
7738   // Load the 64-bit value into an XMM register.
7739   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7740                             Op.getOperand(0));
7741   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7742                               MachinePointerInfo::getConstantPool(),
7743                               false, false, false, 16);
7744   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7745                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7746                               CLod0);
7747
7748   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7749                               MachinePointerInfo::getConstantPool(),
7750                               false, false, false, 16);
7751   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7752   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7753   SDValue Result;
7754
7755   if (Subtarget->hasSSE3()) {
7756     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7757     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7758   } else {
7759     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7760     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7761                                            S2F, 0x4E, DAG);
7762     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7763                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7764                          Sub);
7765   }
7766
7767   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7768                      DAG.getIntPtrConstant(0));
7769 }
7770
7771 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7772 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7773                                                SelectionDAG &DAG) const {
7774   DebugLoc dl = Op.getDebugLoc();
7775   // FP constant to bias correct the final result.
7776   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7777                                    MVT::f64);
7778
7779   // Load the 32-bit value into an XMM register.
7780   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7781                              Op.getOperand(0));
7782
7783   // Zero out the upper parts of the register.
7784   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7785
7786   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7787                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7788                      DAG.getIntPtrConstant(0));
7789
7790   // Or the load with the bias.
7791   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7792                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7793                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7794                                                    MVT::v2f64, Load)),
7795                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7796                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7797                                                    MVT::v2f64, Bias)));
7798   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7799                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7800                    DAG.getIntPtrConstant(0));
7801
7802   // Subtract the bias.
7803   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7804
7805   // Handle final rounding.
7806   EVT DestVT = Op.getValueType();
7807
7808   if (DestVT.bitsLT(MVT::f64))
7809     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7810                        DAG.getIntPtrConstant(0));
7811   if (DestVT.bitsGT(MVT::f64))
7812     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7813
7814   // Handle final rounding.
7815   return Sub;
7816 }
7817
7818 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7819                                            SelectionDAG &DAG) const {
7820   SDValue N0 = Op.getOperand(0);
7821   DebugLoc dl = Op.getDebugLoc();
7822
7823   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7824   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7825   // the optimization here.
7826   if (DAG.SignBitIsZero(N0))
7827     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7828
7829   EVT SrcVT = N0.getValueType();
7830   EVT DstVT = Op.getValueType();
7831   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7832     return LowerUINT_TO_FP_i64(Op, DAG);
7833   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7834     return LowerUINT_TO_FP_i32(Op, DAG);
7835   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7836     return SDValue();
7837
7838   // Make a 64-bit buffer, and use it to build an FILD.
7839   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7840   if (SrcVT == MVT::i32) {
7841     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7842     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7843                                      getPointerTy(), StackSlot, WordOff);
7844     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7845                                   StackSlot, MachinePointerInfo(),
7846                                   false, false, 0);
7847     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7848                                   OffsetSlot, MachinePointerInfo(),
7849                                   false, false, 0);
7850     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7851     return Fild;
7852   }
7853
7854   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7855   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7856                                StackSlot, MachinePointerInfo(),
7857                                false, false, 0);
7858   // For i64 source, we need to add the appropriate power of 2 if the input
7859   // was negative.  This is the same as the optimization in
7860   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7861   // we must be careful to do the computation in x87 extended precision, not
7862   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7863   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7864   MachineMemOperand *MMO =
7865     DAG.getMachineFunction()
7866     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7867                           MachineMemOperand::MOLoad, 8, 8);
7868
7869   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7870   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7871   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7872                                          MVT::i64, MMO);
7873
7874   APInt FF(32, 0x5F800000ULL);
7875
7876   // Check whether the sign bit is set.
7877   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7878                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7879                                  ISD::SETLT);
7880
7881   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7882   SDValue FudgePtr = DAG.getConstantPool(
7883                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7884                                          getPointerTy());
7885
7886   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7887   SDValue Zero = DAG.getIntPtrConstant(0);
7888   SDValue Four = DAG.getIntPtrConstant(4);
7889   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7890                                Zero, Four);
7891   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7892
7893   // Load the value out, extending it from f32 to f80.
7894   // FIXME: Avoid the extend by constructing the right constant pool?
7895   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7896                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7897                                  MVT::f32, false, false, 4);
7898   // Extend everything to 80 bits to force it to be done on x87.
7899   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7900   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7901 }
7902
7903 std::pair<SDValue,SDValue> X86TargetLowering::
7904 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7905   DebugLoc DL = Op.getDebugLoc();
7906
7907   EVT DstTy = Op.getValueType();
7908
7909   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7910     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7911     DstTy = MVT::i64;
7912   }
7913
7914   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7915          DstTy.getSimpleVT() >= MVT::i16 &&
7916          "Unknown FP_TO_INT to lower!");
7917
7918   // These are really Legal.
7919   if (DstTy == MVT::i32 &&
7920       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7921     return std::make_pair(SDValue(), SDValue());
7922   if (Subtarget->is64Bit() &&
7923       DstTy == MVT::i64 &&
7924       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7925     return std::make_pair(SDValue(), SDValue());
7926
7927   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7928   // stack slot, or into the FTOL runtime function.
7929   MachineFunction &MF = DAG.getMachineFunction();
7930   unsigned MemSize = DstTy.getSizeInBits()/8;
7931   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7932   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7933
7934   unsigned Opc;
7935   if (!IsSigned && isIntegerTypeFTOL(DstTy))
7936     Opc = X86ISD::WIN_FTOL;
7937   else
7938     switch (DstTy.getSimpleVT().SimpleTy) {
7939     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7940     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7941     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7942     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7943     }
7944
7945   SDValue Chain = DAG.getEntryNode();
7946   SDValue Value = Op.getOperand(0);
7947   EVT TheVT = Op.getOperand(0).getValueType();
7948   // FIXME This causes a redundant load/store if the SSE-class value is already
7949   // in memory, such as if it is on the callstack.
7950   if (isScalarFPTypeInSSEReg(TheVT)) {
7951     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7952     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7953                          MachinePointerInfo::getFixedStack(SSFI),
7954                          false, false, 0);
7955     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7956     SDValue Ops[] = {
7957       Chain, StackSlot, DAG.getValueType(TheVT)
7958     };
7959
7960     MachineMemOperand *MMO =
7961       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7962                               MachineMemOperand::MOLoad, MemSize, MemSize);
7963     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7964                                     DstTy, MMO);
7965     Chain = Value.getValue(1);
7966     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7967     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7968   }
7969
7970   MachineMemOperand *MMO =
7971     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7972                             MachineMemOperand::MOStore, MemSize, MemSize);
7973
7974   if (Opc != X86ISD::WIN_FTOL) {
7975     // Build the FP_TO_INT*_IN_MEM
7976     SDValue Ops[] = { Chain, Value, StackSlot };
7977     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7978                                            Ops, 3, DstTy, MMO);
7979     return std::make_pair(FIST, StackSlot);
7980   } else {
7981     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
7982       DAG.getVTList(MVT::Other, MVT::Glue),
7983       Chain, Value);
7984     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
7985       MVT::i32, ftol.getValue(1));
7986     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
7987       MVT::i32, eax.getValue(2));
7988     SDValue Ops[] = { eax, edx };
7989     SDValue pair = IsReplace
7990       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
7991       : DAG.getMergeValues(Ops, 2, DL);
7992     return std::make_pair(pair, SDValue());
7993   }
7994 }
7995
7996 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7997                                            SelectionDAG &DAG) const {
7998   if (Op.getValueType().isVector())
7999     return SDValue();
8000
8001   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8002     /*IsSigned=*/ true, /*IsReplace=*/ false);
8003   SDValue FIST = Vals.first, StackSlot = Vals.second;
8004   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8005   if (FIST.getNode() == 0) return Op;
8006
8007   if (StackSlot.getNode())
8008     // Load the result.
8009     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8010                        FIST, StackSlot, MachinePointerInfo(),
8011                        false, false, false, 0);
8012
8013   // The node is the result.
8014   return FIST;
8015 }
8016
8017 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8018                                            SelectionDAG &DAG) const {
8019   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8020     /*IsSigned=*/ false, /*IsReplace=*/ false);
8021   SDValue FIST = Vals.first, StackSlot = Vals.second;
8022   assert(FIST.getNode() && "Unexpected failure");
8023
8024   if (StackSlot.getNode())
8025     // Load the result.
8026     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8027                        FIST, StackSlot, MachinePointerInfo(),
8028                        false, false, false, 0);
8029
8030   // The node is the result.
8031   return FIST;
8032 }
8033
8034 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8035                                      SelectionDAG &DAG) const {
8036   LLVMContext *Context = DAG.getContext();
8037   DebugLoc dl = Op.getDebugLoc();
8038   EVT VT = Op.getValueType();
8039   EVT EltVT = VT;
8040   if (VT.isVector())
8041     EltVT = VT.getVectorElementType();
8042   Constant *C;
8043   if (EltVT == MVT::f64) {
8044     C = ConstantVector::getSplat(2,
8045                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8046   } else {
8047     C = ConstantVector::getSplat(4,
8048                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8049   }
8050   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8051   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8052                              MachinePointerInfo::getConstantPool(),
8053                              false, false, false, 16);
8054   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8055 }
8056
8057 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8058   LLVMContext *Context = DAG.getContext();
8059   DebugLoc dl = Op.getDebugLoc();
8060   EVT VT = Op.getValueType();
8061   EVT EltVT = VT;
8062   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8063   if (VT.isVector()) {
8064     EltVT = VT.getVectorElementType();
8065     NumElts = VT.getVectorNumElements();
8066   }
8067   Constant *C;
8068   if (EltVT == MVT::f64)
8069     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8070   else
8071     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8072   C = ConstantVector::getSplat(NumElts, C);
8073   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8074   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8075                              MachinePointerInfo::getConstantPool(),
8076                              false, false, false, 16);
8077   if (VT.isVector()) {
8078     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8079     return DAG.getNode(ISD::BITCAST, dl, VT,
8080                        DAG.getNode(ISD::XOR, dl, XORVT,
8081                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8082                                                Op.getOperand(0)),
8083                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8084   }
8085
8086   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8087 }
8088
8089 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8090   LLVMContext *Context = DAG.getContext();
8091   SDValue Op0 = Op.getOperand(0);
8092   SDValue Op1 = Op.getOperand(1);
8093   DebugLoc dl = Op.getDebugLoc();
8094   EVT VT = Op.getValueType();
8095   EVT SrcVT = Op1.getValueType();
8096
8097   // If second operand is smaller, extend it first.
8098   if (SrcVT.bitsLT(VT)) {
8099     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8100     SrcVT = VT;
8101   }
8102   // And if it is bigger, shrink it first.
8103   if (SrcVT.bitsGT(VT)) {
8104     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8105     SrcVT = VT;
8106   }
8107
8108   // At this point the operands and the result should have the same
8109   // type, and that won't be f80 since that is not custom lowered.
8110
8111   // First get the sign bit of second operand.
8112   SmallVector<Constant*,4> CV;
8113   if (SrcVT == MVT::f64) {
8114     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8115     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8116   } else {
8117     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8118     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8119     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8120     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8121   }
8122   Constant *C = ConstantVector::get(CV);
8123   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8124   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8125                               MachinePointerInfo::getConstantPool(),
8126                               false, false, false, 16);
8127   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8128
8129   // Shift sign bit right or left if the two operands have different types.
8130   if (SrcVT.bitsGT(VT)) {
8131     // Op0 is MVT::f32, Op1 is MVT::f64.
8132     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8133     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8134                           DAG.getConstant(32, MVT::i32));
8135     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8136     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8137                           DAG.getIntPtrConstant(0));
8138   }
8139
8140   // Clear first operand sign bit.
8141   CV.clear();
8142   if (VT == MVT::f64) {
8143     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8144     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8145   } else {
8146     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8147     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8148     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8149     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8150   }
8151   C = ConstantVector::get(CV);
8152   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8153   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8154                               MachinePointerInfo::getConstantPool(),
8155                               false, false, false, 16);
8156   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8157
8158   // Or the value with the sign bit.
8159   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8160 }
8161
8162 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8163   SDValue N0 = Op.getOperand(0);
8164   DebugLoc dl = Op.getDebugLoc();
8165   EVT VT = Op.getValueType();
8166
8167   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8168   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8169                                   DAG.getConstant(1, VT));
8170   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8171 }
8172
8173 /// Emit nodes that will be selected as "test Op0,Op0", or something
8174 /// equivalent.
8175 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8176                                     SelectionDAG &DAG) const {
8177   DebugLoc dl = Op.getDebugLoc();
8178
8179   // CF and OF aren't always set the way we want. Determine which
8180   // of these we need.
8181   bool NeedCF = false;
8182   bool NeedOF = false;
8183   switch (X86CC) {
8184   default: break;
8185   case X86::COND_A: case X86::COND_AE:
8186   case X86::COND_B: case X86::COND_BE:
8187     NeedCF = true;
8188     break;
8189   case X86::COND_G: case X86::COND_GE:
8190   case X86::COND_L: case X86::COND_LE:
8191   case X86::COND_O: case X86::COND_NO:
8192     NeedOF = true;
8193     break;
8194   }
8195
8196   // See if we can use the EFLAGS value from the operand instead of
8197   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8198   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8199   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8200     // Emit a CMP with 0, which is the TEST pattern.
8201     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8202                        DAG.getConstant(0, Op.getValueType()));
8203
8204   unsigned Opcode = 0;
8205   unsigned NumOperands = 0;
8206   switch (Op.getNode()->getOpcode()) {
8207   case ISD::ADD:
8208     // Due to an isel shortcoming, be conservative if this add is likely to be
8209     // selected as part of a load-modify-store instruction. When the root node
8210     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8211     // uses of other nodes in the match, such as the ADD in this case. This
8212     // leads to the ADD being left around and reselected, with the result being
8213     // two adds in the output.  Alas, even if none our users are stores, that
8214     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8215     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8216     // climbing the DAG back to the root, and it doesn't seem to be worth the
8217     // effort.
8218     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8219          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8220       if (UI->getOpcode() != ISD::CopyToReg &&
8221           UI->getOpcode() != ISD::SETCC &&
8222           UI->getOpcode() != ISD::STORE)
8223         goto default_case;
8224
8225     if (ConstantSDNode *C =
8226         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8227       // An add of one will be selected as an INC.
8228       if (C->getAPIntValue() == 1) {
8229         Opcode = X86ISD::INC;
8230         NumOperands = 1;
8231         break;
8232       }
8233
8234       // An add of negative one (subtract of one) will be selected as a DEC.
8235       if (C->getAPIntValue().isAllOnesValue()) {
8236         Opcode = X86ISD::DEC;
8237         NumOperands = 1;
8238         break;
8239       }
8240     }
8241
8242     // Otherwise use a regular EFLAGS-setting add.
8243     Opcode = X86ISD::ADD;
8244     NumOperands = 2;
8245     break;
8246   case ISD::AND: {
8247     // If the primary and result isn't used, don't bother using X86ISD::AND,
8248     // because a TEST instruction will be better.
8249     bool NonFlagUse = false;
8250     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8251            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8252       SDNode *User = *UI;
8253       unsigned UOpNo = UI.getOperandNo();
8254       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8255         // Look pass truncate.
8256         UOpNo = User->use_begin().getOperandNo();
8257         User = *User->use_begin();
8258       }
8259
8260       if (User->getOpcode() != ISD::BRCOND &&
8261           User->getOpcode() != ISD::SETCC &&
8262           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8263         NonFlagUse = true;
8264         break;
8265       }
8266     }
8267
8268     if (!NonFlagUse)
8269       break;
8270   }
8271     // FALL THROUGH
8272   case ISD::SUB:
8273   case ISD::OR:
8274   case ISD::XOR:
8275     // Due to the ISEL shortcoming noted above, be conservative if this op is
8276     // likely to be selected as part of a load-modify-store instruction.
8277     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8278            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8279       if (UI->getOpcode() == ISD::STORE)
8280         goto default_case;
8281
8282     // Otherwise use a regular EFLAGS-setting instruction.
8283     switch (Op.getNode()->getOpcode()) {
8284     default: llvm_unreachable("unexpected operator!");
8285     case ISD::SUB:
8286       Opcode = X86ISD::SUB;
8287       break;
8288     case ISD::OR:  Opcode = X86ISD::OR;  break;
8289     case ISD::XOR: Opcode = X86ISD::XOR; break;
8290     case ISD::AND: Opcode = X86ISD::AND; break;
8291     }
8292
8293     NumOperands = 2;
8294     break;
8295   case X86ISD::ADD:
8296   case X86ISD::SUB:
8297   case X86ISD::INC:
8298   case X86ISD::DEC:
8299   case X86ISD::OR:
8300   case X86ISD::XOR:
8301   case X86ISD::AND:
8302     return SDValue(Op.getNode(), 1);
8303   default:
8304   default_case:
8305     break;
8306   }
8307
8308   if (Opcode == 0)
8309     // Emit a CMP with 0, which is the TEST pattern.
8310     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8311                        DAG.getConstant(0, Op.getValueType()));
8312
8313   if (Opcode == X86ISD::CMP) {
8314     SDValue New = DAG.getNode(Opcode, dl, MVT::i32, Op.getOperand(0),
8315                               Op.getOperand(1));
8316     // We can't replace usage of SUB with CMP.
8317     // The SUB node will be removed later because there is no use of it.
8318     return SDValue(New.getNode(), 0);
8319   }
8320
8321   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8322   SmallVector<SDValue, 4> Ops;
8323   for (unsigned i = 0; i != NumOperands; ++i)
8324     Ops.push_back(Op.getOperand(i));
8325
8326   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8327   DAG.ReplaceAllUsesWith(Op, New);
8328   return SDValue(New.getNode(), 1);
8329 }
8330
8331 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8332 /// equivalent.
8333 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8334                                    SelectionDAG &DAG) const {
8335   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8336     if (C->getAPIntValue() == 0)
8337       return EmitTest(Op0, X86CC, DAG);
8338
8339   DebugLoc dl = Op0.getDebugLoc();
8340   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8341        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8342     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8343     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8344     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8345                               Op0, Op1);
8346     return SDValue(Sub.getNode(), 1);
8347   }
8348   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8349 }
8350
8351 /// Convert a comparison if required by the subtarget.
8352 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8353                                                  SelectionDAG &DAG) const {
8354   // If the subtarget does not support the FUCOMI instruction, floating-point
8355   // comparisons have to be converted.
8356   if (Subtarget->hasCMov() ||
8357       Cmp.getOpcode() != X86ISD::CMP ||
8358       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8359       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8360     return Cmp;
8361
8362   // The instruction selector will select an FUCOM instruction instead of
8363   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8364   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8365   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8366   DebugLoc dl = Cmp.getDebugLoc();
8367   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8368   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8369   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8370                             DAG.getConstant(8, MVT::i8));
8371   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8372   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8373 }
8374
8375 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8376 /// if it's possible.
8377 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8378                                      DebugLoc dl, SelectionDAG &DAG) const {
8379   SDValue Op0 = And.getOperand(0);
8380   SDValue Op1 = And.getOperand(1);
8381   if (Op0.getOpcode() == ISD::TRUNCATE)
8382     Op0 = Op0.getOperand(0);
8383   if (Op1.getOpcode() == ISD::TRUNCATE)
8384     Op1 = Op1.getOperand(0);
8385
8386   SDValue LHS, RHS;
8387   if (Op1.getOpcode() == ISD::SHL)
8388     std::swap(Op0, Op1);
8389   if (Op0.getOpcode() == ISD::SHL) {
8390     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8391       if (And00C->getZExtValue() == 1) {
8392         // If we looked past a truncate, check that it's only truncating away
8393         // known zeros.
8394         unsigned BitWidth = Op0.getValueSizeInBits();
8395         unsigned AndBitWidth = And.getValueSizeInBits();
8396         if (BitWidth > AndBitWidth) {
8397           APInt Zeros, Ones;
8398           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8399           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8400             return SDValue();
8401         }
8402         LHS = Op1;
8403         RHS = Op0.getOperand(1);
8404       }
8405   } else if (Op1.getOpcode() == ISD::Constant) {
8406     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8407     uint64_t AndRHSVal = AndRHS->getZExtValue();
8408     SDValue AndLHS = Op0;
8409
8410     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8411       LHS = AndLHS.getOperand(0);
8412       RHS = AndLHS.getOperand(1);
8413     }
8414
8415     // Use BT if the immediate can't be encoded in a TEST instruction.
8416     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8417       LHS = AndLHS;
8418       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8419     }
8420   }
8421
8422   if (LHS.getNode()) {
8423     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8424     // instruction.  Since the shift amount is in-range-or-undefined, we know
8425     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8426     // the encoding for the i16 version is larger than the i32 version.
8427     // Also promote i16 to i32 for performance / code size reason.
8428     if (LHS.getValueType() == MVT::i8 ||
8429         LHS.getValueType() == MVT::i16)
8430       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8431
8432     // If the operand types disagree, extend the shift amount to match.  Since
8433     // BT ignores high bits (like shifts) we can use anyextend.
8434     if (LHS.getValueType() != RHS.getValueType())
8435       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8436
8437     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8438     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8439     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8440                        DAG.getConstant(Cond, MVT::i8), BT);
8441   }
8442
8443   return SDValue();
8444 }
8445
8446 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8447
8448   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8449
8450   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8451   SDValue Op0 = Op.getOperand(0);
8452   SDValue Op1 = Op.getOperand(1);
8453   DebugLoc dl = Op.getDebugLoc();
8454   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8455
8456   // Optimize to BT if possible.
8457   // Lower (X & (1 << N)) == 0 to BT(X, N).
8458   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8459   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8460   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8461       Op1.getOpcode() == ISD::Constant &&
8462       cast<ConstantSDNode>(Op1)->isNullValue() &&
8463       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8464     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8465     if (NewSetCC.getNode())
8466       return NewSetCC;
8467   }
8468
8469   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8470   // these.
8471   if (Op1.getOpcode() == ISD::Constant &&
8472       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8473        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8474       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8475
8476     // If the input is a setcc, then reuse the input setcc or use a new one with
8477     // the inverted condition.
8478     if (Op0.getOpcode() == X86ISD::SETCC) {
8479       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8480       bool Invert = (CC == ISD::SETNE) ^
8481         cast<ConstantSDNode>(Op1)->isNullValue();
8482       if (!Invert) return Op0;
8483
8484       CCode = X86::GetOppositeBranchCondition(CCode);
8485       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8486                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8487     }
8488   }
8489
8490   bool isFP = Op1.getValueType().isFloatingPoint();
8491   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8492   if (X86CC == X86::COND_INVALID)
8493     return SDValue();
8494
8495   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8496   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8497   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8498                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8499 }
8500
8501 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8502 // ones, and then concatenate the result back.
8503 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8504   EVT VT = Op.getValueType();
8505
8506   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8507          "Unsupported value type for operation");
8508
8509   unsigned NumElems = VT.getVectorNumElements();
8510   DebugLoc dl = Op.getDebugLoc();
8511   SDValue CC = Op.getOperand(2);
8512
8513   // Extract the LHS vectors
8514   SDValue LHS = Op.getOperand(0);
8515   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8516   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8517
8518   // Extract the RHS vectors
8519   SDValue RHS = Op.getOperand(1);
8520   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8521   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8522
8523   // Issue the operation on the smaller types and concatenate the result back
8524   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8525   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8526   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8527                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8528                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8529 }
8530
8531
8532 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8533   SDValue Cond;
8534   SDValue Op0 = Op.getOperand(0);
8535   SDValue Op1 = Op.getOperand(1);
8536   SDValue CC = Op.getOperand(2);
8537   EVT VT = Op.getValueType();
8538   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8539   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8540   DebugLoc dl = Op.getDebugLoc();
8541
8542   if (isFP) {
8543     unsigned SSECC = 8;
8544     EVT EltVT = Op0.getValueType().getVectorElementType();
8545     assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8546
8547     bool Swap = false;
8548
8549     // SSE Condition code mapping:
8550     //  0 - EQ
8551     //  1 - LT
8552     //  2 - LE
8553     //  3 - UNORD
8554     //  4 - NEQ
8555     //  5 - NLT
8556     //  6 - NLE
8557     //  7 - ORD
8558     switch (SetCCOpcode) {
8559     default: break;
8560     case ISD::SETOEQ:
8561     case ISD::SETEQ:  SSECC = 0; break;
8562     case ISD::SETOGT:
8563     case ISD::SETGT: Swap = true; // Fallthrough
8564     case ISD::SETLT:
8565     case ISD::SETOLT: SSECC = 1; break;
8566     case ISD::SETOGE:
8567     case ISD::SETGE: Swap = true; // Fallthrough
8568     case ISD::SETLE:
8569     case ISD::SETOLE: SSECC = 2; break;
8570     case ISD::SETUO:  SSECC = 3; break;
8571     case ISD::SETUNE:
8572     case ISD::SETNE:  SSECC = 4; break;
8573     case ISD::SETULE: Swap = true;
8574     case ISD::SETUGE: SSECC = 5; break;
8575     case ISD::SETULT: Swap = true;
8576     case ISD::SETUGT: SSECC = 6; break;
8577     case ISD::SETO:   SSECC = 7; break;
8578     }
8579     if (Swap)
8580       std::swap(Op0, Op1);
8581
8582     // In the two special cases we can't handle, emit two comparisons.
8583     if (SSECC == 8) {
8584       if (SetCCOpcode == ISD::SETUEQ) {
8585         SDValue UNORD, EQ;
8586         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8587                             DAG.getConstant(3, MVT::i8));
8588         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8589                          DAG.getConstant(0, MVT::i8));
8590         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8591       }
8592       if (SetCCOpcode == ISD::SETONE) {
8593         SDValue ORD, NEQ;
8594         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8595                           DAG.getConstant(7, MVT::i8));
8596         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8597                           DAG.getConstant(4, MVT::i8));
8598         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8599       }
8600       llvm_unreachable("Illegal FP comparison");
8601     }
8602     // Handle all other FP comparisons here.
8603     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8604                        DAG.getConstant(SSECC, MVT::i8));
8605   }
8606
8607   // Break 256-bit integer vector compare into smaller ones.
8608   if (VT.is256BitVector() && !Subtarget->hasAVX2())
8609     return Lower256IntVSETCC(Op, DAG);
8610
8611   // We are handling one of the integer comparisons here.  Since SSE only has
8612   // GT and EQ comparisons for integer, swapping operands and multiple
8613   // operations may be required for some comparisons.
8614   unsigned Opc = 0;
8615   bool Swap = false, Invert = false, FlipSigns = false;
8616
8617   switch (SetCCOpcode) {
8618   default: break;
8619   case ISD::SETNE:  Invert = true;
8620   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8621   case ISD::SETLT:  Swap = true;
8622   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8623   case ISD::SETGE:  Swap = true;
8624   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8625   case ISD::SETULT: Swap = true;
8626   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8627   case ISD::SETUGE: Swap = true;
8628   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8629   }
8630   if (Swap)
8631     std::swap(Op0, Op1);
8632
8633   // Check that the operation in question is available (most are plain SSE2,
8634   // but PCMPGTQ and PCMPEQQ have different requirements).
8635   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8636     return SDValue();
8637   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8638     return SDValue();
8639
8640   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8641   // bits of the inputs before performing those operations.
8642   if (FlipSigns) {
8643     EVT EltVT = VT.getVectorElementType();
8644     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8645                                       EltVT);
8646     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8647     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8648                                     SignBits.size());
8649     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8650     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8651   }
8652
8653   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8654
8655   // If the logical-not of the result is required, perform that now.
8656   if (Invert)
8657     Result = DAG.getNOT(dl, Result, VT);
8658
8659   return Result;
8660 }
8661
8662 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8663 static bool isX86LogicalCmp(SDValue Op) {
8664   unsigned Opc = Op.getNode()->getOpcode();
8665   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8666       Opc == X86ISD::SAHF)
8667     return true;
8668   if (Op.getResNo() == 1 &&
8669       (Opc == X86ISD::ADD ||
8670        Opc == X86ISD::SUB ||
8671        Opc == X86ISD::ADC ||
8672        Opc == X86ISD::SBB ||
8673        Opc == X86ISD::SMUL ||
8674        Opc == X86ISD::UMUL ||
8675        Opc == X86ISD::INC ||
8676        Opc == X86ISD::DEC ||
8677        Opc == X86ISD::OR ||
8678        Opc == X86ISD::XOR ||
8679        Opc == X86ISD::AND))
8680     return true;
8681
8682   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8683     return true;
8684
8685   return false;
8686 }
8687
8688 static bool isZero(SDValue V) {
8689   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8690   return C && C->isNullValue();
8691 }
8692
8693 static bool isAllOnes(SDValue V) {
8694   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8695   return C && C->isAllOnesValue();
8696 }
8697
8698 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8699   if (V.getOpcode() != ISD::TRUNCATE)
8700     return false;
8701
8702   SDValue VOp0 = V.getOperand(0);
8703   unsigned InBits = VOp0.getValueSizeInBits();
8704   unsigned Bits = V.getValueSizeInBits();
8705   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8706 }
8707
8708 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8709   bool addTest = true;
8710   SDValue Cond  = Op.getOperand(0);
8711   SDValue Op1 = Op.getOperand(1);
8712   SDValue Op2 = Op.getOperand(2);
8713   DebugLoc DL = Op.getDebugLoc();
8714   SDValue CC;
8715
8716   if (Cond.getOpcode() == ISD::SETCC) {
8717     SDValue NewCond = LowerSETCC(Cond, DAG);
8718     if (NewCond.getNode())
8719       Cond = NewCond;
8720   }
8721
8722   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8723   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8724   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8725   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8726   if (Cond.getOpcode() == X86ISD::SETCC &&
8727       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8728       isZero(Cond.getOperand(1).getOperand(1))) {
8729     SDValue Cmp = Cond.getOperand(1);
8730
8731     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8732
8733     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8734         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8735       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8736
8737       SDValue CmpOp0 = Cmp.getOperand(0);
8738       // Apply further optimizations for special cases
8739       // (select (x != 0), -1, 0) -> neg & sbb
8740       // (select (x == 0), 0, -1) -> neg & sbb
8741       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8742         if (YC->isNullValue() &&
8743             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8744           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8745           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8746                                     DAG.getConstant(0, CmpOp0.getValueType()),
8747                                     CmpOp0);
8748           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8749                                     DAG.getConstant(X86::COND_B, MVT::i8),
8750                                     SDValue(Neg.getNode(), 1));
8751           return Res;
8752         }
8753
8754       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8755                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8756       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8757
8758       SDValue Res =   // Res = 0 or -1.
8759         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8760                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8761
8762       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8763         Res = DAG.getNOT(DL, Res, Res.getValueType());
8764
8765       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8766       if (N2C == 0 || !N2C->isNullValue())
8767         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8768       return Res;
8769     }
8770   }
8771
8772   // Look past (and (setcc_carry (cmp ...)), 1).
8773   if (Cond.getOpcode() == ISD::AND &&
8774       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8775     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8776     if (C && C->getAPIntValue() == 1)
8777       Cond = Cond.getOperand(0);
8778   }
8779
8780   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8781   // setting operand in place of the X86ISD::SETCC.
8782   unsigned CondOpcode = Cond.getOpcode();
8783   if (CondOpcode == X86ISD::SETCC ||
8784       CondOpcode == X86ISD::SETCC_CARRY) {
8785     CC = Cond.getOperand(0);
8786
8787     SDValue Cmp = Cond.getOperand(1);
8788     unsigned Opc = Cmp.getOpcode();
8789     EVT VT = Op.getValueType();
8790
8791     bool IllegalFPCMov = false;
8792     if (VT.isFloatingPoint() && !VT.isVector() &&
8793         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8794       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8795
8796     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8797         Opc == X86ISD::BT) { // FIXME
8798       Cond = Cmp;
8799       addTest = false;
8800     }
8801   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8802              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8803              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8804               Cond.getOperand(0).getValueType() != MVT::i8)) {
8805     SDValue LHS = Cond.getOperand(0);
8806     SDValue RHS = Cond.getOperand(1);
8807     unsigned X86Opcode;
8808     unsigned X86Cond;
8809     SDVTList VTs;
8810     switch (CondOpcode) {
8811     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8812     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8813     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8814     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8815     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8816     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8817     default: llvm_unreachable("unexpected overflowing operator");
8818     }
8819     if (CondOpcode == ISD::UMULO)
8820       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8821                           MVT::i32);
8822     else
8823       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8824
8825     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8826
8827     if (CondOpcode == ISD::UMULO)
8828       Cond = X86Op.getValue(2);
8829     else
8830       Cond = X86Op.getValue(1);
8831
8832     CC = DAG.getConstant(X86Cond, MVT::i8);
8833     addTest = false;
8834   }
8835
8836   if (addTest) {
8837     // Look pass the truncate if the high bits are known zero.
8838     if (isTruncWithZeroHighBitsInput(Cond, DAG))
8839         Cond = Cond.getOperand(0);
8840
8841     // We know the result of AND is compared against zero. Try to match
8842     // it to BT.
8843     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8844       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8845       if (NewSetCC.getNode()) {
8846         CC = NewSetCC.getOperand(0);
8847         Cond = NewSetCC.getOperand(1);
8848         addTest = false;
8849       }
8850     }
8851   }
8852
8853   if (addTest) {
8854     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8855     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8856   }
8857
8858   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8859   // a <  b ?  0 : -1 -> RES = setcc_carry
8860   // a >= b ? -1 :  0 -> RES = setcc_carry
8861   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8862   if (Cond.getOpcode() == X86ISD::SUB) {
8863     Cond = ConvertCmpIfNecessary(Cond, DAG);
8864     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8865
8866     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8867         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8868       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8869                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8870       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8871         return DAG.getNOT(DL, Res, Res.getValueType());
8872       return Res;
8873     }
8874   }
8875
8876   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8877   // condition is true.
8878   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8879   SDValue Ops[] = { Op2, Op1, CC, Cond };
8880   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8881 }
8882
8883 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8884 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8885 // from the AND / OR.
8886 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8887   Opc = Op.getOpcode();
8888   if (Opc != ISD::OR && Opc != ISD::AND)
8889     return false;
8890   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8891           Op.getOperand(0).hasOneUse() &&
8892           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8893           Op.getOperand(1).hasOneUse());
8894 }
8895
8896 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8897 // 1 and that the SETCC node has a single use.
8898 static bool isXor1OfSetCC(SDValue Op) {
8899   if (Op.getOpcode() != ISD::XOR)
8900     return false;
8901   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8902   if (N1C && N1C->getAPIntValue() == 1) {
8903     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8904       Op.getOperand(0).hasOneUse();
8905   }
8906   return false;
8907 }
8908
8909 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8910   bool addTest = true;
8911   SDValue Chain = Op.getOperand(0);
8912   SDValue Cond  = Op.getOperand(1);
8913   SDValue Dest  = Op.getOperand(2);
8914   DebugLoc dl = Op.getDebugLoc();
8915   SDValue CC;
8916   bool Inverted = false;
8917
8918   if (Cond.getOpcode() == ISD::SETCC) {
8919     // Check for setcc([su]{add,sub,mul}o == 0).
8920     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8921         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8922         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8923         Cond.getOperand(0).getResNo() == 1 &&
8924         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8925          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8926          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8927          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8928          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8929          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8930       Inverted = true;
8931       Cond = Cond.getOperand(0);
8932     } else {
8933       SDValue NewCond = LowerSETCC(Cond, DAG);
8934       if (NewCond.getNode())
8935         Cond = NewCond;
8936     }
8937   }
8938 #if 0
8939   // FIXME: LowerXALUO doesn't handle these!!
8940   else if (Cond.getOpcode() == X86ISD::ADD  ||
8941            Cond.getOpcode() == X86ISD::SUB  ||
8942            Cond.getOpcode() == X86ISD::SMUL ||
8943            Cond.getOpcode() == X86ISD::UMUL)
8944     Cond = LowerXALUO(Cond, DAG);
8945 #endif
8946
8947   // Look pass (and (setcc_carry (cmp ...)), 1).
8948   if (Cond.getOpcode() == ISD::AND &&
8949       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8950     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8951     if (C && C->getAPIntValue() == 1)
8952       Cond = Cond.getOperand(0);
8953   }
8954
8955   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8956   // setting operand in place of the X86ISD::SETCC.
8957   unsigned CondOpcode = Cond.getOpcode();
8958   if (CondOpcode == X86ISD::SETCC ||
8959       CondOpcode == X86ISD::SETCC_CARRY) {
8960     CC = Cond.getOperand(0);
8961
8962     SDValue Cmp = Cond.getOperand(1);
8963     unsigned Opc = Cmp.getOpcode();
8964     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8965     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8966       Cond = Cmp;
8967       addTest = false;
8968     } else {
8969       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8970       default: break;
8971       case X86::COND_O:
8972       case X86::COND_B:
8973         // These can only come from an arithmetic instruction with overflow,
8974         // e.g. SADDO, UADDO.
8975         Cond = Cond.getNode()->getOperand(1);
8976         addTest = false;
8977         break;
8978       }
8979     }
8980   }
8981   CondOpcode = Cond.getOpcode();
8982   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8983       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8984       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8985        Cond.getOperand(0).getValueType() != MVT::i8)) {
8986     SDValue LHS = Cond.getOperand(0);
8987     SDValue RHS = Cond.getOperand(1);
8988     unsigned X86Opcode;
8989     unsigned X86Cond;
8990     SDVTList VTs;
8991     switch (CondOpcode) {
8992     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8993     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8994     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8995     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8996     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8997     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8998     default: llvm_unreachable("unexpected overflowing operator");
8999     }
9000     if (Inverted)
9001       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9002     if (CondOpcode == ISD::UMULO)
9003       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9004                           MVT::i32);
9005     else
9006       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9007
9008     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9009
9010     if (CondOpcode == ISD::UMULO)
9011       Cond = X86Op.getValue(2);
9012     else
9013       Cond = X86Op.getValue(1);
9014
9015     CC = DAG.getConstant(X86Cond, MVT::i8);
9016     addTest = false;
9017   } else {
9018     unsigned CondOpc;
9019     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9020       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9021       if (CondOpc == ISD::OR) {
9022         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9023         // two branches instead of an explicit OR instruction with a
9024         // separate test.
9025         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9026             isX86LogicalCmp(Cmp)) {
9027           CC = Cond.getOperand(0).getOperand(0);
9028           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9029                               Chain, Dest, CC, Cmp);
9030           CC = Cond.getOperand(1).getOperand(0);
9031           Cond = Cmp;
9032           addTest = false;
9033         }
9034       } else { // ISD::AND
9035         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9036         // two branches instead of an explicit AND instruction with a
9037         // separate test. However, we only do this if this block doesn't
9038         // have a fall-through edge, because this requires an explicit
9039         // jmp when the condition is false.
9040         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9041             isX86LogicalCmp(Cmp) &&
9042             Op.getNode()->hasOneUse()) {
9043           X86::CondCode CCode =
9044             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9045           CCode = X86::GetOppositeBranchCondition(CCode);
9046           CC = DAG.getConstant(CCode, MVT::i8);
9047           SDNode *User = *Op.getNode()->use_begin();
9048           // Look for an unconditional branch following this conditional branch.
9049           // We need this because we need to reverse the successors in order
9050           // to implement FCMP_OEQ.
9051           if (User->getOpcode() == ISD::BR) {
9052             SDValue FalseBB = User->getOperand(1);
9053             SDNode *NewBR =
9054               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9055             assert(NewBR == User);
9056             (void)NewBR;
9057             Dest = FalseBB;
9058
9059             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9060                                 Chain, Dest, CC, Cmp);
9061             X86::CondCode CCode =
9062               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9063             CCode = X86::GetOppositeBranchCondition(CCode);
9064             CC = DAG.getConstant(CCode, MVT::i8);
9065             Cond = Cmp;
9066             addTest = false;
9067           }
9068         }
9069       }
9070     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9071       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9072       // It should be transformed during dag combiner except when the condition
9073       // is set by a arithmetics with overflow node.
9074       X86::CondCode CCode =
9075         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9076       CCode = X86::GetOppositeBranchCondition(CCode);
9077       CC = DAG.getConstant(CCode, MVT::i8);
9078       Cond = Cond.getOperand(0).getOperand(1);
9079       addTest = false;
9080     } else if (Cond.getOpcode() == ISD::SETCC &&
9081                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9082       // For FCMP_OEQ, we can emit
9083       // two branches instead of an explicit AND instruction with a
9084       // separate test. However, we only do this if this block doesn't
9085       // have a fall-through edge, because this requires an explicit
9086       // jmp when the condition is false.
9087       if (Op.getNode()->hasOneUse()) {
9088         SDNode *User = *Op.getNode()->use_begin();
9089         // Look for an unconditional branch following this conditional branch.
9090         // We need this because we need to reverse the successors in order
9091         // to implement FCMP_OEQ.
9092         if (User->getOpcode() == ISD::BR) {
9093           SDValue FalseBB = User->getOperand(1);
9094           SDNode *NewBR =
9095             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9096           assert(NewBR == User);
9097           (void)NewBR;
9098           Dest = FalseBB;
9099
9100           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9101                                     Cond.getOperand(0), Cond.getOperand(1));
9102           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9103           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9104           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9105                               Chain, Dest, CC, Cmp);
9106           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9107           Cond = Cmp;
9108           addTest = false;
9109         }
9110       }
9111     } else if (Cond.getOpcode() == ISD::SETCC &&
9112                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9113       // For FCMP_UNE, we can emit
9114       // two branches instead of an explicit AND instruction with a
9115       // separate test. However, we only do this if this block doesn't
9116       // have a fall-through edge, because this requires an explicit
9117       // jmp when the condition is false.
9118       if (Op.getNode()->hasOneUse()) {
9119         SDNode *User = *Op.getNode()->use_begin();
9120         // Look for an unconditional branch following this conditional branch.
9121         // We need this because we need to reverse the successors in order
9122         // to implement FCMP_UNE.
9123         if (User->getOpcode() == ISD::BR) {
9124           SDValue FalseBB = User->getOperand(1);
9125           SDNode *NewBR =
9126             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9127           assert(NewBR == User);
9128           (void)NewBR;
9129
9130           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9131                                     Cond.getOperand(0), Cond.getOperand(1));
9132           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9133           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9134           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9135                               Chain, Dest, CC, Cmp);
9136           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9137           Cond = Cmp;
9138           addTest = false;
9139           Dest = FalseBB;
9140         }
9141       }
9142     }
9143   }
9144
9145   if (addTest) {
9146     // Look pass the truncate if the high bits are known zero.
9147     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9148         Cond = Cond.getOperand(0);
9149
9150     // We know the result of AND is compared against zero. Try to match
9151     // it to BT.
9152     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9153       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9154       if (NewSetCC.getNode()) {
9155         CC = NewSetCC.getOperand(0);
9156         Cond = NewSetCC.getOperand(1);
9157         addTest = false;
9158       }
9159     }
9160   }
9161
9162   if (addTest) {
9163     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9164     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9165   }
9166   Cond = ConvertCmpIfNecessary(Cond, DAG);
9167   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9168                      Chain, Dest, CC, Cond);
9169 }
9170
9171
9172 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9173 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9174 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9175 // that the guard pages used by the OS virtual memory manager are allocated in
9176 // correct sequence.
9177 SDValue
9178 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9179                                            SelectionDAG &DAG) const {
9180   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9181           getTargetMachine().Options.EnableSegmentedStacks) &&
9182          "This should be used only on Windows targets or when segmented stacks "
9183          "are being used");
9184   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9185   DebugLoc dl = Op.getDebugLoc();
9186
9187   // Get the inputs.
9188   SDValue Chain = Op.getOperand(0);
9189   SDValue Size  = Op.getOperand(1);
9190   // FIXME: Ensure alignment here
9191
9192   bool Is64Bit = Subtarget->is64Bit();
9193   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9194
9195   if (getTargetMachine().Options.EnableSegmentedStacks) {
9196     MachineFunction &MF = DAG.getMachineFunction();
9197     MachineRegisterInfo &MRI = MF.getRegInfo();
9198
9199     if (Is64Bit) {
9200       // The 64 bit implementation of segmented stacks needs to clobber both r10
9201       // r11. This makes it impossible to use it along with nested parameters.
9202       const Function *F = MF.getFunction();
9203
9204       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9205            I != E; ++I)
9206         if (I->hasNestAttr())
9207           report_fatal_error("Cannot use segmented stacks with functions that "
9208                              "have nested arguments.");
9209     }
9210
9211     const TargetRegisterClass *AddrRegClass =
9212       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9213     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9214     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9215     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9216                                 DAG.getRegister(Vreg, SPTy));
9217     SDValue Ops1[2] = { Value, Chain };
9218     return DAG.getMergeValues(Ops1, 2, dl);
9219   } else {
9220     SDValue Flag;
9221     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9222
9223     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9224     Flag = Chain.getValue(1);
9225     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9226
9227     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9228     Flag = Chain.getValue(1);
9229
9230     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9231
9232     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9233     return DAG.getMergeValues(Ops1, 2, dl);
9234   }
9235 }
9236
9237 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9238   MachineFunction &MF = DAG.getMachineFunction();
9239   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9240
9241   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9242   DebugLoc DL = Op.getDebugLoc();
9243
9244   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9245     // vastart just stores the address of the VarArgsFrameIndex slot into the
9246     // memory location argument.
9247     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9248                                    getPointerTy());
9249     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9250                         MachinePointerInfo(SV), false, false, 0);
9251   }
9252
9253   // __va_list_tag:
9254   //   gp_offset         (0 - 6 * 8)
9255   //   fp_offset         (48 - 48 + 8 * 16)
9256   //   overflow_arg_area (point to parameters coming in memory).
9257   //   reg_save_area
9258   SmallVector<SDValue, 8> MemOps;
9259   SDValue FIN = Op.getOperand(1);
9260   // Store gp_offset
9261   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9262                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9263                                                MVT::i32),
9264                                FIN, MachinePointerInfo(SV), false, false, 0);
9265   MemOps.push_back(Store);
9266
9267   // Store fp_offset
9268   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9269                     FIN, DAG.getIntPtrConstant(4));
9270   Store = DAG.getStore(Op.getOperand(0), DL,
9271                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9272                                        MVT::i32),
9273                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9274   MemOps.push_back(Store);
9275
9276   // Store ptr to overflow_arg_area
9277   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9278                     FIN, DAG.getIntPtrConstant(4));
9279   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9280                                     getPointerTy());
9281   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9282                        MachinePointerInfo(SV, 8),
9283                        false, false, 0);
9284   MemOps.push_back(Store);
9285
9286   // Store ptr to reg_save_area.
9287   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9288                     FIN, DAG.getIntPtrConstant(8));
9289   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9290                                     getPointerTy());
9291   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9292                        MachinePointerInfo(SV, 16), false, false, 0);
9293   MemOps.push_back(Store);
9294   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9295                      &MemOps[0], MemOps.size());
9296 }
9297
9298 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9299   assert(Subtarget->is64Bit() &&
9300          "LowerVAARG only handles 64-bit va_arg!");
9301   assert((Subtarget->isTargetLinux() ||
9302           Subtarget->isTargetDarwin()) &&
9303           "Unhandled target in LowerVAARG");
9304   assert(Op.getNode()->getNumOperands() == 4);
9305   SDValue Chain = Op.getOperand(0);
9306   SDValue SrcPtr = Op.getOperand(1);
9307   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9308   unsigned Align = Op.getConstantOperandVal(3);
9309   DebugLoc dl = Op.getDebugLoc();
9310
9311   EVT ArgVT = Op.getNode()->getValueType(0);
9312   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9313   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9314   uint8_t ArgMode;
9315
9316   // Decide which area this value should be read from.
9317   // TODO: Implement the AMD64 ABI in its entirety. This simple
9318   // selection mechanism works only for the basic types.
9319   if (ArgVT == MVT::f80) {
9320     llvm_unreachable("va_arg for f80 not yet implemented");
9321   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9322     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9323   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9324     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9325   } else {
9326     llvm_unreachable("Unhandled argument type in LowerVAARG");
9327   }
9328
9329   if (ArgMode == 2) {
9330     // Sanity Check: Make sure using fp_offset makes sense.
9331     assert(!getTargetMachine().Options.UseSoftFloat &&
9332            !(DAG.getMachineFunction()
9333                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9334            Subtarget->hasSSE1());
9335   }
9336
9337   // Insert VAARG_64 node into the DAG
9338   // VAARG_64 returns two values: Variable Argument Address, Chain
9339   SmallVector<SDValue, 11> InstOps;
9340   InstOps.push_back(Chain);
9341   InstOps.push_back(SrcPtr);
9342   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9343   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9344   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9345   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9346   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9347                                           VTs, &InstOps[0], InstOps.size(),
9348                                           MVT::i64,
9349                                           MachinePointerInfo(SV),
9350                                           /*Align=*/0,
9351                                           /*Volatile=*/false,
9352                                           /*ReadMem=*/true,
9353                                           /*WriteMem=*/true);
9354   Chain = VAARG.getValue(1);
9355
9356   // Load the next argument and return it
9357   return DAG.getLoad(ArgVT, dl,
9358                      Chain,
9359                      VAARG,
9360                      MachinePointerInfo(),
9361                      false, false, false, 0);
9362 }
9363
9364 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9365   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9366   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9367   SDValue Chain = Op.getOperand(0);
9368   SDValue DstPtr = Op.getOperand(1);
9369   SDValue SrcPtr = Op.getOperand(2);
9370   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9371   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9372   DebugLoc DL = Op.getDebugLoc();
9373
9374   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9375                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9376                        false,
9377                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9378 }
9379
9380 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9381 // may or may not be a constant. Takes immediate version of shift as input.
9382 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9383                                    SDValue SrcOp, SDValue ShAmt,
9384                                    SelectionDAG &DAG) {
9385   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9386
9387   if (isa<ConstantSDNode>(ShAmt)) {
9388     // Constant may be a TargetConstant. Use a regular constant.
9389     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9390     switch (Opc) {
9391       default: llvm_unreachable("Unknown target vector shift node");
9392       case X86ISD::VSHLI:
9393       case X86ISD::VSRLI:
9394       case X86ISD::VSRAI:
9395         return DAG.getNode(Opc, dl, VT, SrcOp,
9396                            DAG.getConstant(ShiftAmt, MVT::i32));
9397     }
9398   }
9399
9400   // Change opcode to non-immediate version
9401   switch (Opc) {
9402     default: llvm_unreachable("Unknown target vector shift node");
9403     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9404     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9405     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9406   }
9407
9408   // Need to build a vector containing shift amount
9409   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9410   SDValue ShOps[4];
9411   ShOps[0] = ShAmt;
9412   ShOps[1] = DAG.getConstant(0, MVT::i32);
9413   ShOps[2] = DAG.getUNDEF(MVT::i32);
9414   ShOps[3] = DAG.getUNDEF(MVT::i32);
9415   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9416
9417   // The return type has to be a 128-bit type with the same element
9418   // type as the input type.
9419   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9420   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9421
9422   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9423   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9424 }
9425
9426 SDValue
9427 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9428   DebugLoc dl = Op.getDebugLoc();
9429   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9430   switch (IntNo) {
9431   default: return SDValue();    // Don't custom lower most intrinsics.
9432   // Comparison intrinsics.
9433   case Intrinsic::x86_sse_comieq_ss:
9434   case Intrinsic::x86_sse_comilt_ss:
9435   case Intrinsic::x86_sse_comile_ss:
9436   case Intrinsic::x86_sse_comigt_ss:
9437   case Intrinsic::x86_sse_comige_ss:
9438   case Intrinsic::x86_sse_comineq_ss:
9439   case Intrinsic::x86_sse_ucomieq_ss:
9440   case Intrinsic::x86_sse_ucomilt_ss:
9441   case Intrinsic::x86_sse_ucomile_ss:
9442   case Intrinsic::x86_sse_ucomigt_ss:
9443   case Intrinsic::x86_sse_ucomige_ss:
9444   case Intrinsic::x86_sse_ucomineq_ss:
9445   case Intrinsic::x86_sse2_comieq_sd:
9446   case Intrinsic::x86_sse2_comilt_sd:
9447   case Intrinsic::x86_sse2_comile_sd:
9448   case Intrinsic::x86_sse2_comigt_sd:
9449   case Intrinsic::x86_sse2_comige_sd:
9450   case Intrinsic::x86_sse2_comineq_sd:
9451   case Intrinsic::x86_sse2_ucomieq_sd:
9452   case Intrinsic::x86_sse2_ucomilt_sd:
9453   case Intrinsic::x86_sse2_ucomile_sd:
9454   case Intrinsic::x86_sse2_ucomigt_sd:
9455   case Intrinsic::x86_sse2_ucomige_sd:
9456   case Intrinsic::x86_sse2_ucomineq_sd: {
9457     unsigned Opc = 0;
9458     ISD::CondCode CC = ISD::SETCC_INVALID;
9459     switch (IntNo) {
9460     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9461     case Intrinsic::x86_sse_comieq_ss:
9462     case Intrinsic::x86_sse2_comieq_sd:
9463       Opc = X86ISD::COMI;
9464       CC = ISD::SETEQ;
9465       break;
9466     case Intrinsic::x86_sse_comilt_ss:
9467     case Intrinsic::x86_sse2_comilt_sd:
9468       Opc = X86ISD::COMI;
9469       CC = ISD::SETLT;
9470       break;
9471     case Intrinsic::x86_sse_comile_ss:
9472     case Intrinsic::x86_sse2_comile_sd:
9473       Opc = X86ISD::COMI;
9474       CC = ISD::SETLE;
9475       break;
9476     case Intrinsic::x86_sse_comigt_ss:
9477     case Intrinsic::x86_sse2_comigt_sd:
9478       Opc = X86ISD::COMI;
9479       CC = ISD::SETGT;
9480       break;
9481     case Intrinsic::x86_sse_comige_ss:
9482     case Intrinsic::x86_sse2_comige_sd:
9483       Opc = X86ISD::COMI;
9484       CC = ISD::SETGE;
9485       break;
9486     case Intrinsic::x86_sse_comineq_ss:
9487     case Intrinsic::x86_sse2_comineq_sd:
9488       Opc = X86ISD::COMI;
9489       CC = ISD::SETNE;
9490       break;
9491     case Intrinsic::x86_sse_ucomieq_ss:
9492     case Intrinsic::x86_sse2_ucomieq_sd:
9493       Opc = X86ISD::UCOMI;
9494       CC = ISD::SETEQ;
9495       break;
9496     case Intrinsic::x86_sse_ucomilt_ss:
9497     case Intrinsic::x86_sse2_ucomilt_sd:
9498       Opc = X86ISD::UCOMI;
9499       CC = ISD::SETLT;
9500       break;
9501     case Intrinsic::x86_sse_ucomile_ss:
9502     case Intrinsic::x86_sse2_ucomile_sd:
9503       Opc = X86ISD::UCOMI;
9504       CC = ISD::SETLE;
9505       break;
9506     case Intrinsic::x86_sse_ucomigt_ss:
9507     case Intrinsic::x86_sse2_ucomigt_sd:
9508       Opc = X86ISD::UCOMI;
9509       CC = ISD::SETGT;
9510       break;
9511     case Intrinsic::x86_sse_ucomige_ss:
9512     case Intrinsic::x86_sse2_ucomige_sd:
9513       Opc = X86ISD::UCOMI;
9514       CC = ISD::SETGE;
9515       break;
9516     case Intrinsic::x86_sse_ucomineq_ss:
9517     case Intrinsic::x86_sse2_ucomineq_sd:
9518       Opc = X86ISD::UCOMI;
9519       CC = ISD::SETNE;
9520       break;
9521     }
9522
9523     SDValue LHS = Op.getOperand(1);
9524     SDValue RHS = Op.getOperand(2);
9525     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9526     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9527     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9528     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9529                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9530     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9531   }
9532   // Arithmetic intrinsics.
9533   case Intrinsic::x86_sse2_pmulu_dq:
9534   case Intrinsic::x86_avx2_pmulu_dq:
9535     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9536                        Op.getOperand(1), Op.getOperand(2));
9537   case Intrinsic::x86_sse3_hadd_ps:
9538   case Intrinsic::x86_sse3_hadd_pd:
9539   case Intrinsic::x86_avx_hadd_ps_256:
9540   case Intrinsic::x86_avx_hadd_pd_256:
9541     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9542                        Op.getOperand(1), Op.getOperand(2));
9543   case Intrinsic::x86_sse3_hsub_ps:
9544   case Intrinsic::x86_sse3_hsub_pd:
9545   case Intrinsic::x86_avx_hsub_ps_256:
9546   case Intrinsic::x86_avx_hsub_pd_256:
9547     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9548                        Op.getOperand(1), Op.getOperand(2));
9549   case Intrinsic::x86_ssse3_phadd_w_128:
9550   case Intrinsic::x86_ssse3_phadd_d_128:
9551   case Intrinsic::x86_avx2_phadd_w:
9552   case Intrinsic::x86_avx2_phadd_d:
9553     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9554                        Op.getOperand(1), Op.getOperand(2));
9555   case Intrinsic::x86_ssse3_phsub_w_128:
9556   case Intrinsic::x86_ssse3_phsub_d_128:
9557   case Intrinsic::x86_avx2_phsub_w:
9558   case Intrinsic::x86_avx2_phsub_d:
9559     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9560                        Op.getOperand(1), Op.getOperand(2));
9561   case Intrinsic::x86_avx2_psllv_d:
9562   case Intrinsic::x86_avx2_psllv_q:
9563   case Intrinsic::x86_avx2_psllv_d_256:
9564   case Intrinsic::x86_avx2_psllv_q_256:
9565     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9566                       Op.getOperand(1), Op.getOperand(2));
9567   case Intrinsic::x86_avx2_psrlv_d:
9568   case Intrinsic::x86_avx2_psrlv_q:
9569   case Intrinsic::x86_avx2_psrlv_d_256:
9570   case Intrinsic::x86_avx2_psrlv_q_256:
9571     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9572                       Op.getOperand(1), Op.getOperand(2));
9573   case Intrinsic::x86_avx2_psrav_d:
9574   case Intrinsic::x86_avx2_psrav_d_256:
9575     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9576                       Op.getOperand(1), Op.getOperand(2));
9577   case Intrinsic::x86_ssse3_pshuf_b_128:
9578   case Intrinsic::x86_avx2_pshuf_b:
9579     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9580                        Op.getOperand(1), Op.getOperand(2));
9581   case Intrinsic::x86_ssse3_psign_b_128:
9582   case Intrinsic::x86_ssse3_psign_w_128:
9583   case Intrinsic::x86_ssse3_psign_d_128:
9584   case Intrinsic::x86_avx2_psign_b:
9585   case Intrinsic::x86_avx2_psign_w:
9586   case Intrinsic::x86_avx2_psign_d:
9587     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9588                        Op.getOperand(1), Op.getOperand(2));
9589   case Intrinsic::x86_sse41_insertps:
9590     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9591                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9592   case Intrinsic::x86_avx_vperm2f128_ps_256:
9593   case Intrinsic::x86_avx_vperm2f128_pd_256:
9594   case Intrinsic::x86_avx_vperm2f128_si_256:
9595   case Intrinsic::x86_avx2_vperm2i128:
9596     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9597                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9598   case Intrinsic::x86_avx2_permd:
9599   case Intrinsic::x86_avx2_permps:
9600     // Operands intentionally swapped. Mask is last operand to intrinsic,
9601     // but second operand for node/intruction.
9602     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9603                        Op.getOperand(2), Op.getOperand(1));
9604
9605   // ptest and testp intrinsics. The intrinsic these come from are designed to
9606   // return an integer value, not just an instruction so lower it to the ptest
9607   // or testp pattern and a setcc for the result.
9608   case Intrinsic::x86_sse41_ptestz:
9609   case Intrinsic::x86_sse41_ptestc:
9610   case Intrinsic::x86_sse41_ptestnzc:
9611   case Intrinsic::x86_avx_ptestz_256:
9612   case Intrinsic::x86_avx_ptestc_256:
9613   case Intrinsic::x86_avx_ptestnzc_256:
9614   case Intrinsic::x86_avx_vtestz_ps:
9615   case Intrinsic::x86_avx_vtestc_ps:
9616   case Intrinsic::x86_avx_vtestnzc_ps:
9617   case Intrinsic::x86_avx_vtestz_pd:
9618   case Intrinsic::x86_avx_vtestc_pd:
9619   case Intrinsic::x86_avx_vtestnzc_pd:
9620   case Intrinsic::x86_avx_vtestz_ps_256:
9621   case Intrinsic::x86_avx_vtestc_ps_256:
9622   case Intrinsic::x86_avx_vtestnzc_ps_256:
9623   case Intrinsic::x86_avx_vtestz_pd_256:
9624   case Intrinsic::x86_avx_vtestc_pd_256:
9625   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9626     bool IsTestPacked = false;
9627     unsigned X86CC = 0;
9628     switch (IntNo) {
9629     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9630     case Intrinsic::x86_avx_vtestz_ps:
9631     case Intrinsic::x86_avx_vtestz_pd:
9632     case Intrinsic::x86_avx_vtestz_ps_256:
9633     case Intrinsic::x86_avx_vtestz_pd_256:
9634       IsTestPacked = true; // Fallthrough
9635     case Intrinsic::x86_sse41_ptestz:
9636     case Intrinsic::x86_avx_ptestz_256:
9637       // ZF = 1
9638       X86CC = X86::COND_E;
9639       break;
9640     case Intrinsic::x86_avx_vtestc_ps:
9641     case Intrinsic::x86_avx_vtestc_pd:
9642     case Intrinsic::x86_avx_vtestc_ps_256:
9643     case Intrinsic::x86_avx_vtestc_pd_256:
9644       IsTestPacked = true; // Fallthrough
9645     case Intrinsic::x86_sse41_ptestc:
9646     case Intrinsic::x86_avx_ptestc_256:
9647       // CF = 1
9648       X86CC = X86::COND_B;
9649       break;
9650     case Intrinsic::x86_avx_vtestnzc_ps:
9651     case Intrinsic::x86_avx_vtestnzc_pd:
9652     case Intrinsic::x86_avx_vtestnzc_ps_256:
9653     case Intrinsic::x86_avx_vtestnzc_pd_256:
9654       IsTestPacked = true; // Fallthrough
9655     case Intrinsic::x86_sse41_ptestnzc:
9656     case Intrinsic::x86_avx_ptestnzc_256:
9657       // ZF and CF = 0
9658       X86CC = X86::COND_A;
9659       break;
9660     }
9661
9662     SDValue LHS = Op.getOperand(1);
9663     SDValue RHS = Op.getOperand(2);
9664     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9665     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9666     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9667     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9668     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9669   }
9670
9671   // SSE/AVX shift intrinsics
9672   case Intrinsic::x86_sse2_psll_w:
9673   case Intrinsic::x86_sse2_psll_d:
9674   case Intrinsic::x86_sse2_psll_q:
9675   case Intrinsic::x86_avx2_psll_w:
9676   case Intrinsic::x86_avx2_psll_d:
9677   case Intrinsic::x86_avx2_psll_q:
9678     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9679                        Op.getOperand(1), Op.getOperand(2));
9680   case Intrinsic::x86_sse2_psrl_w:
9681   case Intrinsic::x86_sse2_psrl_d:
9682   case Intrinsic::x86_sse2_psrl_q:
9683   case Intrinsic::x86_avx2_psrl_w:
9684   case Intrinsic::x86_avx2_psrl_d:
9685   case Intrinsic::x86_avx2_psrl_q:
9686     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9687                        Op.getOperand(1), Op.getOperand(2));
9688   case Intrinsic::x86_sse2_psra_w:
9689   case Intrinsic::x86_sse2_psra_d:
9690   case Intrinsic::x86_avx2_psra_w:
9691   case Intrinsic::x86_avx2_psra_d:
9692     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9693                        Op.getOperand(1), Op.getOperand(2));
9694   case Intrinsic::x86_sse2_pslli_w:
9695   case Intrinsic::x86_sse2_pslli_d:
9696   case Intrinsic::x86_sse2_pslli_q:
9697   case Intrinsic::x86_avx2_pslli_w:
9698   case Intrinsic::x86_avx2_pslli_d:
9699   case Intrinsic::x86_avx2_pslli_q:
9700     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9701                                Op.getOperand(1), Op.getOperand(2), DAG);
9702   case Intrinsic::x86_sse2_psrli_w:
9703   case Intrinsic::x86_sse2_psrli_d:
9704   case Intrinsic::x86_sse2_psrli_q:
9705   case Intrinsic::x86_avx2_psrli_w:
9706   case Intrinsic::x86_avx2_psrli_d:
9707   case Intrinsic::x86_avx2_psrli_q:
9708     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9709                                Op.getOperand(1), Op.getOperand(2), DAG);
9710   case Intrinsic::x86_sse2_psrai_w:
9711   case Intrinsic::x86_sse2_psrai_d:
9712   case Intrinsic::x86_avx2_psrai_w:
9713   case Intrinsic::x86_avx2_psrai_d:
9714     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9715                                Op.getOperand(1), Op.getOperand(2), DAG);
9716   // Fix vector shift instructions where the last operand is a non-immediate
9717   // i32 value.
9718   case Intrinsic::x86_mmx_pslli_w:
9719   case Intrinsic::x86_mmx_pslli_d:
9720   case Intrinsic::x86_mmx_pslli_q:
9721   case Intrinsic::x86_mmx_psrli_w:
9722   case Intrinsic::x86_mmx_psrli_d:
9723   case Intrinsic::x86_mmx_psrli_q:
9724   case Intrinsic::x86_mmx_psrai_w:
9725   case Intrinsic::x86_mmx_psrai_d: {
9726     SDValue ShAmt = Op.getOperand(2);
9727     if (isa<ConstantSDNode>(ShAmt))
9728       return SDValue();
9729
9730     unsigned NewIntNo = 0;
9731     switch (IntNo) {
9732     case Intrinsic::x86_mmx_pslli_w:
9733       NewIntNo = Intrinsic::x86_mmx_psll_w;
9734       break;
9735     case Intrinsic::x86_mmx_pslli_d:
9736       NewIntNo = Intrinsic::x86_mmx_psll_d;
9737       break;
9738     case Intrinsic::x86_mmx_pslli_q:
9739       NewIntNo = Intrinsic::x86_mmx_psll_q;
9740       break;
9741     case Intrinsic::x86_mmx_psrli_w:
9742       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9743       break;
9744     case Intrinsic::x86_mmx_psrli_d:
9745       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9746       break;
9747     case Intrinsic::x86_mmx_psrli_q:
9748       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9749       break;
9750     case Intrinsic::x86_mmx_psrai_w:
9751       NewIntNo = Intrinsic::x86_mmx_psra_w;
9752       break;
9753     case Intrinsic::x86_mmx_psrai_d:
9754       NewIntNo = Intrinsic::x86_mmx_psra_d;
9755       break;
9756     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9757     }
9758
9759     // The vector shift intrinsics with scalars uses 32b shift amounts but
9760     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9761     // to be zero.
9762     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9763                          DAG.getConstant(0, MVT::i32));
9764 // FIXME this must be lowered to get rid of the invalid type.
9765
9766     EVT VT = Op.getValueType();
9767     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9768     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9769                        DAG.getConstant(NewIntNo, MVT::i32),
9770                        Op.getOperand(1), ShAmt);
9771   }
9772   case Intrinsic::x86_sse42_pcmpistria128:
9773   case Intrinsic::x86_sse42_pcmpestria128:
9774   case Intrinsic::x86_sse42_pcmpistric128:
9775   case Intrinsic::x86_sse42_pcmpestric128:
9776   case Intrinsic::x86_sse42_pcmpistrio128:
9777   case Intrinsic::x86_sse42_pcmpestrio128:
9778   case Intrinsic::x86_sse42_pcmpistris128:
9779   case Intrinsic::x86_sse42_pcmpestris128:
9780   case Intrinsic::x86_sse42_pcmpistriz128:
9781   case Intrinsic::x86_sse42_pcmpestriz128: {
9782     unsigned Opcode;
9783     unsigned X86CC;
9784     switch (IntNo) {
9785     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9786     case Intrinsic::x86_sse42_pcmpistria128:
9787       Opcode = X86ISD::PCMPISTRI;
9788       X86CC = X86::COND_A;
9789       break;
9790     case Intrinsic::x86_sse42_pcmpestria128:
9791       Opcode = X86ISD::PCMPESTRI;
9792       X86CC = X86::COND_A;
9793       break;
9794     case Intrinsic::x86_sse42_pcmpistric128:
9795       Opcode = X86ISD::PCMPISTRI;
9796       X86CC = X86::COND_B;
9797       break;
9798     case Intrinsic::x86_sse42_pcmpestric128:
9799       Opcode = X86ISD::PCMPESTRI;
9800       X86CC = X86::COND_B;
9801       break;
9802     case Intrinsic::x86_sse42_pcmpistrio128:
9803       Opcode = X86ISD::PCMPISTRI;
9804       X86CC = X86::COND_O;
9805       break;
9806     case Intrinsic::x86_sse42_pcmpestrio128:
9807       Opcode = X86ISD::PCMPESTRI;
9808       X86CC = X86::COND_O;
9809       break;
9810     case Intrinsic::x86_sse42_pcmpistris128:
9811       Opcode = X86ISD::PCMPISTRI;
9812       X86CC = X86::COND_S;
9813       break;
9814     case Intrinsic::x86_sse42_pcmpestris128:
9815       Opcode = X86ISD::PCMPESTRI;
9816       X86CC = X86::COND_S;
9817       break;
9818     case Intrinsic::x86_sse42_pcmpistriz128:
9819       Opcode = X86ISD::PCMPISTRI;
9820       X86CC = X86::COND_E;
9821       break;
9822     case Intrinsic::x86_sse42_pcmpestriz128:
9823       Opcode = X86ISD::PCMPESTRI;
9824       X86CC = X86::COND_E;
9825       break;
9826     }
9827     SmallVector<SDValue, 5> NewOps;
9828     NewOps.append(Op->op_begin()+1, Op->op_end());
9829     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9830     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
9831     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9832                                 DAG.getConstant(X86CC, MVT::i8),
9833                                 SDValue(PCMP.getNode(), 1));
9834     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9835   }
9836   case Intrinsic::x86_sse42_pcmpistri128:
9837   case Intrinsic::x86_sse42_pcmpestri128: {
9838     unsigned Opcode;
9839     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
9840       Opcode = X86ISD::PCMPISTRI;
9841     else
9842       Opcode = X86ISD::PCMPESTRI;
9843
9844     SmallVector<SDValue, 5> NewOps;
9845     NewOps.append(Op->op_begin()+1, Op->op_end());
9846     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9847     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
9848   }
9849   }
9850 }
9851
9852 SDValue
9853 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9854   DebugLoc dl = Op.getDebugLoc();
9855   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9856   switch (IntNo) {
9857   default: return SDValue();    // Don't custom lower most intrinsics.
9858
9859   // RDRAND intrinsics.
9860   case Intrinsic::x86_rdrand_16:
9861   case Intrinsic::x86_rdrand_32:
9862   case Intrinsic::x86_rdrand_64: {
9863     // Emit the node with the right value type.
9864     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
9865     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
9866
9867     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
9868     // return the value from Rand, which is always 0, casted to i32.
9869     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
9870                       DAG.getConstant(1, Op->getValueType(1)),
9871                       DAG.getConstant(X86::COND_B, MVT::i32),
9872                       SDValue(Result.getNode(), 1) };
9873     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
9874                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
9875                                   Ops, 4);
9876
9877     // Return { result, isValid, chain }.
9878     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
9879                        SDValue(Result.getNode(), 2));
9880   }
9881   }
9882 }
9883
9884 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9885                                            SelectionDAG &DAG) const {
9886   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9887   MFI->setReturnAddressIsTaken(true);
9888
9889   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9890   DebugLoc dl = Op.getDebugLoc();
9891
9892   if (Depth > 0) {
9893     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9894     SDValue Offset =
9895       DAG.getConstant(TD->getPointerSize(),
9896                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9897     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9898                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9899                                    FrameAddr, Offset),
9900                        MachinePointerInfo(), false, false, false, 0);
9901   }
9902
9903   // Just load the return address.
9904   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9905   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9906                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9907 }
9908
9909 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9910   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9911   MFI->setFrameAddressIsTaken(true);
9912
9913   EVT VT = Op.getValueType();
9914   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9915   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9916   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9917   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9918   while (Depth--)
9919     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9920                             MachinePointerInfo(),
9921                             false, false, false, 0);
9922   return FrameAddr;
9923 }
9924
9925 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9926                                                      SelectionDAG &DAG) const {
9927   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9928 }
9929
9930 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9931   SDValue Chain     = Op.getOperand(0);
9932   SDValue Offset    = Op.getOperand(1);
9933   SDValue Handler   = Op.getOperand(2);
9934   DebugLoc dl       = Op.getDebugLoc();
9935
9936   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9937                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9938                                      getPointerTy());
9939   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9940
9941   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9942                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9943   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9944   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9945                        false, false, 0);
9946   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9947
9948   return DAG.getNode(X86ISD::EH_RETURN, dl,
9949                      MVT::Other,
9950                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9951 }
9952
9953 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9954                                                   SelectionDAG &DAG) const {
9955   return Op.getOperand(0);
9956 }
9957
9958 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9959                                                 SelectionDAG &DAG) const {
9960   SDValue Root = Op.getOperand(0);
9961   SDValue Trmp = Op.getOperand(1); // trampoline
9962   SDValue FPtr = Op.getOperand(2); // nested function
9963   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9964   DebugLoc dl  = Op.getDebugLoc();
9965
9966   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9967
9968   if (Subtarget->is64Bit()) {
9969     SDValue OutChains[6];
9970
9971     // Large code-model.
9972     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9973     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9974
9975     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9976     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9977
9978     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9979
9980     // Load the pointer to the nested function into R11.
9981     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9982     SDValue Addr = Trmp;
9983     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9984                                 Addr, MachinePointerInfo(TrmpAddr),
9985                                 false, false, 0);
9986
9987     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9988                        DAG.getConstant(2, MVT::i64));
9989     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9990                                 MachinePointerInfo(TrmpAddr, 2),
9991                                 false, false, 2);
9992
9993     // Load the 'nest' parameter value into R10.
9994     // R10 is specified in X86CallingConv.td
9995     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9996     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9997                        DAG.getConstant(10, MVT::i64));
9998     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9999                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10000                                 false, false, 0);
10001
10002     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10003                        DAG.getConstant(12, MVT::i64));
10004     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10005                                 MachinePointerInfo(TrmpAddr, 12),
10006                                 false, false, 2);
10007
10008     // Jump to the nested function.
10009     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10010     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10011                        DAG.getConstant(20, MVT::i64));
10012     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10013                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10014                                 false, false, 0);
10015
10016     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10017     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10018                        DAG.getConstant(22, MVT::i64));
10019     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10020                                 MachinePointerInfo(TrmpAddr, 22),
10021                                 false, false, 0);
10022
10023     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10024   } else {
10025     const Function *Func =
10026       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10027     CallingConv::ID CC = Func->getCallingConv();
10028     unsigned NestReg;
10029
10030     switch (CC) {
10031     default:
10032       llvm_unreachable("Unsupported calling convention");
10033     case CallingConv::C:
10034     case CallingConv::X86_StdCall: {
10035       // Pass 'nest' parameter in ECX.
10036       // Must be kept in sync with X86CallingConv.td
10037       NestReg = X86::ECX;
10038
10039       // Check that ECX wasn't needed by an 'inreg' parameter.
10040       FunctionType *FTy = Func->getFunctionType();
10041       const AttrListPtr &Attrs = Func->getAttributes();
10042
10043       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10044         unsigned InRegCount = 0;
10045         unsigned Idx = 1;
10046
10047         for (FunctionType::param_iterator I = FTy->param_begin(),
10048              E = FTy->param_end(); I != E; ++I, ++Idx)
10049           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10050             // FIXME: should only count parameters that are lowered to integers.
10051             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10052
10053         if (InRegCount > 2) {
10054           report_fatal_error("Nest register in use - reduce number of inreg"
10055                              " parameters!");
10056         }
10057       }
10058       break;
10059     }
10060     case CallingConv::X86_FastCall:
10061     case CallingConv::X86_ThisCall:
10062     case CallingConv::Fast:
10063       // Pass 'nest' parameter in EAX.
10064       // Must be kept in sync with X86CallingConv.td
10065       NestReg = X86::EAX;
10066       break;
10067     }
10068
10069     SDValue OutChains[4];
10070     SDValue Addr, Disp;
10071
10072     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10073                        DAG.getConstant(10, MVT::i32));
10074     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10075
10076     // This is storing the opcode for MOV32ri.
10077     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10078     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10079     OutChains[0] = DAG.getStore(Root, dl,
10080                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10081                                 Trmp, MachinePointerInfo(TrmpAddr),
10082                                 false, false, 0);
10083
10084     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10085                        DAG.getConstant(1, MVT::i32));
10086     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10087                                 MachinePointerInfo(TrmpAddr, 1),
10088                                 false, false, 1);
10089
10090     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10091     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10092                        DAG.getConstant(5, MVT::i32));
10093     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10094                                 MachinePointerInfo(TrmpAddr, 5),
10095                                 false, false, 1);
10096
10097     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10098                        DAG.getConstant(6, MVT::i32));
10099     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10100                                 MachinePointerInfo(TrmpAddr, 6),
10101                                 false, false, 1);
10102
10103     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10104   }
10105 }
10106
10107 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10108                                             SelectionDAG &DAG) const {
10109   /*
10110    The rounding mode is in bits 11:10 of FPSR, and has the following
10111    settings:
10112      00 Round to nearest
10113      01 Round to -inf
10114      10 Round to +inf
10115      11 Round to 0
10116
10117   FLT_ROUNDS, on the other hand, expects the following:
10118     -1 Undefined
10119      0 Round to 0
10120      1 Round to nearest
10121      2 Round to +inf
10122      3 Round to -inf
10123
10124   To perform the conversion, we do:
10125     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10126   */
10127
10128   MachineFunction &MF = DAG.getMachineFunction();
10129   const TargetMachine &TM = MF.getTarget();
10130   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10131   unsigned StackAlignment = TFI.getStackAlignment();
10132   EVT VT = Op.getValueType();
10133   DebugLoc DL = Op.getDebugLoc();
10134
10135   // Save FP Control Word to stack slot
10136   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10137   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10138
10139
10140   MachineMemOperand *MMO =
10141    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10142                            MachineMemOperand::MOStore, 2, 2);
10143
10144   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10145   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10146                                           DAG.getVTList(MVT::Other),
10147                                           Ops, 2, MVT::i16, MMO);
10148
10149   // Load FP Control Word from stack slot
10150   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10151                             MachinePointerInfo(), false, false, false, 0);
10152
10153   // Transform as necessary
10154   SDValue CWD1 =
10155     DAG.getNode(ISD::SRL, DL, MVT::i16,
10156                 DAG.getNode(ISD::AND, DL, MVT::i16,
10157                             CWD, DAG.getConstant(0x800, MVT::i16)),
10158                 DAG.getConstant(11, MVT::i8));
10159   SDValue CWD2 =
10160     DAG.getNode(ISD::SRL, DL, MVT::i16,
10161                 DAG.getNode(ISD::AND, DL, MVT::i16,
10162                             CWD, DAG.getConstant(0x400, MVT::i16)),
10163                 DAG.getConstant(9, MVT::i8));
10164
10165   SDValue RetVal =
10166     DAG.getNode(ISD::AND, DL, MVT::i16,
10167                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10168                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10169                             DAG.getConstant(1, MVT::i16)),
10170                 DAG.getConstant(3, MVT::i16));
10171
10172
10173   return DAG.getNode((VT.getSizeInBits() < 16 ?
10174                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10175 }
10176
10177 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10178   EVT VT = Op.getValueType();
10179   EVT OpVT = VT;
10180   unsigned NumBits = VT.getSizeInBits();
10181   DebugLoc dl = Op.getDebugLoc();
10182
10183   Op = Op.getOperand(0);
10184   if (VT == MVT::i8) {
10185     // Zero extend to i32 since there is not an i8 bsr.
10186     OpVT = MVT::i32;
10187     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10188   }
10189
10190   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10191   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10192   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10193
10194   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10195   SDValue Ops[] = {
10196     Op,
10197     DAG.getConstant(NumBits+NumBits-1, OpVT),
10198     DAG.getConstant(X86::COND_E, MVT::i8),
10199     Op.getValue(1)
10200   };
10201   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10202
10203   // Finally xor with NumBits-1.
10204   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10205
10206   if (VT == MVT::i8)
10207     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10208   return Op;
10209 }
10210
10211 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10212                                                 SelectionDAG &DAG) const {
10213   EVT VT = Op.getValueType();
10214   EVT OpVT = VT;
10215   unsigned NumBits = VT.getSizeInBits();
10216   DebugLoc dl = Op.getDebugLoc();
10217
10218   Op = Op.getOperand(0);
10219   if (VT == MVT::i8) {
10220     // Zero extend to i32 since there is not an i8 bsr.
10221     OpVT = MVT::i32;
10222     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10223   }
10224
10225   // Issue a bsr (scan bits in reverse).
10226   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10227   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10228
10229   // And xor with NumBits-1.
10230   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10231
10232   if (VT == MVT::i8)
10233     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10234   return Op;
10235 }
10236
10237 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10238   EVT VT = Op.getValueType();
10239   unsigned NumBits = VT.getSizeInBits();
10240   DebugLoc dl = Op.getDebugLoc();
10241   Op = Op.getOperand(0);
10242
10243   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10244   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10245   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10246
10247   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10248   SDValue Ops[] = {
10249     Op,
10250     DAG.getConstant(NumBits, VT),
10251     DAG.getConstant(X86::COND_E, MVT::i8),
10252     Op.getValue(1)
10253   };
10254   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10255 }
10256
10257 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10258 // ones, and then concatenate the result back.
10259 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10260   EVT VT = Op.getValueType();
10261
10262   assert(VT.is256BitVector() && VT.isInteger() &&
10263          "Unsupported value type for operation");
10264
10265   unsigned NumElems = VT.getVectorNumElements();
10266   DebugLoc dl = Op.getDebugLoc();
10267
10268   // Extract the LHS vectors
10269   SDValue LHS = Op.getOperand(0);
10270   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10271   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10272
10273   // Extract the RHS vectors
10274   SDValue RHS = Op.getOperand(1);
10275   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10276   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10277
10278   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10279   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10280
10281   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10282                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10283                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10284 }
10285
10286 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10287   assert(Op.getValueType().is256BitVector() &&
10288          Op.getValueType().isInteger() &&
10289          "Only handle AVX 256-bit vector integer operation");
10290   return Lower256IntArith(Op, DAG);
10291 }
10292
10293 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10294   assert(Op.getValueType().is256BitVector() &&
10295          Op.getValueType().isInteger() &&
10296          "Only handle AVX 256-bit vector integer operation");
10297   return Lower256IntArith(Op, DAG);
10298 }
10299
10300 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10301   EVT VT = Op.getValueType();
10302
10303   // Decompose 256-bit ops into smaller 128-bit ops.
10304   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10305     return Lower256IntArith(Op, DAG);
10306
10307   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10308          "Only know how to lower V2I64/V4I64 multiply");
10309
10310   DebugLoc dl = Op.getDebugLoc();
10311
10312   //  Ahi = psrlqi(a, 32);
10313   //  Bhi = psrlqi(b, 32);
10314   //
10315   //  AloBlo = pmuludq(a, b);
10316   //  AloBhi = pmuludq(a, Bhi);
10317   //  AhiBlo = pmuludq(Ahi, b);
10318
10319   //  AloBhi = psllqi(AloBhi, 32);
10320   //  AhiBlo = psllqi(AhiBlo, 32);
10321   //  return AloBlo + AloBhi + AhiBlo;
10322
10323   SDValue A = Op.getOperand(0);
10324   SDValue B = Op.getOperand(1);
10325
10326   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10327
10328   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10329   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10330
10331   // Bit cast to 32-bit vectors for MULUDQ
10332   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10333   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10334   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10335   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10336   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10337
10338   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10339   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10340   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10341
10342   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10343   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10344
10345   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10346   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10347 }
10348
10349 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10350
10351   EVT VT = Op.getValueType();
10352   DebugLoc dl = Op.getDebugLoc();
10353   SDValue R = Op.getOperand(0);
10354   SDValue Amt = Op.getOperand(1);
10355   LLVMContext *Context = DAG.getContext();
10356
10357   if (!Subtarget->hasSSE2())
10358     return SDValue();
10359
10360   // Optimize shl/srl/sra with constant shift amount.
10361   if (isSplatVector(Amt.getNode())) {
10362     SDValue SclrAmt = Amt->getOperand(0);
10363     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10364       uint64_t ShiftAmt = C->getZExtValue();
10365
10366       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10367           (Subtarget->hasAVX2() &&
10368            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10369         if (Op.getOpcode() == ISD::SHL)
10370           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10371                              DAG.getConstant(ShiftAmt, MVT::i32));
10372         if (Op.getOpcode() == ISD::SRL)
10373           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10374                              DAG.getConstant(ShiftAmt, MVT::i32));
10375         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10376           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10377                              DAG.getConstant(ShiftAmt, MVT::i32));
10378       }
10379
10380       if (VT == MVT::v16i8) {
10381         if (Op.getOpcode() == ISD::SHL) {
10382           // Make a large shift.
10383           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10384                                     DAG.getConstant(ShiftAmt, MVT::i32));
10385           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10386           // Zero out the rightmost bits.
10387           SmallVector<SDValue, 16> V(16,
10388                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10389                                                      MVT::i8));
10390           return DAG.getNode(ISD::AND, dl, VT, SHL,
10391                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10392         }
10393         if (Op.getOpcode() == ISD::SRL) {
10394           // Make a large shift.
10395           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10396                                     DAG.getConstant(ShiftAmt, MVT::i32));
10397           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10398           // Zero out the leftmost bits.
10399           SmallVector<SDValue, 16> V(16,
10400                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10401                                                      MVT::i8));
10402           return DAG.getNode(ISD::AND, dl, VT, SRL,
10403                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10404         }
10405         if (Op.getOpcode() == ISD::SRA) {
10406           if (ShiftAmt == 7) {
10407             // R s>> 7  ===  R s< 0
10408             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10409             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10410           }
10411
10412           // R s>> a === ((R u>> a) ^ m) - m
10413           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10414           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10415                                                          MVT::i8));
10416           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10417           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10418           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10419           return Res;
10420         }
10421         llvm_unreachable("Unknown shift opcode.");
10422       }
10423
10424       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10425         if (Op.getOpcode() == ISD::SHL) {
10426           // Make a large shift.
10427           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10428                                     DAG.getConstant(ShiftAmt, MVT::i32));
10429           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10430           // Zero out the rightmost bits.
10431           SmallVector<SDValue, 32> V(32,
10432                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10433                                                      MVT::i8));
10434           return DAG.getNode(ISD::AND, dl, VT, SHL,
10435                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10436         }
10437         if (Op.getOpcode() == ISD::SRL) {
10438           // Make a large shift.
10439           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10440                                     DAG.getConstant(ShiftAmt, MVT::i32));
10441           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10442           // Zero out the leftmost bits.
10443           SmallVector<SDValue, 32> V(32,
10444                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10445                                                      MVT::i8));
10446           return DAG.getNode(ISD::AND, dl, VT, SRL,
10447                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10448         }
10449         if (Op.getOpcode() == ISD::SRA) {
10450           if (ShiftAmt == 7) {
10451             // R s>> 7  ===  R s< 0
10452             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10453             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10454           }
10455
10456           // R s>> a === ((R u>> a) ^ m) - m
10457           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10458           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10459                                                          MVT::i8));
10460           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10461           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10462           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10463           return Res;
10464         }
10465         llvm_unreachable("Unknown shift opcode.");
10466       }
10467     }
10468   }
10469
10470   // Lower SHL with variable shift amount.
10471   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10472     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10473                      DAG.getConstant(23, MVT::i32));
10474
10475     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10476     Constant *C = ConstantDataVector::get(*Context, CV);
10477     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10478     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10479                                  MachinePointerInfo::getConstantPool(),
10480                                  false, false, false, 16);
10481
10482     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10483     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10484     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10485     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10486   }
10487   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10488     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10489
10490     // a = a << 5;
10491     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10492                      DAG.getConstant(5, MVT::i32));
10493     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10494
10495     // Turn 'a' into a mask suitable for VSELECT
10496     SDValue VSelM = DAG.getConstant(0x80, VT);
10497     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10498     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10499
10500     SDValue CM1 = DAG.getConstant(0x0f, VT);
10501     SDValue CM2 = DAG.getConstant(0x3f, VT);
10502
10503     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10504     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10505     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10506                             DAG.getConstant(4, MVT::i32), DAG);
10507     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10508     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10509
10510     // a += a
10511     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10512     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10513     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10514
10515     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10516     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10517     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10518                             DAG.getConstant(2, MVT::i32), DAG);
10519     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10520     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10521
10522     // a += a
10523     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10524     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10525     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10526
10527     // return VSELECT(r, r+r, a);
10528     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10529                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10530     return R;
10531   }
10532
10533   // Decompose 256-bit shifts into smaller 128-bit shifts.
10534   if (VT.is256BitVector()) {
10535     unsigned NumElems = VT.getVectorNumElements();
10536     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10537     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10538
10539     // Extract the two vectors
10540     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10541     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10542
10543     // Recreate the shift amount vectors
10544     SDValue Amt1, Amt2;
10545     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10546       // Constant shift amount
10547       SmallVector<SDValue, 4> Amt1Csts;
10548       SmallVector<SDValue, 4> Amt2Csts;
10549       for (unsigned i = 0; i != NumElems/2; ++i)
10550         Amt1Csts.push_back(Amt->getOperand(i));
10551       for (unsigned i = NumElems/2; i != NumElems; ++i)
10552         Amt2Csts.push_back(Amt->getOperand(i));
10553
10554       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10555                                  &Amt1Csts[0], NumElems/2);
10556       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10557                                  &Amt2Csts[0], NumElems/2);
10558     } else {
10559       // Variable shift amount
10560       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10561       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10562     }
10563
10564     // Issue new vector shifts for the smaller types
10565     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10566     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10567
10568     // Concatenate the result back
10569     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10570   }
10571
10572   return SDValue();
10573 }
10574
10575 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10576   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10577   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10578   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10579   // has only one use.
10580   SDNode *N = Op.getNode();
10581   SDValue LHS = N->getOperand(0);
10582   SDValue RHS = N->getOperand(1);
10583   unsigned BaseOp = 0;
10584   unsigned Cond = 0;
10585   DebugLoc DL = Op.getDebugLoc();
10586   switch (Op.getOpcode()) {
10587   default: llvm_unreachable("Unknown ovf instruction!");
10588   case ISD::SADDO:
10589     // A subtract of one will be selected as a INC. Note that INC doesn't
10590     // set CF, so we can't do this for UADDO.
10591     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10592       if (C->isOne()) {
10593         BaseOp = X86ISD::INC;
10594         Cond = X86::COND_O;
10595         break;
10596       }
10597     BaseOp = X86ISD::ADD;
10598     Cond = X86::COND_O;
10599     break;
10600   case ISD::UADDO:
10601     BaseOp = X86ISD::ADD;
10602     Cond = X86::COND_B;
10603     break;
10604   case ISD::SSUBO:
10605     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10606     // set CF, so we can't do this for USUBO.
10607     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10608       if (C->isOne()) {
10609         BaseOp = X86ISD::DEC;
10610         Cond = X86::COND_O;
10611         break;
10612       }
10613     BaseOp = X86ISD::SUB;
10614     Cond = X86::COND_O;
10615     break;
10616   case ISD::USUBO:
10617     BaseOp = X86ISD::SUB;
10618     Cond = X86::COND_B;
10619     break;
10620   case ISD::SMULO:
10621     BaseOp = X86ISD::SMUL;
10622     Cond = X86::COND_O;
10623     break;
10624   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10625     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10626                                  MVT::i32);
10627     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10628
10629     SDValue SetCC =
10630       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10631                   DAG.getConstant(X86::COND_O, MVT::i32),
10632                   SDValue(Sum.getNode(), 2));
10633
10634     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10635   }
10636   }
10637
10638   // Also sets EFLAGS.
10639   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10640   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10641
10642   SDValue SetCC =
10643     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10644                 DAG.getConstant(Cond, MVT::i32),
10645                 SDValue(Sum.getNode(), 1));
10646
10647   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10648 }
10649
10650 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10651                                                   SelectionDAG &DAG) const {
10652   DebugLoc dl = Op.getDebugLoc();
10653   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10654   EVT VT = Op.getValueType();
10655
10656   if (!Subtarget->hasSSE2() || !VT.isVector())
10657     return SDValue();
10658
10659   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10660                       ExtraVT.getScalarType().getSizeInBits();
10661   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10662
10663   switch (VT.getSimpleVT().SimpleTy) {
10664     default: return SDValue();
10665     case MVT::v8i32:
10666     case MVT::v16i16:
10667       if (!Subtarget->hasAVX())
10668         return SDValue();
10669       if (!Subtarget->hasAVX2()) {
10670         // needs to be split
10671         unsigned NumElems = VT.getVectorNumElements();
10672
10673         // Extract the LHS vectors
10674         SDValue LHS = Op.getOperand(0);
10675         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10676         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10677
10678         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10679         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10680
10681         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10682         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10683         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10684                                    ExtraNumElems/2);
10685         SDValue Extra = DAG.getValueType(ExtraVT);
10686
10687         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10688         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10689
10690         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10691       }
10692       // fall through
10693     case MVT::v4i32:
10694     case MVT::v8i16: {
10695       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10696                                          Op.getOperand(0), ShAmt, DAG);
10697       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10698     }
10699   }
10700 }
10701
10702
10703 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10704   DebugLoc dl = Op.getDebugLoc();
10705
10706   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10707   // There isn't any reason to disable it if the target processor supports it.
10708   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10709     SDValue Chain = Op.getOperand(0);
10710     SDValue Zero = DAG.getConstant(0, MVT::i32);
10711     SDValue Ops[] = {
10712       DAG.getRegister(X86::ESP, MVT::i32), // Base
10713       DAG.getTargetConstant(1, MVT::i8),   // Scale
10714       DAG.getRegister(0, MVT::i32),        // Index
10715       DAG.getTargetConstant(0, MVT::i32),  // Disp
10716       DAG.getRegister(0, MVT::i32),        // Segment.
10717       Zero,
10718       Chain
10719     };
10720     SDNode *Res =
10721       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10722                           array_lengthof(Ops));
10723     return SDValue(Res, 0);
10724   }
10725
10726   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10727   if (!isDev)
10728     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10729
10730   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10731   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10732   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10733   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10734
10735   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10736   if (!Op1 && !Op2 && !Op3 && Op4)
10737     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10738
10739   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10740   if (Op1 && !Op2 && !Op3 && !Op4)
10741     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10742
10743   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10744   //           (MFENCE)>;
10745   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10746 }
10747
10748 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10749                                              SelectionDAG &DAG) const {
10750   DebugLoc dl = Op.getDebugLoc();
10751   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10752     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10753   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10754     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10755
10756   // The only fence that needs an instruction is a sequentially-consistent
10757   // cross-thread fence.
10758   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10759     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10760     // no-sse2). There isn't any reason to disable it if the target processor
10761     // supports it.
10762     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10763       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10764
10765     SDValue Chain = Op.getOperand(0);
10766     SDValue Zero = DAG.getConstant(0, MVT::i32);
10767     SDValue Ops[] = {
10768       DAG.getRegister(X86::ESP, MVT::i32), // Base
10769       DAG.getTargetConstant(1, MVT::i8),   // Scale
10770       DAG.getRegister(0, MVT::i32),        // Index
10771       DAG.getTargetConstant(0, MVT::i32),  // Disp
10772       DAG.getRegister(0, MVT::i32),        // Segment.
10773       Zero,
10774       Chain
10775     };
10776     SDNode *Res =
10777       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10778                          array_lengthof(Ops));
10779     return SDValue(Res, 0);
10780   }
10781
10782   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10783   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10784 }
10785
10786
10787 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10788   EVT T = Op.getValueType();
10789   DebugLoc DL = Op.getDebugLoc();
10790   unsigned Reg = 0;
10791   unsigned size = 0;
10792   switch(T.getSimpleVT().SimpleTy) {
10793   default: llvm_unreachable("Invalid value type!");
10794   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10795   case MVT::i16: Reg = X86::AX;  size = 2; break;
10796   case MVT::i32: Reg = X86::EAX; size = 4; break;
10797   case MVT::i64:
10798     assert(Subtarget->is64Bit() && "Node not type legal!");
10799     Reg = X86::RAX; size = 8;
10800     break;
10801   }
10802   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10803                                     Op.getOperand(2), SDValue());
10804   SDValue Ops[] = { cpIn.getValue(0),
10805                     Op.getOperand(1),
10806                     Op.getOperand(3),
10807                     DAG.getTargetConstant(size, MVT::i8),
10808                     cpIn.getValue(1) };
10809   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10810   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10811   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10812                                            Ops, 5, T, MMO);
10813   SDValue cpOut =
10814     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10815   return cpOut;
10816 }
10817
10818 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10819                                                  SelectionDAG &DAG) const {
10820   assert(Subtarget->is64Bit() && "Result not type legalized?");
10821   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10822   SDValue TheChain = Op.getOperand(0);
10823   DebugLoc dl = Op.getDebugLoc();
10824   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10825   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10826   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10827                                    rax.getValue(2));
10828   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10829                             DAG.getConstant(32, MVT::i8));
10830   SDValue Ops[] = {
10831     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10832     rdx.getValue(1)
10833   };
10834   return DAG.getMergeValues(Ops, 2, dl);
10835 }
10836
10837 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10838                                             SelectionDAG &DAG) const {
10839   EVT SrcVT = Op.getOperand(0).getValueType();
10840   EVT DstVT = Op.getValueType();
10841   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10842          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10843   assert((DstVT == MVT::i64 ||
10844           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10845          "Unexpected custom BITCAST");
10846   // i64 <=> MMX conversions are Legal.
10847   if (SrcVT==MVT::i64 && DstVT.isVector())
10848     return Op;
10849   if (DstVT==MVT::i64 && SrcVT.isVector())
10850     return Op;
10851   // MMX <=> MMX conversions are Legal.
10852   if (SrcVT.isVector() && DstVT.isVector())
10853     return Op;
10854   // All other conversions need to be expanded.
10855   return SDValue();
10856 }
10857
10858 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10859   SDNode *Node = Op.getNode();
10860   DebugLoc dl = Node->getDebugLoc();
10861   EVT T = Node->getValueType(0);
10862   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10863                               DAG.getConstant(0, T), Node->getOperand(2));
10864   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10865                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10866                        Node->getOperand(0),
10867                        Node->getOperand(1), negOp,
10868                        cast<AtomicSDNode>(Node)->getSrcValue(),
10869                        cast<AtomicSDNode>(Node)->getAlignment(),
10870                        cast<AtomicSDNode>(Node)->getOrdering(),
10871                        cast<AtomicSDNode>(Node)->getSynchScope());
10872 }
10873
10874 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10875   SDNode *Node = Op.getNode();
10876   DebugLoc dl = Node->getDebugLoc();
10877   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10878
10879   // Convert seq_cst store -> xchg
10880   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10881   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10882   //        (The only way to get a 16-byte store is cmpxchg16b)
10883   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10884   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10885       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10886     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10887                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10888                                  Node->getOperand(0),
10889                                  Node->getOperand(1), Node->getOperand(2),
10890                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10891                                  cast<AtomicSDNode>(Node)->getOrdering(),
10892                                  cast<AtomicSDNode>(Node)->getSynchScope());
10893     return Swap.getValue(1);
10894   }
10895   // Other atomic stores have a simple pattern.
10896   return Op;
10897 }
10898
10899 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10900   EVT VT = Op.getNode()->getValueType(0);
10901
10902   // Let legalize expand this if it isn't a legal type yet.
10903   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10904     return SDValue();
10905
10906   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10907
10908   unsigned Opc;
10909   bool ExtraOp = false;
10910   switch (Op.getOpcode()) {
10911   default: llvm_unreachable("Invalid code");
10912   case ISD::ADDC: Opc = X86ISD::ADD; break;
10913   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10914   case ISD::SUBC: Opc = X86ISD::SUB; break;
10915   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10916   }
10917
10918   if (!ExtraOp)
10919     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10920                        Op.getOperand(1));
10921   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10922                      Op.getOperand(1), Op.getOperand(2));
10923 }
10924
10925 /// LowerOperation - Provide custom lowering hooks for some operations.
10926 ///
10927 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10928   switch (Op.getOpcode()) {
10929   default: llvm_unreachable("Should not custom lower this!");
10930   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10931   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10932   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10933   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10934   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10935   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10936   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10937   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10938   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10939   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10940   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10941   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10942   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10943   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10944   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10945   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10946   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10947   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10948   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10949   case ISD::SHL_PARTS:
10950   case ISD::SRA_PARTS:
10951   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10952   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10953   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10954   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10955   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10956   case ISD::FABS:               return LowerFABS(Op, DAG);
10957   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10958   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10959   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10960   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10961   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10962   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10963   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10964   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10965   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10966   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10967   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10968   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
10969   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10970   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10971   case ISD::FRAME_TO_ARGS_OFFSET:
10972                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10973   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10974   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10975   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10976   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10977   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10978   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10979   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
10980   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10981   case ISD::MUL:                return LowerMUL(Op, DAG);
10982   case ISD::SRA:
10983   case ISD::SRL:
10984   case ISD::SHL:                return LowerShift(Op, DAG);
10985   case ISD::SADDO:
10986   case ISD::UADDO:
10987   case ISD::SSUBO:
10988   case ISD::USUBO:
10989   case ISD::SMULO:
10990   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10991   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10992   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10993   case ISD::ADDC:
10994   case ISD::ADDE:
10995   case ISD::SUBC:
10996   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10997   case ISD::ADD:                return LowerADD(Op, DAG);
10998   case ISD::SUB:                return LowerSUB(Op, DAG);
10999   }
11000 }
11001
11002 static void ReplaceATOMIC_LOAD(SDNode *Node,
11003                                   SmallVectorImpl<SDValue> &Results,
11004                                   SelectionDAG &DAG) {
11005   DebugLoc dl = Node->getDebugLoc();
11006   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11007
11008   // Convert wide load -> cmpxchg8b/cmpxchg16b
11009   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11010   //        (The only way to get a 16-byte load is cmpxchg16b)
11011   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11012   SDValue Zero = DAG.getConstant(0, VT);
11013   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11014                                Node->getOperand(0),
11015                                Node->getOperand(1), Zero, Zero,
11016                                cast<AtomicSDNode>(Node)->getMemOperand(),
11017                                cast<AtomicSDNode>(Node)->getOrdering(),
11018                                cast<AtomicSDNode>(Node)->getSynchScope());
11019   Results.push_back(Swap.getValue(0));
11020   Results.push_back(Swap.getValue(1));
11021 }
11022
11023 void X86TargetLowering::
11024 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11025                         SelectionDAG &DAG, unsigned NewOp) const {
11026   DebugLoc dl = Node->getDebugLoc();
11027   assert (Node->getValueType(0) == MVT::i64 &&
11028           "Only know how to expand i64 atomics");
11029
11030   SDValue Chain = Node->getOperand(0);
11031   SDValue In1 = Node->getOperand(1);
11032   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11033                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11034   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11035                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11036   SDValue Ops[] = { Chain, In1, In2L, In2H };
11037   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11038   SDValue Result =
11039     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11040                             cast<MemSDNode>(Node)->getMemOperand());
11041   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11042   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11043   Results.push_back(Result.getValue(2));
11044 }
11045
11046 /// ReplaceNodeResults - Replace a node with an illegal result type
11047 /// with a new node built out of custom code.
11048 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11049                                            SmallVectorImpl<SDValue>&Results,
11050                                            SelectionDAG &DAG) const {
11051   DebugLoc dl = N->getDebugLoc();
11052   switch (N->getOpcode()) {
11053   default:
11054     llvm_unreachable("Do not know how to custom type legalize this operation!");
11055   case ISD::SIGN_EXTEND_INREG:
11056   case ISD::ADDC:
11057   case ISD::ADDE:
11058   case ISD::SUBC:
11059   case ISD::SUBE:
11060     // We don't want to expand or promote these.
11061     return;
11062   case ISD::FP_TO_SINT:
11063   case ISD::FP_TO_UINT: {
11064     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11065
11066     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11067       return;
11068
11069     std::pair<SDValue,SDValue> Vals =
11070         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11071     SDValue FIST = Vals.first, StackSlot = Vals.second;
11072     if (FIST.getNode() != 0) {
11073       EVT VT = N->getValueType(0);
11074       // Return a load from the stack slot.
11075       if (StackSlot.getNode() != 0)
11076         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11077                                       MachinePointerInfo(),
11078                                       false, false, false, 0));
11079       else
11080         Results.push_back(FIST);
11081     }
11082     return;
11083   }
11084   case ISD::READCYCLECOUNTER: {
11085     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11086     SDValue TheChain = N->getOperand(0);
11087     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11088     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11089                                      rd.getValue(1));
11090     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11091                                      eax.getValue(2));
11092     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11093     SDValue Ops[] = { eax, edx };
11094     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11095     Results.push_back(edx.getValue(1));
11096     return;
11097   }
11098   case ISD::ATOMIC_CMP_SWAP: {
11099     EVT T = N->getValueType(0);
11100     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11101     bool Regs64bit = T == MVT::i128;
11102     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11103     SDValue cpInL, cpInH;
11104     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11105                         DAG.getConstant(0, HalfT));
11106     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11107                         DAG.getConstant(1, HalfT));
11108     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11109                              Regs64bit ? X86::RAX : X86::EAX,
11110                              cpInL, SDValue());
11111     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11112                              Regs64bit ? X86::RDX : X86::EDX,
11113                              cpInH, cpInL.getValue(1));
11114     SDValue swapInL, swapInH;
11115     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11116                           DAG.getConstant(0, HalfT));
11117     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11118                           DAG.getConstant(1, HalfT));
11119     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11120                                Regs64bit ? X86::RBX : X86::EBX,
11121                                swapInL, cpInH.getValue(1));
11122     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11123                                Regs64bit ? X86::RCX : X86::ECX,
11124                                swapInH, swapInL.getValue(1));
11125     SDValue Ops[] = { swapInH.getValue(0),
11126                       N->getOperand(1),
11127                       swapInH.getValue(1) };
11128     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11129     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11130     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11131                                   X86ISD::LCMPXCHG8_DAG;
11132     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11133                                              Ops, 3, T, MMO);
11134     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11135                                         Regs64bit ? X86::RAX : X86::EAX,
11136                                         HalfT, Result.getValue(1));
11137     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11138                                         Regs64bit ? X86::RDX : X86::EDX,
11139                                         HalfT, cpOutL.getValue(2));
11140     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11141     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11142     Results.push_back(cpOutH.getValue(1));
11143     return;
11144   }
11145   case ISD::ATOMIC_LOAD_ADD:
11146     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11147     return;
11148   case ISD::ATOMIC_LOAD_AND:
11149     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11150     return;
11151   case ISD::ATOMIC_LOAD_NAND:
11152     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11153     return;
11154   case ISD::ATOMIC_LOAD_OR:
11155     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11156     return;
11157   case ISD::ATOMIC_LOAD_SUB:
11158     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11159     return;
11160   case ISD::ATOMIC_LOAD_XOR:
11161     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11162     return;
11163   case ISD::ATOMIC_SWAP:
11164     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11165     return;
11166   case ISD::ATOMIC_LOAD:
11167     ReplaceATOMIC_LOAD(N, Results, DAG);
11168   }
11169 }
11170
11171 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11172   switch (Opcode) {
11173   default: return NULL;
11174   case X86ISD::BSF:                return "X86ISD::BSF";
11175   case X86ISD::BSR:                return "X86ISD::BSR";
11176   case X86ISD::SHLD:               return "X86ISD::SHLD";
11177   case X86ISD::SHRD:               return "X86ISD::SHRD";
11178   case X86ISD::FAND:               return "X86ISD::FAND";
11179   case X86ISD::FOR:                return "X86ISD::FOR";
11180   case X86ISD::FXOR:               return "X86ISD::FXOR";
11181   case X86ISD::FSRL:               return "X86ISD::FSRL";
11182   case X86ISD::FILD:               return "X86ISD::FILD";
11183   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11184   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11185   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11186   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11187   case X86ISD::FLD:                return "X86ISD::FLD";
11188   case X86ISD::FST:                return "X86ISD::FST";
11189   case X86ISD::CALL:               return "X86ISD::CALL";
11190   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11191   case X86ISD::BT:                 return "X86ISD::BT";
11192   case X86ISD::CMP:                return "X86ISD::CMP";
11193   case X86ISD::COMI:               return "X86ISD::COMI";
11194   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11195   case X86ISD::SETCC:              return "X86ISD::SETCC";
11196   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11197   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11198   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11199   case X86ISD::CMOV:               return "X86ISD::CMOV";
11200   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11201   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11202   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11203   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11204   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11205   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11206   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11207   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11208   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11209   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11210   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11211   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11212   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11213   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11214   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11215   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11216   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11217   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11218   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11219   case X86ISD::HADD:               return "X86ISD::HADD";
11220   case X86ISD::HSUB:               return "X86ISD::HSUB";
11221   case X86ISD::FHADD:              return "X86ISD::FHADD";
11222   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11223   case X86ISD::FMAX:               return "X86ISD::FMAX";
11224   case X86ISD::FMIN:               return "X86ISD::FMIN";
11225   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11226   case X86ISD::FRCP:               return "X86ISD::FRCP";
11227   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11228   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11229   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11230   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11231   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11232   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11233   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11234   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11235   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11236   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11237   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11238   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11239   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11240   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11241   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11242   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11243   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11244   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11245   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11246   case X86ISD::VSHL:               return "X86ISD::VSHL";
11247   case X86ISD::VSRL:               return "X86ISD::VSRL";
11248   case X86ISD::VSRA:               return "X86ISD::VSRA";
11249   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11250   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11251   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11252   case X86ISD::CMPP:               return "X86ISD::CMPP";
11253   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11254   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11255   case X86ISD::ADD:                return "X86ISD::ADD";
11256   case X86ISD::SUB:                return "X86ISD::SUB";
11257   case X86ISD::ADC:                return "X86ISD::ADC";
11258   case X86ISD::SBB:                return "X86ISD::SBB";
11259   case X86ISD::SMUL:               return "X86ISD::SMUL";
11260   case X86ISD::UMUL:               return "X86ISD::UMUL";
11261   case X86ISD::INC:                return "X86ISD::INC";
11262   case X86ISD::DEC:                return "X86ISD::DEC";
11263   case X86ISD::OR:                 return "X86ISD::OR";
11264   case X86ISD::XOR:                return "X86ISD::XOR";
11265   case X86ISD::AND:                return "X86ISD::AND";
11266   case X86ISD::ANDN:               return "X86ISD::ANDN";
11267   case X86ISD::BLSI:               return "X86ISD::BLSI";
11268   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11269   case X86ISD::BLSR:               return "X86ISD::BLSR";
11270   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11271   case X86ISD::PTEST:              return "X86ISD::PTEST";
11272   case X86ISD::TESTP:              return "X86ISD::TESTP";
11273   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11274   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11275   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11276   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11277   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11278   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11279   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11280   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11281   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11282   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11283   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11284   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11285   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11286   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11287   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11288   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11289   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11290   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11291   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11292   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11293   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11294   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11295   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11296   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11297   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11298   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11299   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11300   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11301   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11302   case X86ISD::SAHF:               return "X86ISD::SAHF";
11303   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11304   case X86ISD::FMADD:              return "X86ISD::FMADD";
11305   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11306   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11307   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11308   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11309   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11310   }
11311 }
11312
11313 // isLegalAddressingMode - Return true if the addressing mode represented
11314 // by AM is legal for this target, for a load/store of the specified type.
11315 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11316                                               Type *Ty) const {
11317   // X86 supports extremely general addressing modes.
11318   CodeModel::Model M = getTargetMachine().getCodeModel();
11319   Reloc::Model R = getTargetMachine().getRelocationModel();
11320
11321   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11322   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11323     return false;
11324
11325   if (AM.BaseGV) {
11326     unsigned GVFlags =
11327       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11328
11329     // If a reference to this global requires an extra load, we can't fold it.
11330     if (isGlobalStubReference(GVFlags))
11331       return false;
11332
11333     // If BaseGV requires a register for the PIC base, we cannot also have a
11334     // BaseReg specified.
11335     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11336       return false;
11337
11338     // If lower 4G is not available, then we must use rip-relative addressing.
11339     if ((M != CodeModel::Small || R != Reloc::Static) &&
11340         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11341       return false;
11342   }
11343
11344   switch (AM.Scale) {
11345   case 0:
11346   case 1:
11347   case 2:
11348   case 4:
11349   case 8:
11350     // These scales always work.
11351     break;
11352   case 3:
11353   case 5:
11354   case 9:
11355     // These scales are formed with basereg+scalereg.  Only accept if there is
11356     // no basereg yet.
11357     if (AM.HasBaseReg)
11358       return false;
11359     break;
11360   default:  // Other stuff never works.
11361     return false;
11362   }
11363
11364   return true;
11365 }
11366
11367
11368 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11369   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11370     return false;
11371   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11372   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11373   if (NumBits1 <= NumBits2)
11374     return false;
11375   return true;
11376 }
11377
11378 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11379   return Imm == (int32_t)Imm;
11380 }
11381
11382 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11383   // Can also use sub to handle negated immediates.
11384   return Imm == (int32_t)Imm;
11385 }
11386
11387 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11388   if (!VT1.isInteger() || !VT2.isInteger())
11389     return false;
11390   unsigned NumBits1 = VT1.getSizeInBits();
11391   unsigned NumBits2 = VT2.getSizeInBits();
11392   if (NumBits1 <= NumBits2)
11393     return false;
11394   return true;
11395 }
11396
11397 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11398   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11399   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11400 }
11401
11402 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11403   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11404   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11405 }
11406
11407 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11408   // i16 instructions are longer (0x66 prefix) and potentially slower.
11409   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11410 }
11411
11412 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11413 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11414 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11415 /// are assumed to be legal.
11416 bool
11417 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11418                                       EVT VT) const {
11419   // Very little shuffling can be done for 64-bit vectors right now.
11420   if (VT.getSizeInBits() == 64)
11421     return false;
11422
11423   // FIXME: pshufb, blends, shifts.
11424   return (VT.getVectorNumElements() == 2 ||
11425           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11426           isMOVLMask(M, VT) ||
11427           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11428           isPSHUFDMask(M, VT) ||
11429           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11430           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11431           isPALIGNRMask(M, VT, Subtarget) ||
11432           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11433           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11434           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11435           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11436 }
11437
11438 bool
11439 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11440                                           EVT VT) const {
11441   unsigned NumElts = VT.getVectorNumElements();
11442   // FIXME: This collection of masks seems suspect.
11443   if (NumElts == 2)
11444     return true;
11445   if (NumElts == 4 && VT.is128BitVector()) {
11446     return (isMOVLMask(Mask, VT)  ||
11447             isCommutedMOVLMask(Mask, VT, true) ||
11448             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11449             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11450   }
11451   return false;
11452 }
11453
11454 //===----------------------------------------------------------------------===//
11455 //                           X86 Scheduler Hooks
11456 //===----------------------------------------------------------------------===//
11457
11458 // private utility function
11459 MachineBasicBlock *
11460 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11461                                                        MachineBasicBlock *MBB,
11462                                                        unsigned regOpc,
11463                                                        unsigned immOpc,
11464                                                        unsigned LoadOpc,
11465                                                        unsigned CXchgOpc,
11466                                                        unsigned notOpc,
11467                                                        unsigned EAXreg,
11468                                                  const TargetRegisterClass *RC,
11469                                                        bool Invert) const {
11470   // For the atomic bitwise operator, we generate
11471   //   thisMBB:
11472   //   newMBB:
11473   //     ld  t1 = [bitinstr.addr]
11474   //     op  t2 = t1, [bitinstr.val]
11475   //     not t3 = t2  (if Invert)
11476   //     mov EAX = t1
11477   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11478   //     bz  newMBB
11479   //     fallthrough -->nextMBB
11480   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11481   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11482   MachineFunction::iterator MBBIter = MBB;
11483   ++MBBIter;
11484
11485   /// First build the CFG
11486   MachineFunction *F = MBB->getParent();
11487   MachineBasicBlock *thisMBB = MBB;
11488   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11489   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11490   F->insert(MBBIter, newMBB);
11491   F->insert(MBBIter, nextMBB);
11492
11493   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11494   nextMBB->splice(nextMBB->begin(), thisMBB,
11495                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11496                   thisMBB->end());
11497   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11498
11499   // Update thisMBB to fall through to newMBB
11500   thisMBB->addSuccessor(newMBB);
11501
11502   // newMBB jumps to itself and fall through to nextMBB
11503   newMBB->addSuccessor(nextMBB);
11504   newMBB->addSuccessor(newMBB);
11505
11506   // Insert instructions into newMBB based on incoming instruction
11507   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11508          "unexpected number of operands");
11509   DebugLoc dl = bInstr->getDebugLoc();
11510   MachineOperand& destOper = bInstr->getOperand(0);
11511   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11512   int numArgs = bInstr->getNumOperands() - 1;
11513   for (int i=0; i < numArgs; ++i)
11514     argOpers[i] = &bInstr->getOperand(i+1);
11515
11516   // x86 address has 4 operands: base, index, scale, and displacement
11517   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11518   int valArgIndx = lastAddrIndx + 1;
11519
11520   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11521   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11522   for (int i=0; i <= lastAddrIndx; ++i)
11523     (*MIB).addOperand(*argOpers[i]);
11524
11525   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11526   assert((argOpers[valArgIndx]->isReg() ||
11527           argOpers[valArgIndx]->isImm()) &&
11528          "invalid operand");
11529   if (argOpers[valArgIndx]->isReg())
11530     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11531   else
11532     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11533   MIB.addReg(t1);
11534   (*MIB).addOperand(*argOpers[valArgIndx]);
11535
11536   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11537   if (Invert) {
11538     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11539   }
11540   else
11541     t3 = t2;
11542
11543   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11544   MIB.addReg(t1);
11545
11546   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11547   for (int i=0; i <= lastAddrIndx; ++i)
11548     (*MIB).addOperand(*argOpers[i]);
11549   MIB.addReg(t3);
11550   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11551   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11552                     bInstr->memoperands_end());
11553
11554   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11555   MIB.addReg(EAXreg);
11556
11557   // insert branch
11558   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11559
11560   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11561   return nextMBB;
11562 }
11563
11564 // private utility function:  64 bit atomics on 32 bit host.
11565 MachineBasicBlock *
11566 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11567                                                        MachineBasicBlock *MBB,
11568                                                        unsigned regOpcL,
11569                                                        unsigned regOpcH,
11570                                                        unsigned immOpcL,
11571                                                        unsigned immOpcH,
11572                                                        bool Invert) const {
11573   // For the atomic bitwise operator, we generate
11574   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11575   //     ld t1,t2 = [bitinstr.addr]
11576   //   newMBB:
11577   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11578   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11579   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11580   //     neg t7, t8 < t5, t6  (if Invert)
11581   //     mov ECX, EBX <- t5, t6
11582   //     mov EAX, EDX <- t1, t2
11583   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11584   //     mov t3, t4 <- EAX, EDX
11585   //     bz  newMBB
11586   //     result in out1, out2
11587   //     fallthrough -->nextMBB
11588
11589   const TargetRegisterClass *RC = &X86::GR32RegClass;
11590   const unsigned LoadOpc = X86::MOV32rm;
11591   const unsigned NotOpc = X86::NOT32r;
11592   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11593   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11594   MachineFunction::iterator MBBIter = MBB;
11595   ++MBBIter;
11596
11597   /// First build the CFG
11598   MachineFunction *F = MBB->getParent();
11599   MachineBasicBlock *thisMBB = MBB;
11600   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11601   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11602   F->insert(MBBIter, newMBB);
11603   F->insert(MBBIter, nextMBB);
11604
11605   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11606   nextMBB->splice(nextMBB->begin(), thisMBB,
11607                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11608                   thisMBB->end());
11609   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11610
11611   // Update thisMBB to fall through to newMBB
11612   thisMBB->addSuccessor(newMBB);
11613
11614   // newMBB jumps to itself and fall through to nextMBB
11615   newMBB->addSuccessor(nextMBB);
11616   newMBB->addSuccessor(newMBB);
11617
11618   DebugLoc dl = bInstr->getDebugLoc();
11619   // Insert instructions into newMBB based on incoming instruction
11620   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11621   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11622          "unexpected number of operands");
11623   MachineOperand& dest1Oper = bInstr->getOperand(0);
11624   MachineOperand& dest2Oper = bInstr->getOperand(1);
11625   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11626   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11627     argOpers[i] = &bInstr->getOperand(i+2);
11628
11629     // We use some of the operands multiple times, so conservatively just
11630     // clear any kill flags that might be present.
11631     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11632       argOpers[i]->setIsKill(false);
11633   }
11634
11635   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11636   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11637
11638   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11639   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11640   for (int i=0; i <= lastAddrIndx; ++i)
11641     (*MIB).addOperand(*argOpers[i]);
11642   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11643   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11644   // add 4 to displacement.
11645   for (int i=0; i <= lastAddrIndx-2; ++i)
11646     (*MIB).addOperand(*argOpers[i]);
11647   MachineOperand newOp3 = *(argOpers[3]);
11648   if (newOp3.isImm())
11649     newOp3.setImm(newOp3.getImm()+4);
11650   else
11651     newOp3.setOffset(newOp3.getOffset()+4);
11652   (*MIB).addOperand(newOp3);
11653   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11654
11655   // t3/4 are defined later, at the bottom of the loop
11656   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11657   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11658   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11659     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11660   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11661     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11662
11663   // The subsequent operations should be using the destination registers of
11664   // the PHI instructions.
11665   t1 = dest1Oper.getReg();
11666   t2 = dest2Oper.getReg();
11667
11668   int valArgIndx = lastAddrIndx + 1;
11669   assert((argOpers[valArgIndx]->isReg() ||
11670           argOpers[valArgIndx]->isImm()) &&
11671          "invalid operand");
11672   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11673   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11674   if (argOpers[valArgIndx]->isReg())
11675     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11676   else
11677     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11678   if (regOpcL != X86::MOV32rr)
11679     MIB.addReg(t1);
11680   (*MIB).addOperand(*argOpers[valArgIndx]);
11681   assert(argOpers[valArgIndx + 1]->isReg() ==
11682          argOpers[valArgIndx]->isReg());
11683   assert(argOpers[valArgIndx + 1]->isImm() ==
11684          argOpers[valArgIndx]->isImm());
11685   if (argOpers[valArgIndx + 1]->isReg())
11686     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11687   else
11688     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11689   if (regOpcH != X86::MOV32rr)
11690     MIB.addReg(t2);
11691   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11692
11693   unsigned t7, t8;
11694   if (Invert) {
11695     t7 = F->getRegInfo().createVirtualRegister(RC);
11696     t8 = F->getRegInfo().createVirtualRegister(RC);
11697     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11698     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11699   } else {
11700     t7 = t5;
11701     t8 = t6;
11702   }
11703
11704   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11705   MIB.addReg(t1);
11706   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11707   MIB.addReg(t2);
11708
11709   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11710   MIB.addReg(t7);
11711   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11712   MIB.addReg(t8);
11713
11714   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11715   for (int i=0; i <= lastAddrIndx; ++i)
11716     (*MIB).addOperand(*argOpers[i]);
11717
11718   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11719   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11720                     bInstr->memoperands_end());
11721
11722   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11723   MIB.addReg(X86::EAX);
11724   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11725   MIB.addReg(X86::EDX);
11726
11727   // insert branch
11728   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11729
11730   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11731   return nextMBB;
11732 }
11733
11734 // private utility function
11735 MachineBasicBlock *
11736 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11737                                                       MachineBasicBlock *MBB,
11738                                                       unsigned cmovOpc) const {
11739   // For the atomic min/max operator, we generate
11740   //   thisMBB:
11741   //   newMBB:
11742   //     ld t1 = [min/max.addr]
11743   //     mov t2 = [min/max.val]
11744   //     cmp  t1, t2
11745   //     cmov[cond] t2 = t1
11746   //     mov EAX = t1
11747   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11748   //     bz   newMBB
11749   //     fallthrough -->nextMBB
11750   //
11751   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11752   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11753   MachineFunction::iterator MBBIter = MBB;
11754   ++MBBIter;
11755
11756   /// First build the CFG
11757   MachineFunction *F = MBB->getParent();
11758   MachineBasicBlock *thisMBB = MBB;
11759   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11760   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11761   F->insert(MBBIter, newMBB);
11762   F->insert(MBBIter, nextMBB);
11763
11764   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11765   nextMBB->splice(nextMBB->begin(), thisMBB,
11766                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11767                   thisMBB->end());
11768   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11769
11770   // Update thisMBB to fall through to newMBB
11771   thisMBB->addSuccessor(newMBB);
11772
11773   // newMBB jumps to newMBB and fall through to nextMBB
11774   newMBB->addSuccessor(nextMBB);
11775   newMBB->addSuccessor(newMBB);
11776
11777   DebugLoc dl = mInstr->getDebugLoc();
11778   // Insert instructions into newMBB based on incoming instruction
11779   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11780          "unexpected number of operands");
11781   MachineOperand& destOper = mInstr->getOperand(0);
11782   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11783   int numArgs = mInstr->getNumOperands() - 1;
11784   for (int i=0; i < numArgs; ++i)
11785     argOpers[i] = &mInstr->getOperand(i+1);
11786
11787   // x86 address has 4 operands: base, index, scale, and displacement
11788   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11789   int valArgIndx = lastAddrIndx + 1;
11790
11791   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11792   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11793   for (int i=0; i <= lastAddrIndx; ++i)
11794     (*MIB).addOperand(*argOpers[i]);
11795
11796   // We only support register and immediate values
11797   assert((argOpers[valArgIndx]->isReg() ||
11798           argOpers[valArgIndx]->isImm()) &&
11799          "invalid operand");
11800
11801   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11802   if (argOpers[valArgIndx]->isReg())
11803     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11804   else
11805     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11806   (*MIB).addOperand(*argOpers[valArgIndx]);
11807
11808   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11809   MIB.addReg(t1);
11810
11811   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11812   MIB.addReg(t1);
11813   MIB.addReg(t2);
11814
11815   // Generate movc
11816   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11817   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11818   MIB.addReg(t2);
11819   MIB.addReg(t1);
11820
11821   // Cmp and exchange if none has modified the memory location
11822   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11823   for (int i=0; i <= lastAddrIndx; ++i)
11824     (*MIB).addOperand(*argOpers[i]);
11825   MIB.addReg(t3);
11826   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11827   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11828                     mInstr->memoperands_end());
11829
11830   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11831   MIB.addReg(X86::EAX);
11832
11833   // insert branch
11834   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11835
11836   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11837   return nextMBB;
11838 }
11839
11840 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11841 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11842 // in the .td file.
11843 MachineBasicBlock *
11844 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11845                             unsigned numArgs, bool memArg) const {
11846   assert(Subtarget->hasSSE42() &&
11847          "Target must have SSE4.2 or AVX features enabled");
11848
11849   DebugLoc dl = MI->getDebugLoc();
11850   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11851   unsigned Opc;
11852   if (!Subtarget->hasAVX()) {
11853     if (memArg)
11854       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11855     else
11856       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11857   } else {
11858     if (memArg)
11859       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11860     else
11861       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11862   }
11863
11864   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11865   for (unsigned i = 0; i < numArgs; ++i) {
11866     MachineOperand &Op = MI->getOperand(i+1);
11867     if (!(Op.isReg() && Op.isImplicit()))
11868       MIB.addOperand(Op);
11869   }
11870   BuildMI(*BB, MI, dl,
11871     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
11872     .addReg(X86::XMM0);
11873
11874   MI->eraseFromParent();
11875   return BB;
11876 }
11877
11878 MachineBasicBlock *
11879 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11880   DebugLoc dl = MI->getDebugLoc();
11881   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11882
11883   // Address into RAX/EAX, other two args into ECX, EDX.
11884   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11885   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11886   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11887   for (int i = 0; i < X86::AddrNumOperands; ++i)
11888     MIB.addOperand(MI->getOperand(i));
11889
11890   unsigned ValOps = X86::AddrNumOperands;
11891   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11892     .addReg(MI->getOperand(ValOps).getReg());
11893   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11894     .addReg(MI->getOperand(ValOps+1).getReg());
11895
11896   // The instruction doesn't actually take any operands though.
11897   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11898
11899   MI->eraseFromParent(); // The pseudo is gone now.
11900   return BB;
11901 }
11902
11903 MachineBasicBlock *
11904 X86TargetLowering::EmitVAARG64WithCustomInserter(
11905                    MachineInstr *MI,
11906                    MachineBasicBlock *MBB) const {
11907   // Emit va_arg instruction on X86-64.
11908
11909   // Operands to this pseudo-instruction:
11910   // 0  ) Output        : destination address (reg)
11911   // 1-5) Input         : va_list address (addr, i64mem)
11912   // 6  ) ArgSize       : Size (in bytes) of vararg type
11913   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11914   // 8  ) Align         : Alignment of type
11915   // 9  ) EFLAGS (implicit-def)
11916
11917   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11918   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11919
11920   unsigned DestReg = MI->getOperand(0).getReg();
11921   MachineOperand &Base = MI->getOperand(1);
11922   MachineOperand &Scale = MI->getOperand(2);
11923   MachineOperand &Index = MI->getOperand(3);
11924   MachineOperand &Disp = MI->getOperand(4);
11925   MachineOperand &Segment = MI->getOperand(5);
11926   unsigned ArgSize = MI->getOperand(6).getImm();
11927   unsigned ArgMode = MI->getOperand(7).getImm();
11928   unsigned Align = MI->getOperand(8).getImm();
11929
11930   // Memory Reference
11931   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11932   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11933   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11934
11935   // Machine Information
11936   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11937   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11938   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11939   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11940   DebugLoc DL = MI->getDebugLoc();
11941
11942   // struct va_list {
11943   //   i32   gp_offset
11944   //   i32   fp_offset
11945   //   i64   overflow_area (address)
11946   //   i64   reg_save_area (address)
11947   // }
11948   // sizeof(va_list) = 24
11949   // alignment(va_list) = 8
11950
11951   unsigned TotalNumIntRegs = 6;
11952   unsigned TotalNumXMMRegs = 8;
11953   bool UseGPOffset = (ArgMode == 1);
11954   bool UseFPOffset = (ArgMode == 2);
11955   unsigned MaxOffset = TotalNumIntRegs * 8 +
11956                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11957
11958   /* Align ArgSize to a multiple of 8 */
11959   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11960   bool NeedsAlign = (Align > 8);
11961
11962   MachineBasicBlock *thisMBB = MBB;
11963   MachineBasicBlock *overflowMBB;
11964   MachineBasicBlock *offsetMBB;
11965   MachineBasicBlock *endMBB;
11966
11967   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11968   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11969   unsigned OffsetReg = 0;
11970
11971   if (!UseGPOffset && !UseFPOffset) {
11972     // If we only pull from the overflow region, we don't create a branch.
11973     // We don't need to alter control flow.
11974     OffsetDestReg = 0; // unused
11975     OverflowDestReg = DestReg;
11976
11977     offsetMBB = NULL;
11978     overflowMBB = thisMBB;
11979     endMBB = thisMBB;
11980   } else {
11981     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11982     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11983     // If not, pull from overflow_area. (branch to overflowMBB)
11984     //
11985     //       thisMBB
11986     //         |     .
11987     //         |        .
11988     //     offsetMBB   overflowMBB
11989     //         |        .
11990     //         |     .
11991     //        endMBB
11992
11993     // Registers for the PHI in endMBB
11994     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11995     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11996
11997     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11998     MachineFunction *MF = MBB->getParent();
11999     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12000     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12001     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12002
12003     MachineFunction::iterator MBBIter = MBB;
12004     ++MBBIter;
12005
12006     // Insert the new basic blocks
12007     MF->insert(MBBIter, offsetMBB);
12008     MF->insert(MBBIter, overflowMBB);
12009     MF->insert(MBBIter, endMBB);
12010
12011     // Transfer the remainder of MBB and its successor edges to endMBB.
12012     endMBB->splice(endMBB->begin(), thisMBB,
12013                     llvm::next(MachineBasicBlock::iterator(MI)),
12014                     thisMBB->end());
12015     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12016
12017     // Make offsetMBB and overflowMBB successors of thisMBB
12018     thisMBB->addSuccessor(offsetMBB);
12019     thisMBB->addSuccessor(overflowMBB);
12020
12021     // endMBB is a successor of both offsetMBB and overflowMBB
12022     offsetMBB->addSuccessor(endMBB);
12023     overflowMBB->addSuccessor(endMBB);
12024
12025     // Load the offset value into a register
12026     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12027     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12028       .addOperand(Base)
12029       .addOperand(Scale)
12030       .addOperand(Index)
12031       .addDisp(Disp, UseFPOffset ? 4 : 0)
12032       .addOperand(Segment)
12033       .setMemRefs(MMOBegin, MMOEnd);
12034
12035     // Check if there is enough room left to pull this argument.
12036     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12037       .addReg(OffsetReg)
12038       .addImm(MaxOffset + 8 - ArgSizeA8);
12039
12040     // Branch to "overflowMBB" if offset >= max
12041     // Fall through to "offsetMBB" otherwise
12042     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12043       .addMBB(overflowMBB);
12044   }
12045
12046   // In offsetMBB, emit code to use the reg_save_area.
12047   if (offsetMBB) {
12048     assert(OffsetReg != 0);
12049
12050     // Read the reg_save_area address.
12051     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12052     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12053       .addOperand(Base)
12054       .addOperand(Scale)
12055       .addOperand(Index)
12056       .addDisp(Disp, 16)
12057       .addOperand(Segment)
12058       .setMemRefs(MMOBegin, MMOEnd);
12059
12060     // Zero-extend the offset
12061     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12062       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12063         .addImm(0)
12064         .addReg(OffsetReg)
12065         .addImm(X86::sub_32bit);
12066
12067     // Add the offset to the reg_save_area to get the final address.
12068     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12069       .addReg(OffsetReg64)
12070       .addReg(RegSaveReg);
12071
12072     // Compute the offset for the next argument
12073     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12074     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12075       .addReg(OffsetReg)
12076       .addImm(UseFPOffset ? 16 : 8);
12077
12078     // Store it back into the va_list.
12079     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12080       .addOperand(Base)
12081       .addOperand(Scale)
12082       .addOperand(Index)
12083       .addDisp(Disp, UseFPOffset ? 4 : 0)
12084       .addOperand(Segment)
12085       .addReg(NextOffsetReg)
12086       .setMemRefs(MMOBegin, MMOEnd);
12087
12088     // Jump to endMBB
12089     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12090       .addMBB(endMBB);
12091   }
12092
12093   //
12094   // Emit code to use overflow area
12095   //
12096
12097   // Load the overflow_area address into a register.
12098   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12099   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12100     .addOperand(Base)
12101     .addOperand(Scale)
12102     .addOperand(Index)
12103     .addDisp(Disp, 8)
12104     .addOperand(Segment)
12105     .setMemRefs(MMOBegin, MMOEnd);
12106
12107   // If we need to align it, do so. Otherwise, just copy the address
12108   // to OverflowDestReg.
12109   if (NeedsAlign) {
12110     // Align the overflow address
12111     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12112     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12113
12114     // aligned_addr = (addr + (align-1)) & ~(align-1)
12115     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12116       .addReg(OverflowAddrReg)
12117       .addImm(Align-1);
12118
12119     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12120       .addReg(TmpReg)
12121       .addImm(~(uint64_t)(Align-1));
12122   } else {
12123     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12124       .addReg(OverflowAddrReg);
12125   }
12126
12127   // Compute the next overflow address after this argument.
12128   // (the overflow address should be kept 8-byte aligned)
12129   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12130   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12131     .addReg(OverflowDestReg)
12132     .addImm(ArgSizeA8);
12133
12134   // Store the new overflow address.
12135   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12136     .addOperand(Base)
12137     .addOperand(Scale)
12138     .addOperand(Index)
12139     .addDisp(Disp, 8)
12140     .addOperand(Segment)
12141     .addReg(NextAddrReg)
12142     .setMemRefs(MMOBegin, MMOEnd);
12143
12144   // If we branched, emit the PHI to the front of endMBB.
12145   if (offsetMBB) {
12146     BuildMI(*endMBB, endMBB->begin(), DL,
12147             TII->get(X86::PHI), DestReg)
12148       .addReg(OffsetDestReg).addMBB(offsetMBB)
12149       .addReg(OverflowDestReg).addMBB(overflowMBB);
12150   }
12151
12152   // Erase the pseudo instruction
12153   MI->eraseFromParent();
12154
12155   return endMBB;
12156 }
12157
12158 MachineBasicBlock *
12159 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12160                                                  MachineInstr *MI,
12161                                                  MachineBasicBlock *MBB) const {
12162   // Emit code to save XMM registers to the stack. The ABI says that the
12163   // number of registers to save is given in %al, so it's theoretically
12164   // possible to do an indirect jump trick to avoid saving all of them,
12165   // however this code takes a simpler approach and just executes all
12166   // of the stores if %al is non-zero. It's less code, and it's probably
12167   // easier on the hardware branch predictor, and stores aren't all that
12168   // expensive anyway.
12169
12170   // Create the new basic blocks. One block contains all the XMM stores,
12171   // and one block is the final destination regardless of whether any
12172   // stores were performed.
12173   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12174   MachineFunction *F = MBB->getParent();
12175   MachineFunction::iterator MBBIter = MBB;
12176   ++MBBIter;
12177   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12178   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12179   F->insert(MBBIter, XMMSaveMBB);
12180   F->insert(MBBIter, EndMBB);
12181
12182   // Transfer the remainder of MBB and its successor edges to EndMBB.
12183   EndMBB->splice(EndMBB->begin(), MBB,
12184                  llvm::next(MachineBasicBlock::iterator(MI)),
12185                  MBB->end());
12186   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12187
12188   // The original block will now fall through to the XMM save block.
12189   MBB->addSuccessor(XMMSaveMBB);
12190   // The XMMSaveMBB will fall through to the end block.
12191   XMMSaveMBB->addSuccessor(EndMBB);
12192
12193   // Now add the instructions.
12194   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12195   DebugLoc DL = MI->getDebugLoc();
12196
12197   unsigned CountReg = MI->getOperand(0).getReg();
12198   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12199   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12200
12201   if (!Subtarget->isTargetWin64()) {
12202     // If %al is 0, branch around the XMM save block.
12203     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12204     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12205     MBB->addSuccessor(EndMBB);
12206   }
12207
12208   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12209   // In the XMM save block, save all the XMM argument registers.
12210   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12211     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12212     MachineMemOperand *MMO =
12213       F->getMachineMemOperand(
12214           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12215         MachineMemOperand::MOStore,
12216         /*Size=*/16, /*Align=*/16);
12217     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12218       .addFrameIndex(RegSaveFrameIndex)
12219       .addImm(/*Scale=*/1)
12220       .addReg(/*IndexReg=*/0)
12221       .addImm(/*Disp=*/Offset)
12222       .addReg(/*Segment=*/0)
12223       .addReg(MI->getOperand(i).getReg())
12224       .addMemOperand(MMO);
12225   }
12226
12227   MI->eraseFromParent();   // The pseudo instruction is gone now.
12228
12229   return EndMBB;
12230 }
12231
12232 // The EFLAGS operand of SelectItr might be missing a kill marker
12233 // because there were multiple uses of EFLAGS, and ISel didn't know
12234 // which to mark. Figure out whether SelectItr should have had a
12235 // kill marker, and set it if it should. Returns the correct kill
12236 // marker value.
12237 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12238                                      MachineBasicBlock* BB,
12239                                      const TargetRegisterInfo* TRI) {
12240   // Scan forward through BB for a use/def of EFLAGS.
12241   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12242   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12243     const MachineInstr& mi = *miI;
12244     if (mi.readsRegister(X86::EFLAGS))
12245       return false;
12246     if (mi.definesRegister(X86::EFLAGS))
12247       break; // Should have kill-flag - update below.
12248   }
12249
12250   // If we hit the end of the block, check whether EFLAGS is live into a
12251   // successor.
12252   if (miI == BB->end()) {
12253     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12254                                           sEnd = BB->succ_end();
12255          sItr != sEnd; ++sItr) {
12256       MachineBasicBlock* succ = *sItr;
12257       if (succ->isLiveIn(X86::EFLAGS))
12258         return false;
12259     }
12260   }
12261
12262   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12263   // out. SelectMI should have a kill flag on EFLAGS.
12264   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12265   return true;
12266 }
12267
12268 MachineBasicBlock *
12269 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12270                                      MachineBasicBlock *BB) const {
12271   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12272   DebugLoc DL = MI->getDebugLoc();
12273
12274   // To "insert" a SELECT_CC instruction, we actually have to insert the
12275   // diamond control-flow pattern.  The incoming instruction knows the
12276   // destination vreg to set, the condition code register to branch on, the
12277   // true/false values to select between, and a branch opcode to use.
12278   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12279   MachineFunction::iterator It = BB;
12280   ++It;
12281
12282   //  thisMBB:
12283   //  ...
12284   //   TrueVal = ...
12285   //   cmpTY ccX, r1, r2
12286   //   bCC copy1MBB
12287   //   fallthrough --> copy0MBB
12288   MachineBasicBlock *thisMBB = BB;
12289   MachineFunction *F = BB->getParent();
12290   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12291   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12292   F->insert(It, copy0MBB);
12293   F->insert(It, sinkMBB);
12294
12295   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12296   // live into the sink and copy blocks.
12297   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12298   if (!MI->killsRegister(X86::EFLAGS) &&
12299       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12300     copy0MBB->addLiveIn(X86::EFLAGS);
12301     sinkMBB->addLiveIn(X86::EFLAGS);
12302   }
12303
12304   // Transfer the remainder of BB and its successor edges to sinkMBB.
12305   sinkMBB->splice(sinkMBB->begin(), BB,
12306                   llvm::next(MachineBasicBlock::iterator(MI)),
12307                   BB->end());
12308   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12309
12310   // Add the true and fallthrough blocks as its successors.
12311   BB->addSuccessor(copy0MBB);
12312   BB->addSuccessor(sinkMBB);
12313
12314   // Create the conditional branch instruction.
12315   unsigned Opc =
12316     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12317   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12318
12319   //  copy0MBB:
12320   //   %FalseValue = ...
12321   //   # fallthrough to sinkMBB
12322   copy0MBB->addSuccessor(sinkMBB);
12323
12324   //  sinkMBB:
12325   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12326   //  ...
12327   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12328           TII->get(X86::PHI), MI->getOperand(0).getReg())
12329     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12330     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12331
12332   MI->eraseFromParent();   // The pseudo instruction is gone now.
12333   return sinkMBB;
12334 }
12335
12336 MachineBasicBlock *
12337 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12338                                         bool Is64Bit) const {
12339   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12340   DebugLoc DL = MI->getDebugLoc();
12341   MachineFunction *MF = BB->getParent();
12342   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12343
12344   assert(getTargetMachine().Options.EnableSegmentedStacks);
12345
12346   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12347   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12348
12349   // BB:
12350   //  ... [Till the alloca]
12351   // If stacklet is not large enough, jump to mallocMBB
12352   //
12353   // bumpMBB:
12354   //  Allocate by subtracting from RSP
12355   //  Jump to continueMBB
12356   //
12357   // mallocMBB:
12358   //  Allocate by call to runtime
12359   //
12360   // continueMBB:
12361   //  ...
12362   //  [rest of original BB]
12363   //
12364
12365   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12366   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12367   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12368
12369   MachineRegisterInfo &MRI = MF->getRegInfo();
12370   const TargetRegisterClass *AddrRegClass =
12371     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12372
12373   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12374     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12375     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12376     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12377     sizeVReg = MI->getOperand(1).getReg(),
12378     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12379
12380   MachineFunction::iterator MBBIter = BB;
12381   ++MBBIter;
12382
12383   MF->insert(MBBIter, bumpMBB);
12384   MF->insert(MBBIter, mallocMBB);
12385   MF->insert(MBBIter, continueMBB);
12386
12387   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12388                       (MachineBasicBlock::iterator(MI)), BB->end());
12389   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12390
12391   // Add code to the main basic block to check if the stack limit has been hit,
12392   // and if so, jump to mallocMBB otherwise to bumpMBB.
12393   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12394   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12395     .addReg(tmpSPVReg).addReg(sizeVReg);
12396   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12397     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12398     .addReg(SPLimitVReg);
12399   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12400
12401   // bumpMBB simply decreases the stack pointer, since we know the current
12402   // stacklet has enough space.
12403   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12404     .addReg(SPLimitVReg);
12405   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12406     .addReg(SPLimitVReg);
12407   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12408
12409   // Calls into a routine in libgcc to allocate more space from the heap.
12410   const uint32_t *RegMask =
12411     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12412   if (Is64Bit) {
12413     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12414       .addReg(sizeVReg);
12415     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12416       .addExternalSymbol("__morestack_allocate_stack_space")
12417       .addRegMask(RegMask)
12418       .addReg(X86::RDI, RegState::Implicit)
12419       .addReg(X86::RAX, RegState::ImplicitDefine);
12420   } else {
12421     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12422       .addImm(12);
12423     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12424     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12425       .addExternalSymbol("__morestack_allocate_stack_space")
12426       .addRegMask(RegMask)
12427       .addReg(X86::EAX, RegState::ImplicitDefine);
12428   }
12429
12430   if (!Is64Bit)
12431     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12432       .addImm(16);
12433
12434   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12435     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12436   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12437
12438   // Set up the CFG correctly.
12439   BB->addSuccessor(bumpMBB);
12440   BB->addSuccessor(mallocMBB);
12441   mallocMBB->addSuccessor(continueMBB);
12442   bumpMBB->addSuccessor(continueMBB);
12443
12444   // Take care of the PHI nodes.
12445   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12446           MI->getOperand(0).getReg())
12447     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12448     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12449
12450   // Delete the original pseudo instruction.
12451   MI->eraseFromParent();
12452
12453   // And we're done.
12454   return continueMBB;
12455 }
12456
12457 MachineBasicBlock *
12458 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12459                                           MachineBasicBlock *BB) const {
12460   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12461   DebugLoc DL = MI->getDebugLoc();
12462
12463   assert(!Subtarget->isTargetEnvMacho());
12464
12465   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12466   // non-trivial part is impdef of ESP.
12467
12468   if (Subtarget->isTargetWin64()) {
12469     if (Subtarget->isTargetCygMing()) {
12470       // ___chkstk(Mingw64):
12471       // Clobbers R10, R11, RAX and EFLAGS.
12472       // Updates RSP.
12473       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12474         .addExternalSymbol("___chkstk")
12475         .addReg(X86::RAX, RegState::Implicit)
12476         .addReg(X86::RSP, RegState::Implicit)
12477         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12478         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12479         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12480     } else {
12481       // __chkstk(MSVCRT): does not update stack pointer.
12482       // Clobbers R10, R11 and EFLAGS.
12483       // FIXME: RAX(allocated size) might be reused and not killed.
12484       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12485         .addExternalSymbol("__chkstk")
12486         .addReg(X86::RAX, RegState::Implicit)
12487         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12488       // RAX has the offset to subtracted from RSP.
12489       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12490         .addReg(X86::RSP)
12491         .addReg(X86::RAX);
12492     }
12493   } else {
12494     const char *StackProbeSymbol =
12495       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12496
12497     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12498       .addExternalSymbol(StackProbeSymbol)
12499       .addReg(X86::EAX, RegState::Implicit)
12500       .addReg(X86::ESP, RegState::Implicit)
12501       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12502       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12503       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12504   }
12505
12506   MI->eraseFromParent();   // The pseudo instruction is gone now.
12507   return BB;
12508 }
12509
12510 MachineBasicBlock *
12511 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12512                                       MachineBasicBlock *BB) const {
12513   // This is pretty easy.  We're taking the value that we received from
12514   // our load from the relocation, sticking it in either RDI (x86-64)
12515   // or EAX and doing an indirect call.  The return value will then
12516   // be in the normal return register.
12517   const X86InstrInfo *TII
12518     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12519   DebugLoc DL = MI->getDebugLoc();
12520   MachineFunction *F = BB->getParent();
12521
12522   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12523   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12524
12525   // Get a register mask for the lowered call.
12526   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12527   // proper register mask.
12528   const uint32_t *RegMask =
12529     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12530   if (Subtarget->is64Bit()) {
12531     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12532                                       TII->get(X86::MOV64rm), X86::RDI)
12533     .addReg(X86::RIP)
12534     .addImm(0).addReg(0)
12535     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12536                       MI->getOperand(3).getTargetFlags())
12537     .addReg(0);
12538     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12539     addDirectMem(MIB, X86::RDI);
12540     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12541   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12542     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12543                                       TII->get(X86::MOV32rm), X86::EAX)
12544     .addReg(0)
12545     .addImm(0).addReg(0)
12546     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12547                       MI->getOperand(3).getTargetFlags())
12548     .addReg(0);
12549     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12550     addDirectMem(MIB, X86::EAX);
12551     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12552   } else {
12553     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12554                                       TII->get(X86::MOV32rm), X86::EAX)
12555     .addReg(TII->getGlobalBaseReg(F))
12556     .addImm(0).addReg(0)
12557     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12558                       MI->getOperand(3).getTargetFlags())
12559     .addReg(0);
12560     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12561     addDirectMem(MIB, X86::EAX);
12562     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12563   }
12564
12565   MI->eraseFromParent(); // The pseudo instruction is gone now.
12566   return BB;
12567 }
12568
12569 MachineBasicBlock *
12570 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12571                                                MachineBasicBlock *BB) const {
12572   switch (MI->getOpcode()) {
12573   default: llvm_unreachable("Unexpected instr type to insert");
12574   case X86::TAILJMPd64:
12575   case X86::TAILJMPr64:
12576   case X86::TAILJMPm64:
12577     llvm_unreachable("TAILJMP64 would not be touched here.");
12578   case X86::TCRETURNdi64:
12579   case X86::TCRETURNri64:
12580   case X86::TCRETURNmi64:
12581     return BB;
12582   case X86::WIN_ALLOCA:
12583     return EmitLoweredWinAlloca(MI, BB);
12584   case X86::SEG_ALLOCA_32:
12585     return EmitLoweredSegAlloca(MI, BB, false);
12586   case X86::SEG_ALLOCA_64:
12587     return EmitLoweredSegAlloca(MI, BB, true);
12588   case X86::TLSCall_32:
12589   case X86::TLSCall_64:
12590     return EmitLoweredTLSCall(MI, BB);
12591   case X86::CMOV_GR8:
12592   case X86::CMOV_FR32:
12593   case X86::CMOV_FR64:
12594   case X86::CMOV_V4F32:
12595   case X86::CMOV_V2F64:
12596   case X86::CMOV_V2I64:
12597   case X86::CMOV_V8F32:
12598   case X86::CMOV_V4F64:
12599   case X86::CMOV_V4I64:
12600   case X86::CMOV_GR16:
12601   case X86::CMOV_GR32:
12602   case X86::CMOV_RFP32:
12603   case X86::CMOV_RFP64:
12604   case X86::CMOV_RFP80:
12605     return EmitLoweredSelect(MI, BB);
12606
12607   case X86::FP32_TO_INT16_IN_MEM:
12608   case X86::FP32_TO_INT32_IN_MEM:
12609   case X86::FP32_TO_INT64_IN_MEM:
12610   case X86::FP64_TO_INT16_IN_MEM:
12611   case X86::FP64_TO_INT32_IN_MEM:
12612   case X86::FP64_TO_INT64_IN_MEM:
12613   case X86::FP80_TO_INT16_IN_MEM:
12614   case X86::FP80_TO_INT32_IN_MEM:
12615   case X86::FP80_TO_INT64_IN_MEM: {
12616     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12617     DebugLoc DL = MI->getDebugLoc();
12618
12619     // Change the floating point control register to use "round towards zero"
12620     // mode when truncating to an integer value.
12621     MachineFunction *F = BB->getParent();
12622     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12623     addFrameReference(BuildMI(*BB, MI, DL,
12624                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12625
12626     // Load the old value of the high byte of the control word...
12627     unsigned OldCW =
12628       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12629     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12630                       CWFrameIdx);
12631
12632     // Set the high part to be round to zero...
12633     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12634       .addImm(0xC7F);
12635
12636     // Reload the modified control word now...
12637     addFrameReference(BuildMI(*BB, MI, DL,
12638                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12639
12640     // Restore the memory image of control word to original value
12641     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12642       .addReg(OldCW);
12643
12644     // Get the X86 opcode to use.
12645     unsigned Opc;
12646     switch (MI->getOpcode()) {
12647     default: llvm_unreachable("illegal opcode!");
12648     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12649     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12650     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12651     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12652     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12653     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12654     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12655     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12656     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12657     }
12658
12659     X86AddressMode AM;
12660     MachineOperand &Op = MI->getOperand(0);
12661     if (Op.isReg()) {
12662       AM.BaseType = X86AddressMode::RegBase;
12663       AM.Base.Reg = Op.getReg();
12664     } else {
12665       AM.BaseType = X86AddressMode::FrameIndexBase;
12666       AM.Base.FrameIndex = Op.getIndex();
12667     }
12668     Op = MI->getOperand(1);
12669     if (Op.isImm())
12670       AM.Scale = Op.getImm();
12671     Op = MI->getOperand(2);
12672     if (Op.isImm())
12673       AM.IndexReg = Op.getImm();
12674     Op = MI->getOperand(3);
12675     if (Op.isGlobal()) {
12676       AM.GV = Op.getGlobal();
12677     } else {
12678       AM.Disp = Op.getImm();
12679     }
12680     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12681                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12682
12683     // Reload the original control word now.
12684     addFrameReference(BuildMI(*BB, MI, DL,
12685                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12686
12687     MI->eraseFromParent();   // The pseudo instruction is gone now.
12688     return BB;
12689   }
12690     // String/text processing lowering.
12691   case X86::PCMPISTRM128REG:
12692   case X86::VPCMPISTRM128REG:
12693     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12694   case X86::PCMPISTRM128MEM:
12695   case X86::VPCMPISTRM128MEM:
12696     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12697   case X86::PCMPESTRM128REG:
12698   case X86::VPCMPESTRM128REG:
12699     return EmitPCMP(MI, BB, 5, false /* in mem */);
12700   case X86::PCMPESTRM128MEM:
12701   case X86::VPCMPESTRM128MEM:
12702     return EmitPCMP(MI, BB, 5, true /* in mem */);
12703
12704     // Thread synchronization.
12705   case X86::MONITOR:
12706     return EmitMonitor(MI, BB);
12707
12708     // Atomic Lowering.
12709   case X86::ATOMAND32:
12710     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12711                                                X86::AND32ri, X86::MOV32rm,
12712                                                X86::LCMPXCHG32,
12713                                                X86::NOT32r, X86::EAX,
12714                                                &X86::GR32RegClass);
12715   case X86::ATOMOR32:
12716     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12717                                                X86::OR32ri, X86::MOV32rm,
12718                                                X86::LCMPXCHG32,
12719                                                X86::NOT32r, X86::EAX,
12720                                                &X86::GR32RegClass);
12721   case X86::ATOMXOR32:
12722     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12723                                                X86::XOR32ri, X86::MOV32rm,
12724                                                X86::LCMPXCHG32,
12725                                                X86::NOT32r, X86::EAX,
12726                                                &X86::GR32RegClass);
12727   case X86::ATOMNAND32:
12728     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12729                                                X86::AND32ri, X86::MOV32rm,
12730                                                X86::LCMPXCHG32,
12731                                                X86::NOT32r, X86::EAX,
12732                                                &X86::GR32RegClass, true);
12733   case X86::ATOMMIN32:
12734     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12735   case X86::ATOMMAX32:
12736     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12737   case X86::ATOMUMIN32:
12738     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12739   case X86::ATOMUMAX32:
12740     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12741
12742   case X86::ATOMAND16:
12743     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12744                                                X86::AND16ri, X86::MOV16rm,
12745                                                X86::LCMPXCHG16,
12746                                                X86::NOT16r, X86::AX,
12747                                                &X86::GR16RegClass);
12748   case X86::ATOMOR16:
12749     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12750                                                X86::OR16ri, X86::MOV16rm,
12751                                                X86::LCMPXCHG16,
12752                                                X86::NOT16r, X86::AX,
12753                                                &X86::GR16RegClass);
12754   case X86::ATOMXOR16:
12755     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12756                                                X86::XOR16ri, X86::MOV16rm,
12757                                                X86::LCMPXCHG16,
12758                                                X86::NOT16r, X86::AX,
12759                                                &X86::GR16RegClass);
12760   case X86::ATOMNAND16:
12761     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12762                                                X86::AND16ri, X86::MOV16rm,
12763                                                X86::LCMPXCHG16,
12764                                                X86::NOT16r, X86::AX,
12765                                                &X86::GR16RegClass, true);
12766   case X86::ATOMMIN16:
12767     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12768   case X86::ATOMMAX16:
12769     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12770   case X86::ATOMUMIN16:
12771     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12772   case X86::ATOMUMAX16:
12773     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12774
12775   case X86::ATOMAND8:
12776     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12777                                                X86::AND8ri, X86::MOV8rm,
12778                                                X86::LCMPXCHG8,
12779                                                X86::NOT8r, X86::AL,
12780                                                &X86::GR8RegClass);
12781   case X86::ATOMOR8:
12782     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12783                                                X86::OR8ri, X86::MOV8rm,
12784                                                X86::LCMPXCHG8,
12785                                                X86::NOT8r, X86::AL,
12786                                                &X86::GR8RegClass);
12787   case X86::ATOMXOR8:
12788     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12789                                                X86::XOR8ri, X86::MOV8rm,
12790                                                X86::LCMPXCHG8,
12791                                                X86::NOT8r, X86::AL,
12792                                                &X86::GR8RegClass);
12793   case X86::ATOMNAND8:
12794     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12795                                                X86::AND8ri, X86::MOV8rm,
12796                                                X86::LCMPXCHG8,
12797                                                X86::NOT8r, X86::AL,
12798                                                &X86::GR8RegClass, true);
12799   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12800   // This group is for 64-bit host.
12801   case X86::ATOMAND64:
12802     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12803                                                X86::AND64ri32, X86::MOV64rm,
12804                                                X86::LCMPXCHG64,
12805                                                X86::NOT64r, X86::RAX,
12806                                                &X86::GR64RegClass);
12807   case X86::ATOMOR64:
12808     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12809                                                X86::OR64ri32, X86::MOV64rm,
12810                                                X86::LCMPXCHG64,
12811                                                X86::NOT64r, X86::RAX,
12812                                                &X86::GR64RegClass);
12813   case X86::ATOMXOR64:
12814     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12815                                                X86::XOR64ri32, X86::MOV64rm,
12816                                                X86::LCMPXCHG64,
12817                                                X86::NOT64r, X86::RAX,
12818                                                &X86::GR64RegClass);
12819   case X86::ATOMNAND64:
12820     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12821                                                X86::AND64ri32, X86::MOV64rm,
12822                                                X86::LCMPXCHG64,
12823                                                X86::NOT64r, X86::RAX,
12824                                                &X86::GR64RegClass, true);
12825   case X86::ATOMMIN64:
12826     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12827   case X86::ATOMMAX64:
12828     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12829   case X86::ATOMUMIN64:
12830     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12831   case X86::ATOMUMAX64:
12832     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12833
12834   // This group does 64-bit operations on a 32-bit host.
12835   case X86::ATOMAND6432:
12836     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12837                                                X86::AND32rr, X86::AND32rr,
12838                                                X86::AND32ri, X86::AND32ri,
12839                                                false);
12840   case X86::ATOMOR6432:
12841     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12842                                                X86::OR32rr, X86::OR32rr,
12843                                                X86::OR32ri, X86::OR32ri,
12844                                                false);
12845   case X86::ATOMXOR6432:
12846     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12847                                                X86::XOR32rr, X86::XOR32rr,
12848                                                X86::XOR32ri, X86::XOR32ri,
12849                                                false);
12850   case X86::ATOMNAND6432:
12851     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12852                                                X86::AND32rr, X86::AND32rr,
12853                                                X86::AND32ri, X86::AND32ri,
12854                                                true);
12855   case X86::ATOMADD6432:
12856     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12857                                                X86::ADD32rr, X86::ADC32rr,
12858                                                X86::ADD32ri, X86::ADC32ri,
12859                                                false);
12860   case X86::ATOMSUB6432:
12861     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12862                                                X86::SUB32rr, X86::SBB32rr,
12863                                                X86::SUB32ri, X86::SBB32ri,
12864                                                false);
12865   case X86::ATOMSWAP6432:
12866     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12867                                                X86::MOV32rr, X86::MOV32rr,
12868                                                X86::MOV32ri, X86::MOV32ri,
12869                                                false);
12870   case X86::VASTART_SAVE_XMM_REGS:
12871     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12872
12873   case X86::VAARG_64:
12874     return EmitVAARG64WithCustomInserter(MI, BB);
12875   }
12876 }
12877
12878 //===----------------------------------------------------------------------===//
12879 //                           X86 Optimization Hooks
12880 //===----------------------------------------------------------------------===//
12881
12882 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12883                                                        APInt &KnownZero,
12884                                                        APInt &KnownOne,
12885                                                        const SelectionDAG &DAG,
12886                                                        unsigned Depth) const {
12887   unsigned BitWidth = KnownZero.getBitWidth();
12888   unsigned Opc = Op.getOpcode();
12889   assert((Opc >= ISD::BUILTIN_OP_END ||
12890           Opc == ISD::INTRINSIC_WO_CHAIN ||
12891           Opc == ISD::INTRINSIC_W_CHAIN ||
12892           Opc == ISD::INTRINSIC_VOID) &&
12893          "Should use MaskedValueIsZero if you don't know whether Op"
12894          " is a target node!");
12895
12896   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
12897   switch (Opc) {
12898   default: break;
12899   case X86ISD::ADD:
12900   case X86ISD::SUB:
12901   case X86ISD::ADC:
12902   case X86ISD::SBB:
12903   case X86ISD::SMUL:
12904   case X86ISD::UMUL:
12905   case X86ISD::INC:
12906   case X86ISD::DEC:
12907   case X86ISD::OR:
12908   case X86ISD::XOR:
12909   case X86ISD::AND:
12910     // These nodes' second result is a boolean.
12911     if (Op.getResNo() == 0)
12912       break;
12913     // Fallthrough
12914   case X86ISD::SETCC:
12915     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12916     break;
12917   case ISD::INTRINSIC_WO_CHAIN: {
12918     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12919     unsigned NumLoBits = 0;
12920     switch (IntId) {
12921     default: break;
12922     case Intrinsic::x86_sse_movmsk_ps:
12923     case Intrinsic::x86_avx_movmsk_ps_256:
12924     case Intrinsic::x86_sse2_movmsk_pd:
12925     case Intrinsic::x86_avx_movmsk_pd_256:
12926     case Intrinsic::x86_mmx_pmovmskb:
12927     case Intrinsic::x86_sse2_pmovmskb_128:
12928     case Intrinsic::x86_avx2_pmovmskb: {
12929       // High bits of movmskp{s|d}, pmovmskb are known zero.
12930       switch (IntId) {
12931         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12932         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12933         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12934         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12935         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12936         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12937         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12938         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
12939       }
12940       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
12941       break;
12942     }
12943     }
12944     break;
12945   }
12946   }
12947 }
12948
12949 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12950                                                          unsigned Depth) const {
12951   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12952   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12953     return Op.getValueType().getScalarType().getSizeInBits();
12954
12955   // Fallback case.
12956   return 1;
12957 }
12958
12959 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12960 /// node is a GlobalAddress + offset.
12961 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12962                                        const GlobalValue* &GA,
12963                                        int64_t &Offset) const {
12964   if (N->getOpcode() == X86ISD::Wrapper) {
12965     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12966       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12967       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12968       return true;
12969     }
12970   }
12971   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12972 }
12973
12974 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12975 /// same as extracting the high 128-bit part of 256-bit vector and then
12976 /// inserting the result into the low part of a new 256-bit vector
12977 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12978   EVT VT = SVOp->getValueType(0);
12979   unsigned NumElems = VT.getVectorNumElements();
12980
12981   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12982   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
12983     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12984         SVOp->getMaskElt(j) >= 0)
12985       return false;
12986
12987   return true;
12988 }
12989
12990 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12991 /// same as extracting the low 128-bit part of 256-bit vector and then
12992 /// inserting the result into the high part of a new 256-bit vector
12993 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12994   EVT VT = SVOp->getValueType(0);
12995   unsigned NumElems = VT.getVectorNumElements();
12996
12997   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12998   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
12999     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13000         SVOp->getMaskElt(j) >= 0)
13001       return false;
13002
13003   return true;
13004 }
13005
13006 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13007 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13008                                         TargetLowering::DAGCombinerInfo &DCI,
13009                                         const X86Subtarget* Subtarget) {
13010   DebugLoc dl = N->getDebugLoc();
13011   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13012   SDValue V1 = SVOp->getOperand(0);
13013   SDValue V2 = SVOp->getOperand(1);
13014   EVT VT = SVOp->getValueType(0);
13015   unsigned NumElems = VT.getVectorNumElements();
13016
13017   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13018       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13019     //
13020     //                   0,0,0,...
13021     //                      |
13022     //    V      UNDEF    BUILD_VECTOR    UNDEF
13023     //     \      /           \           /
13024     //  CONCAT_VECTOR         CONCAT_VECTOR
13025     //         \                  /
13026     //          \                /
13027     //          RESULT: V + zero extended
13028     //
13029     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13030         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13031         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13032       return SDValue();
13033
13034     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13035       return SDValue();
13036
13037     // To match the shuffle mask, the first half of the mask should
13038     // be exactly the first vector, and all the rest a splat with the
13039     // first element of the second one.
13040     for (unsigned i = 0; i != NumElems/2; ++i)
13041       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13042           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13043         return SDValue();
13044
13045     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13046     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13047       if (Ld->hasNUsesOfValue(1, 0)) {
13048         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13049         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13050         SDValue ResNode =
13051           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13052                                   Ld->getMemoryVT(),
13053                                   Ld->getPointerInfo(),
13054                                   Ld->getAlignment(),
13055                                   false/*isVolatile*/, true/*ReadMem*/,
13056                                   false/*WriteMem*/);
13057         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13058       }
13059     }
13060
13061     // Emit a zeroed vector and insert the desired subvector on its
13062     // first half.
13063     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13064     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13065     return DCI.CombineTo(N, InsV);
13066   }
13067
13068   //===--------------------------------------------------------------------===//
13069   // Combine some shuffles into subvector extracts and inserts:
13070   //
13071
13072   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13073   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13074     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13075     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13076     return DCI.CombineTo(N, InsV);
13077   }
13078
13079   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13080   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13081     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13082     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13083     return DCI.CombineTo(N, InsV);
13084   }
13085
13086   return SDValue();
13087 }
13088
13089 /// PerformShuffleCombine - Performs several different shuffle combines.
13090 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13091                                      TargetLowering::DAGCombinerInfo &DCI,
13092                                      const X86Subtarget *Subtarget) {
13093   DebugLoc dl = N->getDebugLoc();
13094   EVT VT = N->getValueType(0);
13095
13096   // Don't create instructions with illegal types after legalize types has run.
13097   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13098   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13099     return SDValue();
13100
13101   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13102   if (Subtarget->hasAVX() && VT.is256BitVector() &&
13103       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13104     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13105
13106   // Only handle 128 wide vector from here on.
13107   if (!VT.is128BitVector())
13108     return SDValue();
13109
13110   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13111   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13112   // consecutive, non-overlapping, and in the right order.
13113   SmallVector<SDValue, 16> Elts;
13114   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13115     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13116
13117   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13118 }
13119
13120
13121 /// DCI, PerformTruncateCombine - Converts truncate operation to
13122 /// a sequence of vector shuffle operations.
13123 /// It is possible when we truncate 256-bit vector to 128-bit vector
13124
13125 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13126                                                   DAGCombinerInfo &DCI) const {
13127   if (!DCI.isBeforeLegalizeOps())
13128     return SDValue();
13129
13130   if (!Subtarget->hasAVX())
13131     return SDValue();
13132
13133   EVT VT = N->getValueType(0);
13134   SDValue Op = N->getOperand(0);
13135   EVT OpVT = Op.getValueType();
13136   DebugLoc dl = N->getDebugLoc();
13137
13138   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13139
13140     if (Subtarget->hasAVX2()) {
13141       // AVX2: v4i64 -> v4i32
13142
13143       // VPERMD
13144       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13145
13146       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13147       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13148                                 ShufMask);
13149
13150       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13151                          DAG.getIntPtrConstant(0));
13152     }
13153
13154     // AVX: v4i64 -> v4i32
13155     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13156                                DAG.getIntPtrConstant(0));
13157
13158     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13159                                DAG.getIntPtrConstant(2));
13160
13161     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13162     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13163
13164     // PSHUFD
13165     static const int ShufMask1[] = {0, 2, 0, 0};
13166
13167     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13168     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13169
13170     // MOVLHPS
13171     static const int ShufMask2[] = {0, 1, 4, 5};
13172
13173     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13174   }
13175
13176   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13177
13178     if (Subtarget->hasAVX2()) {
13179       // AVX2: v8i32 -> v8i16
13180
13181       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13182
13183       // PSHUFB
13184       SmallVector<SDValue,32> pshufbMask;
13185       for (unsigned i = 0; i < 2; ++i) {
13186         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13187         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13188         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13189         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13190         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13191         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13192         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13193         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13194         for (unsigned j = 0; j < 8; ++j)
13195           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13196       }
13197       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13198                                &pshufbMask[0], 32);
13199       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13200
13201       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13202
13203       static const int ShufMask[] = {0,  2,  -1,  -1};
13204       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13205                                 &ShufMask[0]);
13206
13207       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13208                        DAG.getIntPtrConstant(0));
13209
13210       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13211     }
13212
13213     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13214                                DAG.getIntPtrConstant(0));
13215
13216     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13217                                DAG.getIntPtrConstant(4));
13218
13219     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13220     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13221
13222     // PSHUFB
13223     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13224                                    -1, -1, -1, -1, -1, -1, -1, -1};
13225
13226     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13227                                 ShufMask1);
13228     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13229                                 ShufMask1);
13230
13231     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13232     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13233
13234     // MOVLHPS
13235     static const int ShufMask2[] = {0, 1, 4, 5};
13236
13237     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13238     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13239   }
13240
13241   return SDValue();
13242 }
13243
13244 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13245 /// specific shuffle of a load can be folded into a single element load.
13246 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13247 /// shuffles have been customed lowered so we need to handle those here.
13248 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13249                                          TargetLowering::DAGCombinerInfo &DCI) {
13250   if (DCI.isBeforeLegalizeOps())
13251     return SDValue();
13252
13253   SDValue InVec = N->getOperand(0);
13254   SDValue EltNo = N->getOperand(1);
13255
13256   if (!isa<ConstantSDNode>(EltNo))
13257     return SDValue();
13258
13259   EVT VT = InVec.getValueType();
13260
13261   bool HasShuffleIntoBitcast = false;
13262   if (InVec.getOpcode() == ISD::BITCAST) {
13263     // Don't duplicate a load with other uses.
13264     if (!InVec.hasOneUse())
13265       return SDValue();
13266     EVT BCVT = InVec.getOperand(0).getValueType();
13267     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13268       return SDValue();
13269     InVec = InVec.getOperand(0);
13270     HasShuffleIntoBitcast = true;
13271   }
13272
13273   if (!isTargetShuffle(InVec.getOpcode()))
13274     return SDValue();
13275
13276   // Don't duplicate a load with other uses.
13277   if (!InVec.hasOneUse())
13278     return SDValue();
13279
13280   SmallVector<int, 16> ShuffleMask;
13281   bool UnaryShuffle;
13282   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13283                             UnaryShuffle))
13284     return SDValue();
13285
13286   // Select the input vector, guarding against out of range extract vector.
13287   unsigned NumElems = VT.getVectorNumElements();
13288   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13289   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13290   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13291                                          : InVec.getOperand(1);
13292
13293   // If inputs to shuffle are the same for both ops, then allow 2 uses
13294   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13295
13296   if (LdNode.getOpcode() == ISD::BITCAST) {
13297     // Don't duplicate a load with other uses.
13298     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13299       return SDValue();
13300
13301     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13302     LdNode = LdNode.getOperand(0);
13303   }
13304
13305   if (!ISD::isNormalLoad(LdNode.getNode()))
13306     return SDValue();
13307
13308   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13309
13310   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13311     return SDValue();
13312
13313   if (HasShuffleIntoBitcast) {
13314     // If there's a bitcast before the shuffle, check if the load type and
13315     // alignment is valid.
13316     unsigned Align = LN0->getAlignment();
13317     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13318     unsigned NewAlign = TLI.getTargetData()->
13319       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13320
13321     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13322       return SDValue();
13323   }
13324
13325   // All checks match so transform back to vector_shuffle so that DAG combiner
13326   // can finish the job
13327   DebugLoc dl = N->getDebugLoc();
13328
13329   // Create shuffle node taking into account the case that its a unary shuffle
13330   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13331   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13332                                  InVec.getOperand(0), Shuffle,
13333                                  &ShuffleMask[0]);
13334   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13335   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13336                      EltNo);
13337 }
13338
13339 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13340 /// generation and convert it from being a bunch of shuffles and extracts
13341 /// to a simple store and scalar loads to extract the elements.
13342 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13343                                          TargetLowering::DAGCombinerInfo &DCI) {
13344   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13345   if (NewOp.getNode())
13346     return NewOp;
13347
13348   SDValue InputVector = N->getOperand(0);
13349
13350   // Only operate on vectors of 4 elements, where the alternative shuffling
13351   // gets to be more expensive.
13352   if (InputVector.getValueType() != MVT::v4i32)
13353     return SDValue();
13354
13355   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13356   // single use which is a sign-extend or zero-extend, and all elements are
13357   // used.
13358   SmallVector<SDNode *, 4> Uses;
13359   unsigned ExtractedElements = 0;
13360   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13361        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13362     if (UI.getUse().getResNo() != InputVector.getResNo())
13363       return SDValue();
13364
13365     SDNode *Extract = *UI;
13366     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13367       return SDValue();
13368
13369     if (Extract->getValueType(0) != MVT::i32)
13370       return SDValue();
13371     if (!Extract->hasOneUse())
13372       return SDValue();
13373     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13374         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13375       return SDValue();
13376     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13377       return SDValue();
13378
13379     // Record which element was extracted.
13380     ExtractedElements |=
13381       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13382
13383     Uses.push_back(Extract);
13384   }
13385
13386   // If not all the elements were used, this may not be worthwhile.
13387   if (ExtractedElements != 15)
13388     return SDValue();
13389
13390   // Ok, we've now decided to do the transformation.
13391   DebugLoc dl = InputVector.getDebugLoc();
13392
13393   // Store the value to a temporary stack slot.
13394   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13395   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13396                             MachinePointerInfo(), false, false, 0);
13397
13398   // Replace each use (extract) with a load of the appropriate element.
13399   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13400        UE = Uses.end(); UI != UE; ++UI) {
13401     SDNode *Extract = *UI;
13402
13403     // cOMpute the element's address.
13404     SDValue Idx = Extract->getOperand(1);
13405     unsigned EltSize =
13406         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13407     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13408     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13409     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13410
13411     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13412                                      StackPtr, OffsetVal);
13413
13414     // Load the scalar.
13415     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13416                                      ScalarAddr, MachinePointerInfo(),
13417                                      false, false, false, 0);
13418
13419     // Replace the exact with the load.
13420     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13421   }
13422
13423   // The replacement was made in place; don't return anything.
13424   return SDValue();
13425 }
13426
13427 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13428 /// nodes.
13429 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13430                                     TargetLowering::DAGCombinerInfo &DCI,
13431                                     const X86Subtarget *Subtarget) {
13432   DebugLoc DL = N->getDebugLoc();
13433   SDValue Cond = N->getOperand(0);
13434   // Get the LHS/RHS of the select.
13435   SDValue LHS = N->getOperand(1);
13436   SDValue RHS = N->getOperand(2);
13437   EVT VT = LHS.getValueType();
13438
13439   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13440   // instructions match the semantics of the common C idiom x<y?x:y but not
13441   // x<=y?x:y, because of how they handle negative zero (which can be
13442   // ignored in unsafe-math mode).
13443   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13444       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13445       (Subtarget->hasSSE2() ||
13446        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13447     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13448
13449     unsigned Opcode = 0;
13450     // Check for x CC y ? x : y.
13451     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13452         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13453       switch (CC) {
13454       default: break;
13455       case ISD::SETULT:
13456         // Converting this to a min would handle NaNs incorrectly, and swapping
13457         // the operands would cause it to handle comparisons between positive
13458         // and negative zero incorrectly.
13459         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13460           if (!DAG.getTarget().Options.UnsafeFPMath &&
13461               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13462             break;
13463           std::swap(LHS, RHS);
13464         }
13465         Opcode = X86ISD::FMIN;
13466         break;
13467       case ISD::SETOLE:
13468         // Converting this to a min would handle comparisons between positive
13469         // and negative zero incorrectly.
13470         if (!DAG.getTarget().Options.UnsafeFPMath &&
13471             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13472           break;
13473         Opcode = X86ISD::FMIN;
13474         break;
13475       case ISD::SETULE:
13476         // Converting this to a min would handle both negative zeros and NaNs
13477         // incorrectly, but we can swap the operands to fix both.
13478         std::swap(LHS, RHS);
13479       case ISD::SETOLT:
13480       case ISD::SETLT:
13481       case ISD::SETLE:
13482         Opcode = X86ISD::FMIN;
13483         break;
13484
13485       case ISD::SETOGE:
13486         // Converting this to a max would handle comparisons between positive
13487         // and negative zero incorrectly.
13488         if (!DAG.getTarget().Options.UnsafeFPMath &&
13489             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13490           break;
13491         Opcode = X86ISD::FMAX;
13492         break;
13493       case ISD::SETUGT:
13494         // Converting this to a max would handle NaNs incorrectly, and swapping
13495         // the operands would cause it to handle comparisons between positive
13496         // and negative zero incorrectly.
13497         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13498           if (!DAG.getTarget().Options.UnsafeFPMath &&
13499               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13500             break;
13501           std::swap(LHS, RHS);
13502         }
13503         Opcode = X86ISD::FMAX;
13504         break;
13505       case ISD::SETUGE:
13506         // Converting this to a max would handle both negative zeros and NaNs
13507         // incorrectly, but we can swap the operands to fix both.
13508         std::swap(LHS, RHS);
13509       case ISD::SETOGT:
13510       case ISD::SETGT:
13511       case ISD::SETGE:
13512         Opcode = X86ISD::FMAX;
13513         break;
13514       }
13515     // Check for x CC y ? y : x -- a min/max with reversed arms.
13516     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13517                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13518       switch (CC) {
13519       default: break;
13520       case ISD::SETOGE:
13521         // Converting this to a min would handle comparisons between positive
13522         // and negative zero incorrectly, and swapping the operands would
13523         // cause it to handle NaNs incorrectly.
13524         if (!DAG.getTarget().Options.UnsafeFPMath &&
13525             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13526           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13527             break;
13528           std::swap(LHS, RHS);
13529         }
13530         Opcode = X86ISD::FMIN;
13531         break;
13532       case ISD::SETUGT:
13533         // Converting this to a min would handle NaNs incorrectly.
13534         if (!DAG.getTarget().Options.UnsafeFPMath &&
13535             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13536           break;
13537         Opcode = X86ISD::FMIN;
13538         break;
13539       case ISD::SETUGE:
13540         // Converting this to a min would handle both negative zeros and NaNs
13541         // incorrectly, but we can swap the operands to fix both.
13542         std::swap(LHS, RHS);
13543       case ISD::SETOGT:
13544       case ISD::SETGT:
13545       case ISD::SETGE:
13546         Opcode = X86ISD::FMIN;
13547         break;
13548
13549       case ISD::SETULT:
13550         // Converting this to a max would handle NaNs incorrectly.
13551         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13552           break;
13553         Opcode = X86ISD::FMAX;
13554         break;
13555       case ISD::SETOLE:
13556         // Converting this to a max would handle comparisons between positive
13557         // and negative zero incorrectly, and swapping the operands would
13558         // cause it to handle NaNs incorrectly.
13559         if (!DAG.getTarget().Options.UnsafeFPMath &&
13560             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13561           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13562             break;
13563           std::swap(LHS, RHS);
13564         }
13565         Opcode = X86ISD::FMAX;
13566         break;
13567       case ISD::SETULE:
13568         // Converting this to a max would handle both negative zeros and NaNs
13569         // incorrectly, but we can swap the operands to fix both.
13570         std::swap(LHS, RHS);
13571       case ISD::SETOLT:
13572       case ISD::SETLT:
13573       case ISD::SETLE:
13574         Opcode = X86ISD::FMAX;
13575         break;
13576       }
13577     }
13578
13579     if (Opcode)
13580       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13581   }
13582
13583   // If this is a select between two integer constants, try to do some
13584   // optimizations.
13585   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13586     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13587       // Don't do this for crazy integer types.
13588       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13589         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13590         // so that TrueC (the true value) is larger than FalseC.
13591         bool NeedsCondInvert = false;
13592
13593         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13594             // Efficiently invertible.
13595             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13596              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13597               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13598           NeedsCondInvert = true;
13599           std::swap(TrueC, FalseC);
13600         }
13601
13602         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13603         if (FalseC->getAPIntValue() == 0 &&
13604             TrueC->getAPIntValue().isPowerOf2()) {
13605           if (NeedsCondInvert) // Invert the condition if needed.
13606             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13607                                DAG.getConstant(1, Cond.getValueType()));
13608
13609           // Zero extend the condition if needed.
13610           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13611
13612           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13613           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13614                              DAG.getConstant(ShAmt, MVT::i8));
13615         }
13616
13617         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13618         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13619           if (NeedsCondInvert) // Invert the condition if needed.
13620             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13621                                DAG.getConstant(1, Cond.getValueType()));
13622
13623           // Zero extend the condition if needed.
13624           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13625                              FalseC->getValueType(0), Cond);
13626           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13627                              SDValue(FalseC, 0));
13628         }
13629
13630         // Optimize cases that will turn into an LEA instruction.  This requires
13631         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13632         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13633           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13634           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13635
13636           bool isFastMultiplier = false;
13637           if (Diff < 10) {
13638             switch ((unsigned char)Diff) {
13639               default: break;
13640               case 1:  // result = add base, cond
13641               case 2:  // result = lea base(    , cond*2)
13642               case 3:  // result = lea base(cond, cond*2)
13643               case 4:  // result = lea base(    , cond*4)
13644               case 5:  // result = lea base(cond, cond*4)
13645               case 8:  // result = lea base(    , cond*8)
13646               case 9:  // result = lea base(cond, cond*8)
13647                 isFastMultiplier = true;
13648                 break;
13649             }
13650           }
13651
13652           if (isFastMultiplier) {
13653             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13654             if (NeedsCondInvert) // Invert the condition if needed.
13655               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13656                                  DAG.getConstant(1, Cond.getValueType()));
13657
13658             // Zero extend the condition if needed.
13659             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13660                                Cond);
13661             // Scale the condition by the difference.
13662             if (Diff != 1)
13663               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13664                                  DAG.getConstant(Diff, Cond.getValueType()));
13665
13666             // Add the base if non-zero.
13667             if (FalseC->getAPIntValue() != 0)
13668               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13669                                  SDValue(FalseC, 0));
13670             return Cond;
13671           }
13672         }
13673       }
13674   }
13675
13676   // Canonicalize max and min:
13677   // (x > y) ? x : y -> (x >= y) ? x : y
13678   // (x < y) ? x : y -> (x <= y) ? x : y
13679   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13680   // the need for an extra compare
13681   // against zero. e.g.
13682   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13683   // subl   %esi, %edi
13684   // testl  %edi, %edi
13685   // movl   $0, %eax
13686   // cmovgl %edi, %eax
13687   // =>
13688   // xorl   %eax, %eax
13689   // subl   %esi, $edi
13690   // cmovsl %eax, %edi
13691   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13692       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13693       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13694     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13695     switch (CC) {
13696     default: break;
13697     case ISD::SETLT:
13698     case ISD::SETGT: {
13699       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13700       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13701                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13702       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13703     }
13704     }
13705   }
13706
13707   // If we know that this node is legal then we know that it is going to be
13708   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13709   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13710   // to simplify previous instructions.
13711   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13712   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13713       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
13714     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13715
13716     // Don't optimize vector selects that map to mask-registers.
13717     if (BitWidth == 1)
13718       return SDValue();
13719
13720     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13721     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13722
13723     APInt KnownZero, KnownOne;
13724     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13725                                           DCI.isBeforeLegalizeOps());
13726     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13727         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13728       DCI.CommitTargetLoweringOpt(TLO);
13729   }
13730
13731   return SDValue();
13732 }
13733
13734 // Check whether a boolean test is testing a boolean value generated by
13735 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
13736 // code.
13737 //
13738 // Simplify the following patterns:
13739 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
13740 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
13741 // to (Op EFLAGS Cond)
13742 //
13743 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
13744 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
13745 // to (Op EFLAGS !Cond)
13746 //
13747 // where Op could be BRCOND or CMOV.
13748 //
13749 static SDValue BoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
13750   // Quit if not CMP and SUB with its value result used.
13751   if (Cmp.getOpcode() != X86ISD::CMP &&
13752       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
13753       return SDValue();
13754
13755   // Quit if not used as a boolean value.
13756   if (CC != X86::COND_E && CC != X86::COND_NE)
13757     return SDValue();
13758
13759   // Check CMP operands. One of them should be 0 or 1 and the other should be
13760   // an SetCC or extended from it.
13761   SDValue Op1 = Cmp.getOperand(0);
13762   SDValue Op2 = Cmp.getOperand(1);
13763
13764   SDValue SetCC;
13765   const ConstantSDNode* C = 0;
13766   bool needOppositeCond = (CC == X86::COND_E);
13767
13768   if ((C = dyn_cast<ConstantSDNode>(Op1)))
13769     SetCC = Op2;
13770   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
13771     SetCC = Op1;
13772   else // Quit if all operands are not constants.
13773     return SDValue();
13774
13775   if (C->getZExtValue() == 1)
13776     needOppositeCond = !needOppositeCond;
13777   else if (C->getZExtValue() != 0)
13778     // Quit if the constant is neither 0 or 1.
13779     return SDValue();
13780
13781   // Skip 'zext' node.
13782   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
13783     SetCC = SetCC.getOperand(0);
13784
13785   // Quit if not SETCC.
13786   // FIXME: So far we only handle the boolean value generated from SETCC. If
13787   // there is other ways to generate boolean values, we need handle them here
13788   // as well.
13789   if (SetCC.getOpcode() != X86ISD::SETCC)
13790     return SDValue();
13791
13792   // Set the condition code or opposite one if necessary.
13793   CC = X86::CondCode(SetCC.getConstantOperandVal(0));
13794   if (needOppositeCond)
13795     CC = X86::GetOppositeBranchCondition(CC);
13796
13797   return SetCC.getOperand(1);
13798 }
13799
13800 static bool IsValidFCMOVCondition(X86::CondCode CC) {
13801   switch (CC) {
13802   default:
13803     return false;
13804   case X86::COND_B:
13805   case X86::COND_BE:
13806   case X86::COND_E:
13807   case X86::COND_P:
13808   case X86::COND_AE:
13809   case X86::COND_A:
13810   case X86::COND_NE:
13811   case X86::COND_NP:
13812     return true;
13813   }
13814 }
13815
13816 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13817 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13818                                   TargetLowering::DAGCombinerInfo &DCI) {
13819   DebugLoc DL = N->getDebugLoc();
13820
13821   // If the flag operand isn't dead, don't touch this CMOV.
13822   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13823     return SDValue();
13824
13825   SDValue FalseOp = N->getOperand(0);
13826   SDValue TrueOp = N->getOperand(1);
13827   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13828   SDValue Cond = N->getOperand(3);
13829
13830   if (CC == X86::COND_E || CC == X86::COND_NE) {
13831     switch (Cond.getOpcode()) {
13832     default: break;
13833     case X86ISD::BSR:
13834     case X86ISD::BSF:
13835       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13836       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13837         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13838     }
13839   }
13840
13841   SDValue Flags;
13842
13843   Flags = BoolTestSetCCCombine(Cond, CC);
13844   if (Flags.getNode() &&
13845       // Extra check as FCMOV only supports a subset of X86 cond.
13846       (FalseOp.getValueType() != MVT::f80 || IsValidFCMOVCondition(CC))) {
13847     SDValue Ops[] = { FalseOp, TrueOp,
13848                       DAG.getConstant(CC, MVT::i8), Flags };
13849     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
13850                        Ops, array_lengthof(Ops));
13851   }
13852
13853   // If this is a select between two integer constants, try to do some
13854   // optimizations.  Note that the operands are ordered the opposite of SELECT
13855   // operands.
13856   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13857     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13858       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13859       // larger than FalseC (the false value).
13860       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13861         CC = X86::GetOppositeBranchCondition(CC);
13862         std::swap(TrueC, FalseC);
13863       }
13864
13865       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13866       // This is efficient for any integer data type (including i8/i16) and
13867       // shift amount.
13868       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13869         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13870                            DAG.getConstant(CC, MVT::i8), Cond);
13871
13872         // Zero extend the condition if needed.
13873         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13874
13875         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13876         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13877                            DAG.getConstant(ShAmt, MVT::i8));
13878         if (N->getNumValues() == 2)  // Dead flag value?
13879           return DCI.CombineTo(N, Cond, SDValue());
13880         return Cond;
13881       }
13882
13883       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13884       // for any integer data type, including i8/i16.
13885       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13886         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13887                            DAG.getConstant(CC, MVT::i8), Cond);
13888
13889         // Zero extend the condition if needed.
13890         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13891                            FalseC->getValueType(0), Cond);
13892         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13893                            SDValue(FalseC, 0));
13894
13895         if (N->getNumValues() == 2)  // Dead flag value?
13896           return DCI.CombineTo(N, Cond, SDValue());
13897         return Cond;
13898       }
13899
13900       // Optimize cases that will turn into an LEA instruction.  This requires
13901       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13902       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13903         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13904         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13905
13906         bool isFastMultiplier = false;
13907         if (Diff < 10) {
13908           switch ((unsigned char)Diff) {
13909           default: break;
13910           case 1:  // result = add base, cond
13911           case 2:  // result = lea base(    , cond*2)
13912           case 3:  // result = lea base(cond, cond*2)
13913           case 4:  // result = lea base(    , cond*4)
13914           case 5:  // result = lea base(cond, cond*4)
13915           case 8:  // result = lea base(    , cond*8)
13916           case 9:  // result = lea base(cond, cond*8)
13917             isFastMultiplier = true;
13918             break;
13919           }
13920         }
13921
13922         if (isFastMultiplier) {
13923           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13924           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13925                              DAG.getConstant(CC, MVT::i8), Cond);
13926           // Zero extend the condition if needed.
13927           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13928                              Cond);
13929           // Scale the condition by the difference.
13930           if (Diff != 1)
13931             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13932                                DAG.getConstant(Diff, Cond.getValueType()));
13933
13934           // Add the base if non-zero.
13935           if (FalseC->getAPIntValue() != 0)
13936             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13937                                SDValue(FalseC, 0));
13938           if (N->getNumValues() == 2)  // Dead flag value?
13939             return DCI.CombineTo(N, Cond, SDValue());
13940           return Cond;
13941         }
13942       }
13943     }
13944   }
13945   return SDValue();
13946 }
13947
13948
13949 /// PerformMulCombine - Optimize a single multiply with constant into two
13950 /// in order to implement it with two cheaper instructions, e.g.
13951 /// LEA + SHL, LEA + LEA.
13952 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13953                                  TargetLowering::DAGCombinerInfo &DCI) {
13954   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13955     return SDValue();
13956
13957   EVT VT = N->getValueType(0);
13958   if (VT != MVT::i64)
13959     return SDValue();
13960
13961   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13962   if (!C)
13963     return SDValue();
13964   uint64_t MulAmt = C->getZExtValue();
13965   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13966     return SDValue();
13967
13968   uint64_t MulAmt1 = 0;
13969   uint64_t MulAmt2 = 0;
13970   if ((MulAmt % 9) == 0) {
13971     MulAmt1 = 9;
13972     MulAmt2 = MulAmt / 9;
13973   } else if ((MulAmt % 5) == 0) {
13974     MulAmt1 = 5;
13975     MulAmt2 = MulAmt / 5;
13976   } else if ((MulAmt % 3) == 0) {
13977     MulAmt1 = 3;
13978     MulAmt2 = MulAmt / 3;
13979   }
13980   if (MulAmt2 &&
13981       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13982     DebugLoc DL = N->getDebugLoc();
13983
13984     if (isPowerOf2_64(MulAmt2) &&
13985         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13986       // If second multiplifer is pow2, issue it first. We want the multiply by
13987       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13988       // is an add.
13989       std::swap(MulAmt1, MulAmt2);
13990
13991     SDValue NewMul;
13992     if (isPowerOf2_64(MulAmt1))
13993       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13994                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13995     else
13996       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13997                            DAG.getConstant(MulAmt1, VT));
13998
13999     if (isPowerOf2_64(MulAmt2))
14000       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14001                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14002     else
14003       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14004                            DAG.getConstant(MulAmt2, VT));
14005
14006     // Do not add new nodes to DAG combiner worklist.
14007     DCI.CombineTo(N, NewMul, false);
14008   }
14009   return SDValue();
14010 }
14011
14012 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14013   SDValue N0 = N->getOperand(0);
14014   SDValue N1 = N->getOperand(1);
14015   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14016   EVT VT = N0.getValueType();
14017
14018   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14019   // since the result of setcc_c is all zero's or all ones.
14020   if (VT.isInteger() && !VT.isVector() &&
14021       N1C && N0.getOpcode() == ISD::AND &&
14022       N0.getOperand(1).getOpcode() == ISD::Constant) {
14023     SDValue N00 = N0.getOperand(0);
14024     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14025         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14026           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14027          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14028       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14029       APInt ShAmt = N1C->getAPIntValue();
14030       Mask = Mask.shl(ShAmt);
14031       if (Mask != 0)
14032         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14033                            N00, DAG.getConstant(Mask, VT));
14034     }
14035   }
14036
14037
14038   // Hardware support for vector shifts is sparse which makes us scalarize the
14039   // vector operations in many cases. Also, on sandybridge ADD is faster than
14040   // shl.
14041   // (shl V, 1) -> add V,V
14042   if (isSplatVector(N1.getNode())) {
14043     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14044     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14045     // We shift all of the values by one. In many cases we do not have
14046     // hardware support for this operation. This is better expressed as an ADD
14047     // of two values.
14048     if (N1C && (1 == N1C->getZExtValue())) {
14049       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14050     }
14051   }
14052
14053   return SDValue();
14054 }
14055
14056 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14057 ///                       when possible.
14058 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14059                                    TargetLowering::DAGCombinerInfo &DCI,
14060                                    const X86Subtarget *Subtarget) {
14061   EVT VT = N->getValueType(0);
14062   if (N->getOpcode() == ISD::SHL) {
14063     SDValue V = PerformSHLCombine(N, DAG);
14064     if (V.getNode()) return V;
14065   }
14066
14067   // On X86 with SSE2 support, we can transform this to a vector shift if
14068   // all elements are shifted by the same amount.  We can't do this in legalize
14069   // because the a constant vector is typically transformed to a constant pool
14070   // so we have no knowledge of the shift amount.
14071   if (!Subtarget->hasSSE2())
14072     return SDValue();
14073
14074   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14075       (!Subtarget->hasAVX2() ||
14076        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14077     return SDValue();
14078
14079   SDValue ShAmtOp = N->getOperand(1);
14080   EVT EltVT = VT.getVectorElementType();
14081   DebugLoc DL = N->getDebugLoc();
14082   SDValue BaseShAmt = SDValue();
14083   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14084     unsigned NumElts = VT.getVectorNumElements();
14085     unsigned i = 0;
14086     for (; i != NumElts; ++i) {
14087       SDValue Arg = ShAmtOp.getOperand(i);
14088       if (Arg.getOpcode() == ISD::UNDEF) continue;
14089       BaseShAmt = Arg;
14090       break;
14091     }
14092     // Handle the case where the build_vector is all undef
14093     // FIXME: Should DAG allow this?
14094     if (i == NumElts)
14095       return SDValue();
14096
14097     for (; i != NumElts; ++i) {
14098       SDValue Arg = ShAmtOp.getOperand(i);
14099       if (Arg.getOpcode() == ISD::UNDEF) continue;
14100       if (Arg != BaseShAmt) {
14101         return SDValue();
14102       }
14103     }
14104   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14105              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14106     SDValue InVec = ShAmtOp.getOperand(0);
14107     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14108       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14109       unsigned i = 0;
14110       for (; i != NumElts; ++i) {
14111         SDValue Arg = InVec.getOperand(i);
14112         if (Arg.getOpcode() == ISD::UNDEF) continue;
14113         BaseShAmt = Arg;
14114         break;
14115       }
14116     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14117        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14118          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14119          if (C->getZExtValue() == SplatIdx)
14120            BaseShAmt = InVec.getOperand(1);
14121        }
14122     }
14123     if (BaseShAmt.getNode() == 0) {
14124       // Don't create instructions with illegal types after legalize
14125       // types has run.
14126       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14127           !DCI.isBeforeLegalize())
14128         return SDValue();
14129
14130       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14131                               DAG.getIntPtrConstant(0));
14132     }
14133   } else
14134     return SDValue();
14135
14136   // The shift amount is an i32.
14137   if (EltVT.bitsGT(MVT::i32))
14138     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14139   else if (EltVT.bitsLT(MVT::i32))
14140     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14141
14142   // The shift amount is identical so we can do a vector shift.
14143   SDValue  ValOp = N->getOperand(0);
14144   switch (N->getOpcode()) {
14145   default:
14146     llvm_unreachable("Unknown shift opcode!");
14147   case ISD::SHL:
14148     switch (VT.getSimpleVT().SimpleTy) {
14149     default: return SDValue();
14150     case MVT::v2i64:
14151     case MVT::v4i32:
14152     case MVT::v8i16:
14153     case MVT::v4i64:
14154     case MVT::v8i32:
14155     case MVT::v16i16:
14156       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14157     }
14158   case ISD::SRA:
14159     switch (VT.getSimpleVT().SimpleTy) {
14160     default: return SDValue();
14161     case MVT::v4i32:
14162     case MVT::v8i16:
14163     case MVT::v8i32:
14164     case MVT::v16i16:
14165       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14166     }
14167   case ISD::SRL:
14168     switch (VT.getSimpleVT().SimpleTy) {
14169     default: return SDValue();
14170     case MVT::v2i64:
14171     case MVT::v4i32:
14172     case MVT::v8i16:
14173     case MVT::v4i64:
14174     case MVT::v8i32:
14175     case MVT::v16i16:
14176       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14177     }
14178   }
14179 }
14180
14181
14182 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14183 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14184 // and friends.  Likewise for OR -> CMPNEQSS.
14185 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14186                             TargetLowering::DAGCombinerInfo &DCI,
14187                             const X86Subtarget *Subtarget) {
14188   unsigned opcode;
14189
14190   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14191   // we're requiring SSE2 for both.
14192   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14193     SDValue N0 = N->getOperand(0);
14194     SDValue N1 = N->getOperand(1);
14195     SDValue CMP0 = N0->getOperand(1);
14196     SDValue CMP1 = N1->getOperand(1);
14197     DebugLoc DL = N->getDebugLoc();
14198
14199     // The SETCCs should both refer to the same CMP.
14200     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14201       return SDValue();
14202
14203     SDValue CMP00 = CMP0->getOperand(0);
14204     SDValue CMP01 = CMP0->getOperand(1);
14205     EVT     VT    = CMP00.getValueType();
14206
14207     if (VT == MVT::f32 || VT == MVT::f64) {
14208       bool ExpectingFlags = false;
14209       // Check for any users that want flags:
14210       for (SDNode::use_iterator UI = N->use_begin(),
14211              UE = N->use_end();
14212            !ExpectingFlags && UI != UE; ++UI)
14213         switch (UI->getOpcode()) {
14214         default:
14215         case ISD::BR_CC:
14216         case ISD::BRCOND:
14217         case ISD::SELECT:
14218           ExpectingFlags = true;
14219           break;
14220         case ISD::CopyToReg:
14221         case ISD::SIGN_EXTEND:
14222         case ISD::ZERO_EXTEND:
14223         case ISD::ANY_EXTEND:
14224           break;
14225         }
14226
14227       if (!ExpectingFlags) {
14228         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14229         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14230
14231         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14232           X86::CondCode tmp = cc0;
14233           cc0 = cc1;
14234           cc1 = tmp;
14235         }
14236
14237         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14238             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14239           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14240           X86ISD::NodeType NTOperator = is64BitFP ?
14241             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14242           // FIXME: need symbolic constants for these magic numbers.
14243           // See X86ATTInstPrinter.cpp:printSSECC().
14244           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14245           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14246                                               DAG.getConstant(x86cc, MVT::i8));
14247           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14248                                               OnesOrZeroesF);
14249           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14250                                       DAG.getConstant(1, MVT::i32));
14251           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14252           return OneBitOfTruth;
14253         }
14254       }
14255     }
14256   }
14257   return SDValue();
14258 }
14259
14260 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14261 /// so it can be folded inside ANDNP.
14262 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14263   EVT VT = N->getValueType(0);
14264
14265   // Match direct AllOnes for 128 and 256-bit vectors
14266   if (ISD::isBuildVectorAllOnes(N))
14267     return true;
14268
14269   // Look through a bit convert.
14270   if (N->getOpcode() == ISD::BITCAST)
14271     N = N->getOperand(0).getNode();
14272
14273   // Sometimes the operand may come from a insert_subvector building a 256-bit
14274   // allones vector
14275   if (VT.is256BitVector() &&
14276       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14277     SDValue V1 = N->getOperand(0);
14278     SDValue V2 = N->getOperand(1);
14279
14280     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14281         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14282         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14283         ISD::isBuildVectorAllOnes(V2.getNode()))
14284       return true;
14285   }
14286
14287   return false;
14288 }
14289
14290 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14291                                  TargetLowering::DAGCombinerInfo &DCI,
14292                                  const X86Subtarget *Subtarget) {
14293   if (DCI.isBeforeLegalizeOps())
14294     return SDValue();
14295
14296   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14297   if (R.getNode())
14298     return R;
14299
14300   EVT VT = N->getValueType(0);
14301
14302   // Create ANDN, BLSI, and BLSR instructions
14303   // BLSI is X & (-X)
14304   // BLSR is X & (X-1)
14305   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14306     SDValue N0 = N->getOperand(0);
14307     SDValue N1 = N->getOperand(1);
14308     DebugLoc DL = N->getDebugLoc();
14309
14310     // Check LHS for not
14311     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14312       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14313     // Check RHS for not
14314     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14315       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14316
14317     // Check LHS for neg
14318     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14319         isZero(N0.getOperand(0)))
14320       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14321
14322     // Check RHS for neg
14323     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14324         isZero(N1.getOperand(0)))
14325       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14326
14327     // Check LHS for X-1
14328     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14329         isAllOnes(N0.getOperand(1)))
14330       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14331
14332     // Check RHS for X-1
14333     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14334         isAllOnes(N1.getOperand(1)))
14335       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14336
14337     return SDValue();
14338   }
14339
14340   // Want to form ANDNP nodes:
14341   // 1) In the hopes of then easily combining them with OR and AND nodes
14342   //    to form PBLEND/PSIGN.
14343   // 2) To match ANDN packed intrinsics
14344   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14345     return SDValue();
14346
14347   SDValue N0 = N->getOperand(0);
14348   SDValue N1 = N->getOperand(1);
14349   DebugLoc DL = N->getDebugLoc();
14350
14351   // Check LHS for vnot
14352   if (N0.getOpcode() == ISD::XOR &&
14353       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14354       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14355     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14356
14357   // Check RHS for vnot
14358   if (N1.getOpcode() == ISD::XOR &&
14359       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14360       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14361     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14362
14363   return SDValue();
14364 }
14365
14366 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14367                                 TargetLowering::DAGCombinerInfo &DCI,
14368                                 const X86Subtarget *Subtarget) {
14369   if (DCI.isBeforeLegalizeOps())
14370     return SDValue();
14371
14372   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14373   if (R.getNode())
14374     return R;
14375
14376   EVT VT = N->getValueType(0);
14377
14378   SDValue N0 = N->getOperand(0);
14379   SDValue N1 = N->getOperand(1);
14380
14381   // look for psign/blend
14382   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14383     if (!Subtarget->hasSSSE3() ||
14384         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14385       return SDValue();
14386
14387     // Canonicalize pandn to RHS
14388     if (N0.getOpcode() == X86ISD::ANDNP)
14389       std::swap(N0, N1);
14390     // or (and (m, y), (pandn m, x))
14391     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14392       SDValue Mask = N1.getOperand(0);
14393       SDValue X    = N1.getOperand(1);
14394       SDValue Y;
14395       if (N0.getOperand(0) == Mask)
14396         Y = N0.getOperand(1);
14397       if (N0.getOperand(1) == Mask)
14398         Y = N0.getOperand(0);
14399
14400       // Check to see if the mask appeared in both the AND and ANDNP and
14401       if (!Y.getNode())
14402         return SDValue();
14403
14404       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14405       // Look through mask bitcast.
14406       if (Mask.getOpcode() == ISD::BITCAST)
14407         Mask = Mask.getOperand(0);
14408       if (X.getOpcode() == ISD::BITCAST)
14409         X = X.getOperand(0);
14410       if (Y.getOpcode() == ISD::BITCAST)
14411         Y = Y.getOperand(0);
14412
14413       EVT MaskVT = Mask.getValueType();
14414
14415       // Validate that the Mask operand is a vector sra node.
14416       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14417       // there is no psrai.b
14418       if (Mask.getOpcode() != X86ISD::VSRAI)
14419         return SDValue();
14420
14421       // Check that the SRA is all signbits.
14422       SDValue SraC = Mask.getOperand(1);
14423       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14424       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14425       if ((SraAmt + 1) != EltBits)
14426         return SDValue();
14427
14428       DebugLoc DL = N->getDebugLoc();
14429
14430       // Now we know we at least have a plendvb with the mask val.  See if
14431       // we can form a psignb/w/d.
14432       // psign = x.type == y.type == mask.type && y = sub(0, x);
14433       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14434           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14435           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14436         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14437                "Unsupported VT for PSIGN");
14438         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14439         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14440       }
14441       // PBLENDVB only available on SSE 4.1
14442       if (!Subtarget->hasSSE41())
14443         return SDValue();
14444
14445       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14446
14447       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14448       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14449       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14450       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14451       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14452     }
14453   }
14454
14455   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14456     return SDValue();
14457
14458   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14459   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14460     std::swap(N0, N1);
14461   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14462     return SDValue();
14463   if (!N0.hasOneUse() || !N1.hasOneUse())
14464     return SDValue();
14465
14466   SDValue ShAmt0 = N0.getOperand(1);
14467   if (ShAmt0.getValueType() != MVT::i8)
14468     return SDValue();
14469   SDValue ShAmt1 = N1.getOperand(1);
14470   if (ShAmt1.getValueType() != MVT::i8)
14471     return SDValue();
14472   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14473     ShAmt0 = ShAmt0.getOperand(0);
14474   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14475     ShAmt1 = ShAmt1.getOperand(0);
14476
14477   DebugLoc DL = N->getDebugLoc();
14478   unsigned Opc = X86ISD::SHLD;
14479   SDValue Op0 = N0.getOperand(0);
14480   SDValue Op1 = N1.getOperand(0);
14481   if (ShAmt0.getOpcode() == ISD::SUB) {
14482     Opc = X86ISD::SHRD;
14483     std::swap(Op0, Op1);
14484     std::swap(ShAmt0, ShAmt1);
14485   }
14486
14487   unsigned Bits = VT.getSizeInBits();
14488   if (ShAmt1.getOpcode() == ISD::SUB) {
14489     SDValue Sum = ShAmt1.getOperand(0);
14490     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14491       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14492       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14493         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14494       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14495         return DAG.getNode(Opc, DL, VT,
14496                            Op0, Op1,
14497                            DAG.getNode(ISD::TRUNCATE, DL,
14498                                        MVT::i8, ShAmt0));
14499     }
14500   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14501     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14502     if (ShAmt0C &&
14503         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14504       return DAG.getNode(Opc, DL, VT,
14505                          N0.getOperand(0), N1.getOperand(0),
14506                          DAG.getNode(ISD::TRUNCATE, DL,
14507                                        MVT::i8, ShAmt0));
14508   }
14509
14510   return SDValue();
14511 }
14512
14513 // Generate NEG and CMOV for integer abs.
14514 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14515   EVT VT = N->getValueType(0);
14516
14517   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14518   // 8-bit integer abs to NEG and CMOV.
14519   if (VT.isInteger() && VT.getSizeInBits() == 8)
14520     return SDValue();
14521
14522   SDValue N0 = N->getOperand(0);
14523   SDValue N1 = N->getOperand(1);
14524   DebugLoc DL = N->getDebugLoc();
14525
14526   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14527   // and change it to SUB and CMOV.
14528   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14529       N0.getOpcode() == ISD::ADD &&
14530       N0.getOperand(1) == N1 &&
14531       N1.getOpcode() == ISD::SRA &&
14532       N1.getOperand(0) == N0.getOperand(0))
14533     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14534       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14535         // Generate SUB & CMOV.
14536         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14537                                   DAG.getConstant(0, VT), N0.getOperand(0));
14538
14539         SDValue Ops[] = { N0.getOperand(0), Neg,
14540                           DAG.getConstant(X86::COND_GE, MVT::i8),
14541                           SDValue(Neg.getNode(), 1) };
14542         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14543                            Ops, array_lengthof(Ops));
14544       }
14545   return SDValue();
14546 }
14547
14548 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14549 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14550                                  TargetLowering::DAGCombinerInfo &DCI,
14551                                  const X86Subtarget *Subtarget) {
14552   if (DCI.isBeforeLegalizeOps())
14553     return SDValue();
14554
14555   if (Subtarget->hasCMov()) {
14556     SDValue RV = performIntegerAbsCombine(N, DAG);
14557     if (RV.getNode())
14558       return RV;
14559   }
14560
14561   // Try forming BMI if it is available.
14562   if (!Subtarget->hasBMI())
14563     return SDValue();
14564
14565   EVT VT = N->getValueType(0);
14566
14567   if (VT != MVT::i32 && VT != MVT::i64)
14568     return SDValue();
14569
14570   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14571
14572   // Create BLSMSK instructions by finding X ^ (X-1)
14573   SDValue N0 = N->getOperand(0);
14574   SDValue N1 = N->getOperand(1);
14575   DebugLoc DL = N->getDebugLoc();
14576
14577   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14578       isAllOnes(N0.getOperand(1)))
14579     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14580
14581   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14582       isAllOnes(N1.getOperand(1)))
14583     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14584
14585   return SDValue();
14586 }
14587
14588 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14589 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14590                                   TargetLowering::DAGCombinerInfo &DCI,
14591                                   const X86Subtarget *Subtarget) {
14592   LoadSDNode *Ld = cast<LoadSDNode>(N);
14593   EVT RegVT = Ld->getValueType(0);
14594   EVT MemVT = Ld->getMemoryVT();
14595   DebugLoc dl = Ld->getDebugLoc();
14596   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14597
14598   ISD::LoadExtType Ext = Ld->getExtensionType();
14599
14600   // If this is a vector EXT Load then attempt to optimize it using a
14601   // shuffle. We need SSE4 for the shuffles.
14602   // TODO: It is possible to support ZExt by zeroing the undef values
14603   // during the shuffle phase or after the shuffle.
14604   if (RegVT.isVector() && RegVT.isInteger() &&
14605       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14606     assert(MemVT != RegVT && "Cannot extend to the same type");
14607     assert(MemVT.isVector() && "Must load a vector from memory");
14608
14609     unsigned NumElems = RegVT.getVectorNumElements();
14610     unsigned RegSz = RegVT.getSizeInBits();
14611     unsigned MemSz = MemVT.getSizeInBits();
14612     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14613
14614     // All sizes must be a power of two.
14615     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
14616       return SDValue();
14617
14618     // Attempt to load the original value using scalar loads.
14619     // Find the largest scalar type that divides the total loaded size.
14620     MVT SclrLoadTy = MVT::i8;
14621     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14622          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14623       MVT Tp = (MVT::SimpleValueType)tp;
14624       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14625         SclrLoadTy = Tp;
14626       }
14627     }
14628
14629     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14630     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14631         (64 <= MemSz))
14632       SclrLoadTy = MVT::f64;
14633
14634     // Calculate the number of scalar loads that we need to perform
14635     // in order to load our vector from memory.
14636     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14637
14638     // Represent our vector as a sequence of elements which are the
14639     // largest scalar that we can load.
14640     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14641       RegSz/SclrLoadTy.getSizeInBits());
14642
14643     // Represent the data using the same element type that is stored in
14644     // memory. In practice, we ''widen'' MemVT.
14645     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14646                                   RegSz/MemVT.getScalarType().getSizeInBits());
14647
14648     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14649       "Invalid vector type");
14650
14651     // We can't shuffle using an illegal type.
14652     if (!TLI.isTypeLegal(WideVecVT))
14653       return SDValue();
14654
14655     SmallVector<SDValue, 8> Chains;
14656     SDValue Ptr = Ld->getBasePtr();
14657     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
14658                                         TLI.getPointerTy());
14659     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14660
14661     for (unsigned i = 0; i < NumLoads; ++i) {
14662       // Perform a single load.
14663       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14664                                        Ptr, Ld->getPointerInfo(),
14665                                        Ld->isVolatile(), Ld->isNonTemporal(),
14666                                        Ld->isInvariant(), Ld->getAlignment());
14667       Chains.push_back(ScalarLoad.getValue(1));
14668       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14669       // another round of DAGCombining.
14670       if (i == 0)
14671         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14672       else
14673         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14674                           ScalarLoad, DAG.getIntPtrConstant(i));
14675
14676       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14677     }
14678
14679     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14680                                Chains.size());
14681
14682     // Bitcast the loaded value to a vector of the original element type, in
14683     // the size of the target vector type.
14684     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14685     unsigned SizeRatio = RegSz/MemSz;
14686
14687     // Redistribute the loaded elements into the different locations.
14688     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14689     for (unsigned i = 0; i != NumElems; ++i)
14690       ShuffleVec[i*SizeRatio] = i;
14691
14692     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14693                                          DAG.getUNDEF(WideVecVT),
14694                                          &ShuffleVec[0]);
14695
14696     // Bitcast to the requested type.
14697     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14698     // Replace the original load with the new sequence
14699     // and return the new chain.
14700     return DCI.CombineTo(N, Shuff, TF, true);
14701   }
14702
14703   return SDValue();
14704 }
14705
14706 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14707 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14708                                    const X86Subtarget *Subtarget) {
14709   StoreSDNode *St = cast<StoreSDNode>(N);
14710   EVT VT = St->getValue().getValueType();
14711   EVT StVT = St->getMemoryVT();
14712   DebugLoc dl = St->getDebugLoc();
14713   SDValue StoredVal = St->getOperand(1);
14714   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14715
14716   // If we are saving a concatenation of two XMM registers, perform two stores.
14717   // On Sandy Bridge, 256-bit memory operations are executed by two
14718   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14719   // memory  operation.
14720   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
14721       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14722       StoredVal.getNumOperands() == 2) {
14723     SDValue Value0 = StoredVal.getOperand(0);
14724     SDValue Value1 = StoredVal.getOperand(1);
14725
14726     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14727     SDValue Ptr0 = St->getBasePtr();
14728     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14729
14730     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14731                                 St->getPointerInfo(), St->isVolatile(),
14732                                 St->isNonTemporal(), St->getAlignment());
14733     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14734                                 St->getPointerInfo(), St->isVolatile(),
14735                                 St->isNonTemporal(), St->getAlignment());
14736     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14737   }
14738
14739   // Optimize trunc store (of multiple scalars) to shuffle and store.
14740   // First, pack all of the elements in one place. Next, store to memory
14741   // in fewer chunks.
14742   if (St->isTruncatingStore() && VT.isVector()) {
14743     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14744     unsigned NumElems = VT.getVectorNumElements();
14745     assert(StVT != VT && "Cannot truncate to the same type");
14746     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14747     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14748
14749     // From, To sizes and ElemCount must be pow of two
14750     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14751     // We are going to use the original vector elt for storing.
14752     // Accumulated smaller vector elements must be a multiple of the store size.
14753     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14754
14755     unsigned SizeRatio  = FromSz / ToSz;
14756
14757     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14758
14759     // Create a type on which we perform the shuffle
14760     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14761             StVT.getScalarType(), NumElems*SizeRatio);
14762
14763     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14764
14765     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14766     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14767     for (unsigned i = 0; i != NumElems; ++i)
14768       ShuffleVec[i] = i * SizeRatio;
14769
14770     // Can't shuffle using an illegal type.
14771     if (!TLI.isTypeLegal(WideVecVT))
14772       return SDValue();
14773
14774     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14775                                          DAG.getUNDEF(WideVecVT),
14776                                          &ShuffleVec[0]);
14777     // At this point all of the data is stored at the bottom of the
14778     // register. We now need to save it to mem.
14779
14780     // Find the largest store unit
14781     MVT StoreType = MVT::i8;
14782     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14783          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14784       MVT Tp = (MVT::SimpleValueType)tp;
14785       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
14786         StoreType = Tp;
14787     }
14788
14789     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14790     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
14791         (64 <= NumElems * ToSz))
14792       StoreType = MVT::f64;
14793
14794     // Bitcast the original vector into a vector of store-size units
14795     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14796             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
14797     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14798     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14799     SmallVector<SDValue, 8> Chains;
14800     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14801                                         TLI.getPointerTy());
14802     SDValue Ptr = St->getBasePtr();
14803
14804     // Perform one or more big stores into memory.
14805     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14806       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14807                                    StoreType, ShuffWide,
14808                                    DAG.getIntPtrConstant(i));
14809       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14810                                 St->getPointerInfo(), St->isVolatile(),
14811                                 St->isNonTemporal(), St->getAlignment());
14812       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14813       Chains.push_back(Ch);
14814     }
14815
14816     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14817                                Chains.size());
14818   }
14819
14820
14821   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14822   // the FP state in cases where an emms may be missing.
14823   // A preferable solution to the general problem is to figure out the right
14824   // places to insert EMMS.  This qualifies as a quick hack.
14825
14826   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14827   if (VT.getSizeInBits() != 64)
14828     return SDValue();
14829
14830   const Function *F = DAG.getMachineFunction().getFunction();
14831   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14832   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14833                      && Subtarget->hasSSE2();
14834   if ((VT.isVector() ||
14835        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14836       isa<LoadSDNode>(St->getValue()) &&
14837       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14838       St->getChain().hasOneUse() && !St->isVolatile()) {
14839     SDNode* LdVal = St->getValue().getNode();
14840     LoadSDNode *Ld = 0;
14841     int TokenFactorIndex = -1;
14842     SmallVector<SDValue, 8> Ops;
14843     SDNode* ChainVal = St->getChain().getNode();
14844     // Must be a store of a load.  We currently handle two cases:  the load
14845     // is a direct child, and it's under an intervening TokenFactor.  It is
14846     // possible to dig deeper under nested TokenFactors.
14847     if (ChainVal == LdVal)
14848       Ld = cast<LoadSDNode>(St->getChain());
14849     else if (St->getValue().hasOneUse() &&
14850              ChainVal->getOpcode() == ISD::TokenFactor) {
14851       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14852         if (ChainVal->getOperand(i).getNode() == LdVal) {
14853           TokenFactorIndex = i;
14854           Ld = cast<LoadSDNode>(St->getValue());
14855         } else
14856           Ops.push_back(ChainVal->getOperand(i));
14857       }
14858     }
14859
14860     if (!Ld || !ISD::isNormalLoad(Ld))
14861       return SDValue();
14862
14863     // If this is not the MMX case, i.e. we are just turning i64 load/store
14864     // into f64 load/store, avoid the transformation if there are multiple
14865     // uses of the loaded value.
14866     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14867       return SDValue();
14868
14869     DebugLoc LdDL = Ld->getDebugLoc();
14870     DebugLoc StDL = N->getDebugLoc();
14871     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14872     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14873     // pair instead.
14874     if (Subtarget->is64Bit() || F64IsLegal) {
14875       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14876       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14877                                   Ld->getPointerInfo(), Ld->isVolatile(),
14878                                   Ld->isNonTemporal(), Ld->isInvariant(),
14879                                   Ld->getAlignment());
14880       SDValue NewChain = NewLd.getValue(1);
14881       if (TokenFactorIndex != -1) {
14882         Ops.push_back(NewChain);
14883         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14884                                Ops.size());
14885       }
14886       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14887                           St->getPointerInfo(),
14888                           St->isVolatile(), St->isNonTemporal(),
14889                           St->getAlignment());
14890     }
14891
14892     // Otherwise, lower to two pairs of 32-bit loads / stores.
14893     SDValue LoAddr = Ld->getBasePtr();
14894     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14895                                  DAG.getConstant(4, MVT::i32));
14896
14897     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14898                                Ld->getPointerInfo(),
14899                                Ld->isVolatile(), Ld->isNonTemporal(),
14900                                Ld->isInvariant(), Ld->getAlignment());
14901     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14902                                Ld->getPointerInfo().getWithOffset(4),
14903                                Ld->isVolatile(), Ld->isNonTemporal(),
14904                                Ld->isInvariant(),
14905                                MinAlign(Ld->getAlignment(), 4));
14906
14907     SDValue NewChain = LoLd.getValue(1);
14908     if (TokenFactorIndex != -1) {
14909       Ops.push_back(LoLd);
14910       Ops.push_back(HiLd);
14911       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14912                              Ops.size());
14913     }
14914
14915     LoAddr = St->getBasePtr();
14916     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14917                          DAG.getConstant(4, MVT::i32));
14918
14919     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14920                                 St->getPointerInfo(),
14921                                 St->isVolatile(), St->isNonTemporal(),
14922                                 St->getAlignment());
14923     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14924                                 St->getPointerInfo().getWithOffset(4),
14925                                 St->isVolatile(),
14926                                 St->isNonTemporal(),
14927                                 MinAlign(St->getAlignment(), 4));
14928     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14929   }
14930   return SDValue();
14931 }
14932
14933 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14934 /// and return the operands for the horizontal operation in LHS and RHS.  A
14935 /// horizontal operation performs the binary operation on successive elements
14936 /// of its first operand, then on successive elements of its second operand,
14937 /// returning the resulting values in a vector.  For example, if
14938 ///   A = < float a0, float a1, float a2, float a3 >
14939 /// and
14940 ///   B = < float b0, float b1, float b2, float b3 >
14941 /// then the result of doing a horizontal operation on A and B is
14942 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14943 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14944 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14945 /// set to A, RHS to B, and the routine returns 'true'.
14946 /// Note that the binary operation should have the property that if one of the
14947 /// operands is UNDEF then the result is UNDEF.
14948 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14949   // Look for the following pattern: if
14950   //   A = < float a0, float a1, float a2, float a3 >
14951   //   B = < float b0, float b1, float b2, float b3 >
14952   // and
14953   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14954   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14955   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14956   // which is A horizontal-op B.
14957
14958   // At least one of the operands should be a vector shuffle.
14959   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14960       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14961     return false;
14962
14963   EVT VT = LHS.getValueType();
14964
14965   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14966          "Unsupported vector type for horizontal add/sub");
14967
14968   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14969   // operate independently on 128-bit lanes.
14970   unsigned NumElts = VT.getVectorNumElements();
14971   unsigned NumLanes = VT.getSizeInBits()/128;
14972   unsigned NumLaneElts = NumElts / NumLanes;
14973   assert((NumLaneElts % 2 == 0) &&
14974          "Vector type should have an even number of elements in each lane");
14975   unsigned HalfLaneElts = NumLaneElts/2;
14976
14977   // View LHS in the form
14978   //   LHS = VECTOR_SHUFFLE A, B, LMask
14979   // If LHS is not a shuffle then pretend it is the shuffle
14980   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14981   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14982   // type VT.
14983   SDValue A, B;
14984   SmallVector<int, 16> LMask(NumElts);
14985   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14986     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14987       A = LHS.getOperand(0);
14988     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14989       B = LHS.getOperand(1);
14990     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
14991     std::copy(Mask.begin(), Mask.end(), LMask.begin());
14992   } else {
14993     if (LHS.getOpcode() != ISD::UNDEF)
14994       A = LHS;
14995     for (unsigned i = 0; i != NumElts; ++i)
14996       LMask[i] = i;
14997   }
14998
14999   // Likewise, view RHS in the form
15000   //   RHS = VECTOR_SHUFFLE C, D, RMask
15001   SDValue C, D;
15002   SmallVector<int, 16> RMask(NumElts);
15003   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15004     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15005       C = RHS.getOperand(0);
15006     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15007       D = RHS.getOperand(1);
15008     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15009     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15010   } else {
15011     if (RHS.getOpcode() != ISD::UNDEF)
15012       C = RHS;
15013     for (unsigned i = 0; i != NumElts; ++i)
15014       RMask[i] = i;
15015   }
15016
15017   // Check that the shuffles are both shuffling the same vectors.
15018   if (!(A == C && B == D) && !(A == D && B == C))
15019     return false;
15020
15021   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15022   if (!A.getNode() && !B.getNode())
15023     return false;
15024
15025   // If A and B occur in reverse order in RHS, then "swap" them (which means
15026   // rewriting the mask).
15027   if (A != C)
15028     CommuteVectorShuffleMask(RMask, NumElts);
15029
15030   // At this point LHS and RHS are equivalent to
15031   //   LHS = VECTOR_SHUFFLE A, B, LMask
15032   //   RHS = VECTOR_SHUFFLE A, B, RMask
15033   // Check that the masks correspond to performing a horizontal operation.
15034   for (unsigned i = 0; i != NumElts; ++i) {
15035     int LIdx = LMask[i], RIdx = RMask[i];
15036
15037     // Ignore any UNDEF components.
15038     if (LIdx < 0 || RIdx < 0 ||
15039         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15040         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15041       continue;
15042
15043     // Check that successive elements are being operated on.  If not, this is
15044     // not a horizontal operation.
15045     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15046     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15047     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15048     if (!(LIdx == Index && RIdx == Index + 1) &&
15049         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15050       return false;
15051   }
15052
15053   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15054   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15055   return true;
15056 }
15057
15058 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15059 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15060                                   const X86Subtarget *Subtarget) {
15061   EVT VT = N->getValueType(0);
15062   SDValue LHS = N->getOperand(0);
15063   SDValue RHS = N->getOperand(1);
15064
15065   // Try to synthesize horizontal adds from adds of shuffles.
15066   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15067        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15068       isHorizontalBinOp(LHS, RHS, true))
15069     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15070   return SDValue();
15071 }
15072
15073 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15074 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15075                                   const X86Subtarget *Subtarget) {
15076   EVT VT = N->getValueType(0);
15077   SDValue LHS = N->getOperand(0);
15078   SDValue RHS = N->getOperand(1);
15079
15080   // Try to synthesize horizontal subs from subs of shuffles.
15081   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15082        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15083       isHorizontalBinOp(LHS, RHS, false))
15084     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15085   return SDValue();
15086 }
15087
15088 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15089 /// X86ISD::FXOR nodes.
15090 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15091   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15092   // F[X]OR(0.0, x) -> x
15093   // F[X]OR(x, 0.0) -> x
15094   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15095     if (C->getValueAPF().isPosZero())
15096       return N->getOperand(1);
15097   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15098     if (C->getValueAPF().isPosZero())
15099       return N->getOperand(0);
15100   return SDValue();
15101 }
15102
15103 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15104 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15105   // FAND(0.0, x) -> 0.0
15106   // FAND(x, 0.0) -> 0.0
15107   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15108     if (C->getValueAPF().isPosZero())
15109       return N->getOperand(0);
15110   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15111     if (C->getValueAPF().isPosZero())
15112       return N->getOperand(1);
15113   return SDValue();
15114 }
15115
15116 static SDValue PerformBTCombine(SDNode *N,
15117                                 SelectionDAG &DAG,
15118                                 TargetLowering::DAGCombinerInfo &DCI) {
15119   // BT ignores high bits in the bit index operand.
15120   SDValue Op1 = N->getOperand(1);
15121   if (Op1.hasOneUse()) {
15122     unsigned BitWidth = Op1.getValueSizeInBits();
15123     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15124     APInt KnownZero, KnownOne;
15125     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15126                                           !DCI.isBeforeLegalizeOps());
15127     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15128     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15129         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15130       DCI.CommitTargetLoweringOpt(TLO);
15131   }
15132   return SDValue();
15133 }
15134
15135 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15136   SDValue Op = N->getOperand(0);
15137   if (Op.getOpcode() == ISD::BITCAST)
15138     Op = Op.getOperand(0);
15139   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15140   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15141       VT.getVectorElementType().getSizeInBits() ==
15142       OpVT.getVectorElementType().getSizeInBits()) {
15143     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15144   }
15145   return SDValue();
15146 }
15147
15148 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15149                                   TargetLowering::DAGCombinerInfo &DCI,
15150                                   const X86Subtarget *Subtarget) {
15151   if (!DCI.isBeforeLegalizeOps())
15152     return SDValue();
15153
15154   if (!Subtarget->hasAVX())
15155     return SDValue();
15156
15157   EVT VT = N->getValueType(0);
15158   SDValue Op = N->getOperand(0);
15159   EVT OpVT = Op.getValueType();
15160   DebugLoc dl = N->getDebugLoc();
15161
15162   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15163       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15164
15165     if (Subtarget->hasAVX2())
15166       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15167
15168     // Optimize vectors in AVX mode
15169     // Sign extend  v8i16 to v8i32 and
15170     //              v4i32 to v4i64
15171     //
15172     // Divide input vector into two parts
15173     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15174     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15175     // concat the vectors to original VT
15176
15177     unsigned NumElems = OpVT.getVectorNumElements();
15178     SmallVector<int,8> ShufMask1(NumElems, -1);
15179     for (unsigned i = 0; i != NumElems/2; ++i)
15180       ShufMask1[i] = i;
15181
15182     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15183                                         &ShufMask1[0]);
15184
15185     SmallVector<int,8> ShufMask2(NumElems, -1);
15186     for (unsigned i = 0; i != NumElems/2; ++i)
15187       ShufMask2[i] = i + NumElems/2;
15188
15189     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15190                                         &ShufMask2[0]);
15191
15192     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15193                                   VT.getVectorNumElements()/2);
15194
15195     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15196     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15197
15198     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15199   }
15200   return SDValue();
15201 }
15202
15203 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15204                                  const X86Subtarget* Subtarget) {
15205   DebugLoc dl = N->getDebugLoc();
15206   EVT VT = N->getValueType(0);
15207
15208   EVT ScalarVT = VT.getScalarType();
15209   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasFMA())
15210     return SDValue();
15211
15212   SDValue A = N->getOperand(0);
15213   SDValue B = N->getOperand(1);
15214   SDValue C = N->getOperand(2);
15215
15216   bool NegA = (A.getOpcode() == ISD::FNEG);
15217   bool NegB = (B.getOpcode() == ISD::FNEG);
15218   bool NegC = (C.getOpcode() == ISD::FNEG);
15219
15220   // Negative multiplication when NegA xor NegB
15221   bool NegMul = (NegA != NegB);
15222   if (NegA)
15223     A = A.getOperand(0);
15224   if (NegB)
15225     B = B.getOperand(0);
15226   if (NegC)
15227     C = C.getOperand(0);
15228
15229   unsigned Opcode;
15230   if (!NegMul)
15231     Opcode = (!NegC)? X86ISD::FMADD : X86ISD::FMSUB;
15232   else
15233     Opcode = (!NegC)? X86ISD::FNMADD : X86ISD::FNMSUB;
15234   return DAG.getNode(Opcode, dl, VT, A, B, C);
15235 }
15236
15237 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15238                                   TargetLowering::DAGCombinerInfo &DCI,
15239                                   const X86Subtarget *Subtarget) {
15240   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15241   //           (and (i32 x86isd::setcc_carry), 1)
15242   // This eliminates the zext. This transformation is necessary because
15243   // ISD::SETCC is always legalized to i8.
15244   DebugLoc dl = N->getDebugLoc();
15245   SDValue N0 = N->getOperand(0);
15246   EVT VT = N->getValueType(0);
15247   EVT OpVT = N0.getValueType();
15248
15249   if (N0.getOpcode() == ISD::AND &&
15250       N0.hasOneUse() &&
15251       N0.getOperand(0).hasOneUse()) {
15252     SDValue N00 = N0.getOperand(0);
15253     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15254       return SDValue();
15255     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15256     if (!C || C->getZExtValue() != 1)
15257       return SDValue();
15258     return DAG.getNode(ISD::AND, dl, VT,
15259                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15260                                    N00.getOperand(0), N00.getOperand(1)),
15261                        DAG.getConstant(1, VT));
15262   }
15263
15264   // Optimize vectors in AVX mode:
15265   //
15266   //   v8i16 -> v8i32
15267   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15268   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15269   //   Concat upper and lower parts.
15270   //
15271   //   v4i32 -> v4i64
15272   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15273   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15274   //   Concat upper and lower parts.
15275   //
15276   if (!DCI.isBeforeLegalizeOps())
15277     return SDValue();
15278
15279   if (!Subtarget->hasAVX())
15280     return SDValue();
15281
15282   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15283       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15284
15285     if (Subtarget->hasAVX2())
15286       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15287
15288     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15289     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15290     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15291
15292     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15293                                VT.getVectorNumElements()/2);
15294
15295     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15296     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15297
15298     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15299   }
15300
15301   return SDValue();
15302 }
15303
15304 // Optimize x == -y --> x+y == 0
15305 //          x != -y --> x+y != 0
15306 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15307   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15308   SDValue LHS = N->getOperand(0);
15309   SDValue RHS = N->getOperand(1);
15310
15311   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15312     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15313       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15314         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15315                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15316         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15317                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15318       }
15319   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15320     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15321       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15322         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15323                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15324         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15325                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15326       }
15327   return SDValue();
15328 }
15329
15330 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15331 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15332   DebugLoc DL = N->getDebugLoc();
15333   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15334   SDValue EFLAGS = N->getOperand(1);
15335
15336   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15337   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15338   // cases.
15339   if (CC == X86::COND_B)
15340     return DAG.getNode(ISD::AND, DL, MVT::i8,
15341                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15342                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
15343                        DAG.getConstant(1, MVT::i8));
15344
15345   SDValue Flags;
15346
15347   Flags = BoolTestSetCCCombine(EFLAGS, CC);
15348   if (Flags.getNode()) {
15349     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15350     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15351   }
15352
15353   return SDValue();
15354 }
15355
15356 // Optimize branch condition evaluation.
15357 //
15358 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15359                                     TargetLowering::DAGCombinerInfo &DCI,
15360                                     const X86Subtarget *Subtarget) {
15361   DebugLoc DL = N->getDebugLoc();
15362   SDValue Chain = N->getOperand(0);
15363   SDValue Dest = N->getOperand(1);
15364   SDValue EFLAGS = N->getOperand(3);
15365   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15366
15367   SDValue Flags;
15368
15369   Flags = BoolTestSetCCCombine(EFLAGS, CC);
15370   if (Flags.getNode()) {
15371     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15372     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15373                        Flags);
15374   }
15375
15376   return SDValue();
15377 }
15378
15379 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15380   SDValue Op0 = N->getOperand(0);
15381   EVT InVT = Op0->getValueType(0);
15382
15383   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15384   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15385     DebugLoc dl = N->getDebugLoc();
15386     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15387     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15388     // Notice that we use SINT_TO_FP because we know that the high bits
15389     // are zero and SINT_TO_FP is better supported by the hardware.
15390     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15391   }
15392
15393   return SDValue();
15394 }
15395
15396 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15397                                         const X86TargetLowering *XTLI) {
15398   SDValue Op0 = N->getOperand(0);
15399   EVT InVT = Op0->getValueType(0);
15400
15401   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15402   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15403     DebugLoc dl = N->getDebugLoc();
15404     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15405     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15406     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15407   }
15408
15409   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15410   // a 32-bit target where SSE doesn't support i64->FP operations.
15411   if (Op0.getOpcode() == ISD::LOAD) {
15412     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15413     EVT VT = Ld->getValueType(0);
15414     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15415         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15416         !XTLI->getSubtarget()->is64Bit() &&
15417         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15418       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15419                                           Ld->getChain(), Op0, DAG);
15420       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15421       return FILDChain;
15422     }
15423   }
15424   return SDValue();
15425 }
15426
15427 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15428   EVT VT = N->getValueType(0);
15429
15430   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15431   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15432     DebugLoc dl = N->getDebugLoc();
15433     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15434     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15435     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15436   }
15437
15438   return SDValue();
15439 }
15440
15441 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15442 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15443                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15444   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15445   // the result is either zero or one (depending on the input carry bit).
15446   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15447   if (X86::isZeroNode(N->getOperand(0)) &&
15448       X86::isZeroNode(N->getOperand(1)) &&
15449       // We don't have a good way to replace an EFLAGS use, so only do this when
15450       // dead right now.
15451       SDValue(N, 1).use_empty()) {
15452     DebugLoc DL = N->getDebugLoc();
15453     EVT VT = N->getValueType(0);
15454     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15455     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15456                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15457                                            DAG.getConstant(X86::COND_B,MVT::i8),
15458                                            N->getOperand(2)),
15459                                DAG.getConstant(1, VT));
15460     return DCI.CombineTo(N, Res1, CarryOut);
15461   }
15462
15463   return SDValue();
15464 }
15465
15466 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15467 //      (add Y, (setne X, 0)) -> sbb -1, Y
15468 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15469 //      (sub (setne X, 0), Y) -> adc -1, Y
15470 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15471   DebugLoc DL = N->getDebugLoc();
15472
15473   // Look through ZExts.
15474   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15475   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15476     return SDValue();
15477
15478   SDValue SetCC = Ext.getOperand(0);
15479   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15480     return SDValue();
15481
15482   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15483   if (CC != X86::COND_E && CC != X86::COND_NE)
15484     return SDValue();
15485
15486   SDValue Cmp = SetCC.getOperand(1);
15487   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15488       !X86::isZeroNode(Cmp.getOperand(1)) ||
15489       !Cmp.getOperand(0).getValueType().isInteger())
15490     return SDValue();
15491
15492   SDValue CmpOp0 = Cmp.getOperand(0);
15493   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15494                                DAG.getConstant(1, CmpOp0.getValueType()));
15495
15496   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15497   if (CC == X86::COND_NE)
15498     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15499                        DL, OtherVal.getValueType(), OtherVal,
15500                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15501   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15502                      DL, OtherVal.getValueType(), OtherVal,
15503                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15504 }
15505
15506 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15507 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15508                                  const X86Subtarget *Subtarget) {
15509   EVT VT = N->getValueType(0);
15510   SDValue Op0 = N->getOperand(0);
15511   SDValue Op1 = N->getOperand(1);
15512
15513   // Try to synthesize horizontal adds from adds of shuffles.
15514   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15515        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15516       isHorizontalBinOp(Op0, Op1, true))
15517     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15518
15519   return OptimizeConditionalInDecrement(N, DAG);
15520 }
15521
15522 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15523                                  const X86Subtarget *Subtarget) {
15524   SDValue Op0 = N->getOperand(0);
15525   SDValue Op1 = N->getOperand(1);
15526
15527   // X86 can't encode an immediate LHS of a sub. See if we can push the
15528   // negation into a preceding instruction.
15529   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15530     // If the RHS of the sub is a XOR with one use and a constant, invert the
15531     // immediate. Then add one to the LHS of the sub so we can turn
15532     // X-Y -> X+~Y+1, saving one register.
15533     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15534         isa<ConstantSDNode>(Op1.getOperand(1))) {
15535       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15536       EVT VT = Op0.getValueType();
15537       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15538                                    Op1.getOperand(0),
15539                                    DAG.getConstant(~XorC, VT));
15540       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15541                          DAG.getConstant(C->getAPIntValue()+1, VT));
15542     }
15543   }
15544
15545   // Try to synthesize horizontal adds from adds of shuffles.
15546   EVT VT = N->getValueType(0);
15547   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15548        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15549       isHorizontalBinOp(Op0, Op1, true))
15550     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15551
15552   return OptimizeConditionalInDecrement(N, DAG);
15553 }
15554
15555 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15556                                              DAGCombinerInfo &DCI) const {
15557   SelectionDAG &DAG = DCI.DAG;
15558   switch (N->getOpcode()) {
15559   default: break;
15560   case ISD::EXTRACT_VECTOR_ELT:
15561     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15562   case ISD::VSELECT:
15563   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15564   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
15565   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15566   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15567   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
15568   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
15569   case ISD::SHL:
15570   case ISD::SRA:
15571   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
15572   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
15573   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
15574   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
15575   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
15576   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
15577   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
15578   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
15579   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
15580   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
15581   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
15582   case X86ISD::FXOR:
15583   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
15584   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
15585   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
15586   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
15587   case ISD::ANY_EXTEND:
15588   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
15589   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
15590   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
15591   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
15592   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
15593   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
15594   case X86ISD::SHUFP:       // Handle all target specific shuffles
15595   case X86ISD::PALIGN:
15596   case X86ISD::UNPCKH:
15597   case X86ISD::UNPCKL:
15598   case X86ISD::MOVHLPS:
15599   case X86ISD::MOVLHPS:
15600   case X86ISD::PSHUFD:
15601   case X86ISD::PSHUFHW:
15602   case X86ISD::PSHUFLW:
15603   case X86ISD::MOVSS:
15604   case X86ISD::MOVSD:
15605   case X86ISD::VPERMILP:
15606   case X86ISD::VPERM2X128:
15607   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15608   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
15609   }
15610
15611   return SDValue();
15612 }
15613
15614 /// isTypeDesirableForOp - Return true if the target has native support for
15615 /// the specified value type and it is 'desirable' to use the type for the
15616 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15617 /// instruction encodings are longer and some i16 instructions are slow.
15618 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15619   if (!isTypeLegal(VT))
15620     return false;
15621   if (VT != MVT::i16)
15622     return true;
15623
15624   switch (Opc) {
15625   default:
15626     return true;
15627   case ISD::LOAD:
15628   case ISD::SIGN_EXTEND:
15629   case ISD::ZERO_EXTEND:
15630   case ISD::ANY_EXTEND:
15631   case ISD::SHL:
15632   case ISD::SRL:
15633   case ISD::SUB:
15634   case ISD::ADD:
15635   case ISD::MUL:
15636   case ISD::AND:
15637   case ISD::OR:
15638   case ISD::XOR:
15639     return false;
15640   }
15641 }
15642
15643 /// IsDesirableToPromoteOp - This method query the target whether it is
15644 /// beneficial for dag combiner to promote the specified node. If true, it
15645 /// should return the desired promotion type by reference.
15646 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15647   EVT VT = Op.getValueType();
15648   if (VT != MVT::i16)
15649     return false;
15650
15651   bool Promote = false;
15652   bool Commute = false;
15653   switch (Op.getOpcode()) {
15654   default: break;
15655   case ISD::LOAD: {
15656     LoadSDNode *LD = cast<LoadSDNode>(Op);
15657     // If the non-extending load has a single use and it's not live out, then it
15658     // might be folded.
15659     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15660                                                      Op.hasOneUse()*/) {
15661       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15662              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15663         // The only case where we'd want to promote LOAD (rather then it being
15664         // promoted as an operand is when it's only use is liveout.
15665         if (UI->getOpcode() != ISD::CopyToReg)
15666           return false;
15667       }
15668     }
15669     Promote = true;
15670     break;
15671   }
15672   case ISD::SIGN_EXTEND:
15673   case ISD::ZERO_EXTEND:
15674   case ISD::ANY_EXTEND:
15675     Promote = true;
15676     break;
15677   case ISD::SHL:
15678   case ISD::SRL: {
15679     SDValue N0 = Op.getOperand(0);
15680     // Look out for (store (shl (load), x)).
15681     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15682       return false;
15683     Promote = true;
15684     break;
15685   }
15686   case ISD::ADD:
15687   case ISD::MUL:
15688   case ISD::AND:
15689   case ISD::OR:
15690   case ISD::XOR:
15691     Commute = true;
15692     // fallthrough
15693   case ISD::SUB: {
15694     SDValue N0 = Op.getOperand(0);
15695     SDValue N1 = Op.getOperand(1);
15696     if (!Commute && MayFoldLoad(N1))
15697       return false;
15698     // Avoid disabling potential load folding opportunities.
15699     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15700       return false;
15701     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15702       return false;
15703     Promote = true;
15704   }
15705   }
15706
15707   PVT = MVT::i32;
15708   return Promote;
15709 }
15710
15711 //===----------------------------------------------------------------------===//
15712 //                           X86 Inline Assembly Support
15713 //===----------------------------------------------------------------------===//
15714
15715 namespace {
15716   // Helper to match a string separated by whitespace.
15717   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15718     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15719
15720     for (unsigned i = 0, e = args.size(); i != e; ++i) {
15721       StringRef piece(*args[i]);
15722       if (!s.startswith(piece)) // Check if the piece matches.
15723         return false;
15724
15725       s = s.substr(piece.size());
15726       StringRef::size_type pos = s.find_first_not_of(" \t");
15727       if (pos == 0) // We matched a prefix.
15728         return false;
15729
15730       s = s.substr(pos);
15731     }
15732
15733     return s.empty();
15734   }
15735   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15736 }
15737
15738 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15739   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15740
15741   std::string AsmStr = IA->getAsmString();
15742
15743   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15744   if (!Ty || Ty->getBitWidth() % 16 != 0)
15745     return false;
15746
15747   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15748   SmallVector<StringRef, 4> AsmPieces;
15749   SplitString(AsmStr, AsmPieces, ";\n");
15750
15751   switch (AsmPieces.size()) {
15752   default: return false;
15753   case 1:
15754     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15755     // we will turn this bswap into something that will be lowered to logical
15756     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
15757     // lower so don't worry about this.
15758     // bswap $0
15759     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15760         matchAsm(AsmPieces[0], "bswapl", "$0") ||
15761         matchAsm(AsmPieces[0], "bswapq", "$0") ||
15762         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15763         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15764         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15765       // No need to check constraints, nothing other than the equivalent of
15766       // "=r,0" would be valid here.
15767       return IntrinsicLowering::LowerToByteSwap(CI);
15768     }
15769
15770     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15771     if (CI->getType()->isIntegerTy(16) &&
15772         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15773         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15774          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15775       AsmPieces.clear();
15776       const std::string &ConstraintsStr = IA->getConstraintString();
15777       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15778       std::sort(AsmPieces.begin(), AsmPieces.end());
15779       if (AsmPieces.size() == 4 &&
15780           AsmPieces[0] == "~{cc}" &&
15781           AsmPieces[1] == "~{dirflag}" &&
15782           AsmPieces[2] == "~{flags}" &&
15783           AsmPieces[3] == "~{fpsr}")
15784       return IntrinsicLowering::LowerToByteSwap(CI);
15785     }
15786     break;
15787   case 3:
15788     if (CI->getType()->isIntegerTy(32) &&
15789         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15790         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15791         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15792         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15793       AsmPieces.clear();
15794       const std::string &ConstraintsStr = IA->getConstraintString();
15795       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15796       std::sort(AsmPieces.begin(), AsmPieces.end());
15797       if (AsmPieces.size() == 4 &&
15798           AsmPieces[0] == "~{cc}" &&
15799           AsmPieces[1] == "~{dirflag}" &&
15800           AsmPieces[2] == "~{flags}" &&
15801           AsmPieces[3] == "~{fpsr}")
15802         return IntrinsicLowering::LowerToByteSwap(CI);
15803     }
15804
15805     if (CI->getType()->isIntegerTy(64)) {
15806       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15807       if (Constraints.size() >= 2 &&
15808           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15809           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15810         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15811         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15812             matchAsm(AsmPieces[1], "bswap", "%edx") &&
15813             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15814           return IntrinsicLowering::LowerToByteSwap(CI);
15815       }
15816     }
15817     break;
15818   }
15819   return false;
15820 }
15821
15822
15823
15824 /// getConstraintType - Given a constraint letter, return the type of
15825 /// constraint it is for this target.
15826 X86TargetLowering::ConstraintType
15827 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15828   if (Constraint.size() == 1) {
15829     switch (Constraint[0]) {
15830     case 'R':
15831     case 'q':
15832     case 'Q':
15833     case 'f':
15834     case 't':
15835     case 'u':
15836     case 'y':
15837     case 'x':
15838     case 'Y':
15839     case 'l':
15840       return C_RegisterClass;
15841     case 'a':
15842     case 'b':
15843     case 'c':
15844     case 'd':
15845     case 'S':
15846     case 'D':
15847     case 'A':
15848       return C_Register;
15849     case 'I':
15850     case 'J':
15851     case 'K':
15852     case 'L':
15853     case 'M':
15854     case 'N':
15855     case 'G':
15856     case 'C':
15857     case 'e':
15858     case 'Z':
15859       return C_Other;
15860     default:
15861       break;
15862     }
15863   }
15864   return TargetLowering::getConstraintType(Constraint);
15865 }
15866
15867 /// Examine constraint type and operand type and determine a weight value.
15868 /// This object must already have been set up with the operand type
15869 /// and the current alternative constraint selected.
15870 TargetLowering::ConstraintWeight
15871   X86TargetLowering::getSingleConstraintMatchWeight(
15872     AsmOperandInfo &info, const char *constraint) const {
15873   ConstraintWeight weight = CW_Invalid;
15874   Value *CallOperandVal = info.CallOperandVal;
15875     // If we don't have a value, we can't do a match,
15876     // but allow it at the lowest weight.
15877   if (CallOperandVal == NULL)
15878     return CW_Default;
15879   Type *type = CallOperandVal->getType();
15880   // Look at the constraint type.
15881   switch (*constraint) {
15882   default:
15883     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15884   case 'R':
15885   case 'q':
15886   case 'Q':
15887   case 'a':
15888   case 'b':
15889   case 'c':
15890   case 'd':
15891   case 'S':
15892   case 'D':
15893   case 'A':
15894     if (CallOperandVal->getType()->isIntegerTy())
15895       weight = CW_SpecificReg;
15896     break;
15897   case 'f':
15898   case 't':
15899   case 'u':
15900       if (type->isFloatingPointTy())
15901         weight = CW_SpecificReg;
15902       break;
15903   case 'y':
15904       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15905         weight = CW_SpecificReg;
15906       break;
15907   case 'x':
15908   case 'Y':
15909     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15910         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15911       weight = CW_Register;
15912     break;
15913   case 'I':
15914     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15915       if (C->getZExtValue() <= 31)
15916         weight = CW_Constant;
15917     }
15918     break;
15919   case 'J':
15920     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15921       if (C->getZExtValue() <= 63)
15922         weight = CW_Constant;
15923     }
15924     break;
15925   case 'K':
15926     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15927       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15928         weight = CW_Constant;
15929     }
15930     break;
15931   case 'L':
15932     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15933       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15934         weight = CW_Constant;
15935     }
15936     break;
15937   case 'M':
15938     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15939       if (C->getZExtValue() <= 3)
15940         weight = CW_Constant;
15941     }
15942     break;
15943   case 'N':
15944     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15945       if (C->getZExtValue() <= 0xff)
15946         weight = CW_Constant;
15947     }
15948     break;
15949   case 'G':
15950   case 'C':
15951     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15952       weight = CW_Constant;
15953     }
15954     break;
15955   case 'e':
15956     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15957       if ((C->getSExtValue() >= -0x80000000LL) &&
15958           (C->getSExtValue() <= 0x7fffffffLL))
15959         weight = CW_Constant;
15960     }
15961     break;
15962   case 'Z':
15963     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15964       if (C->getZExtValue() <= 0xffffffff)
15965         weight = CW_Constant;
15966     }
15967     break;
15968   }
15969   return weight;
15970 }
15971
15972 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15973 /// with another that has more specific requirements based on the type of the
15974 /// corresponding operand.
15975 const char *X86TargetLowering::
15976 LowerXConstraint(EVT ConstraintVT) const {
15977   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15978   // 'f' like normal targets.
15979   if (ConstraintVT.isFloatingPoint()) {
15980     if (Subtarget->hasSSE2())
15981       return "Y";
15982     if (Subtarget->hasSSE1())
15983       return "x";
15984   }
15985
15986   return TargetLowering::LowerXConstraint(ConstraintVT);
15987 }
15988
15989 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15990 /// vector.  If it is invalid, don't add anything to Ops.
15991 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15992                                                      std::string &Constraint,
15993                                                      std::vector<SDValue>&Ops,
15994                                                      SelectionDAG &DAG) const {
15995   SDValue Result(0, 0);
15996
15997   // Only support length 1 constraints for now.
15998   if (Constraint.length() > 1) return;
15999
16000   char ConstraintLetter = Constraint[0];
16001   switch (ConstraintLetter) {
16002   default: break;
16003   case 'I':
16004     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16005       if (C->getZExtValue() <= 31) {
16006         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16007         break;
16008       }
16009     }
16010     return;
16011   case 'J':
16012     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16013       if (C->getZExtValue() <= 63) {
16014         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16015         break;
16016       }
16017     }
16018     return;
16019   case 'K':
16020     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16021       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16022         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16023         break;
16024       }
16025     }
16026     return;
16027   case 'N':
16028     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16029       if (C->getZExtValue() <= 255) {
16030         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16031         break;
16032       }
16033     }
16034     return;
16035   case 'e': {
16036     // 32-bit signed value
16037     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16038       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16039                                            C->getSExtValue())) {
16040         // Widen to 64 bits here to get it sign extended.
16041         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16042         break;
16043       }
16044     // FIXME gcc accepts some relocatable values here too, but only in certain
16045     // memory models; it's complicated.
16046     }
16047     return;
16048   }
16049   case 'Z': {
16050     // 32-bit unsigned value
16051     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16052       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16053                                            C->getZExtValue())) {
16054         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16055         break;
16056       }
16057     }
16058     // FIXME gcc accepts some relocatable values here too, but only in certain
16059     // memory models; it's complicated.
16060     return;
16061   }
16062   case 'i': {
16063     // Literal immediates are always ok.
16064     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16065       // Widen to 64 bits here to get it sign extended.
16066       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16067       break;
16068     }
16069
16070     // In any sort of PIC mode addresses need to be computed at runtime by
16071     // adding in a register or some sort of table lookup.  These can't
16072     // be used as immediates.
16073     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16074       return;
16075
16076     // If we are in non-pic codegen mode, we allow the address of a global (with
16077     // an optional displacement) to be used with 'i'.
16078     GlobalAddressSDNode *GA = 0;
16079     int64_t Offset = 0;
16080
16081     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16082     while (1) {
16083       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16084         Offset += GA->getOffset();
16085         break;
16086       } else if (Op.getOpcode() == ISD::ADD) {
16087         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16088           Offset += C->getZExtValue();
16089           Op = Op.getOperand(0);
16090           continue;
16091         }
16092       } else if (Op.getOpcode() == ISD::SUB) {
16093         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16094           Offset += -C->getZExtValue();
16095           Op = Op.getOperand(0);
16096           continue;
16097         }
16098       }
16099
16100       // Otherwise, this isn't something we can handle, reject it.
16101       return;
16102     }
16103
16104     const GlobalValue *GV = GA->getGlobal();
16105     // If we require an extra load to get this address, as in PIC mode, we
16106     // can't accept it.
16107     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16108                                                         getTargetMachine())))
16109       return;
16110
16111     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16112                                         GA->getValueType(0), Offset);
16113     break;
16114   }
16115   }
16116
16117   if (Result.getNode()) {
16118     Ops.push_back(Result);
16119     return;
16120   }
16121   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16122 }
16123
16124 std::pair<unsigned, const TargetRegisterClass*>
16125 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16126                                                 EVT VT) const {
16127   // First, see if this is a constraint that directly corresponds to an LLVM
16128   // register class.
16129   if (Constraint.size() == 1) {
16130     // GCC Constraint Letters
16131     switch (Constraint[0]) {
16132     default: break;
16133       // TODO: Slight differences here in allocation order and leaving
16134       // RIP in the class. Do they matter any more here than they do
16135       // in the normal allocation?
16136     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16137       if (Subtarget->is64Bit()) {
16138         if (VT == MVT::i32 || VT == MVT::f32)
16139           return std::make_pair(0U, &X86::GR32RegClass);
16140         if (VT == MVT::i16)
16141           return std::make_pair(0U, &X86::GR16RegClass);
16142         if (VT == MVT::i8 || VT == MVT::i1)
16143           return std::make_pair(0U, &X86::GR8RegClass);
16144         if (VT == MVT::i64 || VT == MVT::f64)
16145           return std::make_pair(0U, &X86::GR64RegClass);
16146         break;
16147       }
16148       // 32-bit fallthrough
16149     case 'Q':   // Q_REGS
16150       if (VT == MVT::i32 || VT == MVT::f32)
16151         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16152       if (VT == MVT::i16)
16153         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16154       if (VT == MVT::i8 || VT == MVT::i1)
16155         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16156       if (VT == MVT::i64)
16157         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16158       break;
16159     case 'r':   // GENERAL_REGS
16160     case 'l':   // INDEX_REGS
16161       if (VT == MVT::i8 || VT == MVT::i1)
16162         return std::make_pair(0U, &X86::GR8RegClass);
16163       if (VT == MVT::i16)
16164         return std::make_pair(0U, &X86::GR16RegClass);
16165       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16166         return std::make_pair(0U, &X86::GR32RegClass);
16167       return std::make_pair(0U, &X86::GR64RegClass);
16168     case 'R':   // LEGACY_REGS
16169       if (VT == MVT::i8 || VT == MVT::i1)
16170         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16171       if (VT == MVT::i16)
16172         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16173       if (VT == MVT::i32 || !Subtarget->is64Bit())
16174         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16175       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16176     case 'f':  // FP Stack registers.
16177       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16178       // value to the correct fpstack register class.
16179       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16180         return std::make_pair(0U, &X86::RFP32RegClass);
16181       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16182         return std::make_pair(0U, &X86::RFP64RegClass);
16183       return std::make_pair(0U, &X86::RFP80RegClass);
16184     case 'y':   // MMX_REGS if MMX allowed.
16185       if (!Subtarget->hasMMX()) break;
16186       return std::make_pair(0U, &X86::VR64RegClass);
16187     case 'Y':   // SSE_REGS if SSE2 allowed
16188       if (!Subtarget->hasSSE2()) break;
16189       // FALL THROUGH.
16190     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16191       if (!Subtarget->hasSSE1()) break;
16192
16193       switch (VT.getSimpleVT().SimpleTy) {
16194       default: break;
16195       // Scalar SSE types.
16196       case MVT::f32:
16197       case MVT::i32:
16198         return std::make_pair(0U, &X86::FR32RegClass);
16199       case MVT::f64:
16200       case MVT::i64:
16201         return std::make_pair(0U, &X86::FR64RegClass);
16202       // Vector types.
16203       case MVT::v16i8:
16204       case MVT::v8i16:
16205       case MVT::v4i32:
16206       case MVT::v2i64:
16207       case MVT::v4f32:
16208       case MVT::v2f64:
16209         return std::make_pair(0U, &X86::VR128RegClass);
16210       // AVX types.
16211       case MVT::v32i8:
16212       case MVT::v16i16:
16213       case MVT::v8i32:
16214       case MVT::v4i64:
16215       case MVT::v8f32:
16216       case MVT::v4f64:
16217         return std::make_pair(0U, &X86::VR256RegClass);
16218       }
16219       break;
16220     }
16221   }
16222
16223   // Use the default implementation in TargetLowering to convert the register
16224   // constraint into a member of a register class.
16225   std::pair<unsigned, const TargetRegisterClass*> Res;
16226   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16227
16228   // Not found as a standard register?
16229   if (Res.second == 0) {
16230     // Map st(0) -> st(7) -> ST0
16231     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16232         tolower(Constraint[1]) == 's' &&
16233         tolower(Constraint[2]) == 't' &&
16234         Constraint[3] == '(' &&
16235         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16236         Constraint[5] == ')' &&
16237         Constraint[6] == '}') {
16238
16239       Res.first = X86::ST0+Constraint[4]-'0';
16240       Res.second = &X86::RFP80RegClass;
16241       return Res;
16242     }
16243
16244     // GCC allows "st(0)" to be called just plain "st".
16245     if (StringRef("{st}").equals_lower(Constraint)) {
16246       Res.first = X86::ST0;
16247       Res.second = &X86::RFP80RegClass;
16248       return Res;
16249     }
16250
16251     // flags -> EFLAGS
16252     if (StringRef("{flags}").equals_lower(Constraint)) {
16253       Res.first = X86::EFLAGS;
16254       Res.second = &X86::CCRRegClass;
16255       return Res;
16256     }
16257
16258     // 'A' means EAX + EDX.
16259     if (Constraint == "A") {
16260       Res.first = X86::EAX;
16261       Res.second = &X86::GR32_ADRegClass;
16262       return Res;
16263     }
16264     return Res;
16265   }
16266
16267   // Otherwise, check to see if this is a register class of the wrong value
16268   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16269   // turn into {ax},{dx}.
16270   if (Res.second->hasType(VT))
16271     return Res;   // Correct type already, nothing to do.
16272
16273   // All of the single-register GCC register classes map their values onto
16274   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16275   // really want an 8-bit or 32-bit register, map to the appropriate register
16276   // class and return the appropriate register.
16277   if (Res.second == &X86::GR16RegClass) {
16278     if (VT == MVT::i8) {
16279       unsigned DestReg = 0;
16280       switch (Res.first) {
16281       default: break;
16282       case X86::AX: DestReg = X86::AL; break;
16283       case X86::DX: DestReg = X86::DL; break;
16284       case X86::CX: DestReg = X86::CL; break;
16285       case X86::BX: DestReg = X86::BL; break;
16286       }
16287       if (DestReg) {
16288         Res.first = DestReg;
16289         Res.second = &X86::GR8RegClass;
16290       }
16291     } else if (VT == MVT::i32) {
16292       unsigned DestReg = 0;
16293       switch (Res.first) {
16294       default: break;
16295       case X86::AX: DestReg = X86::EAX; break;
16296       case X86::DX: DestReg = X86::EDX; break;
16297       case X86::CX: DestReg = X86::ECX; break;
16298       case X86::BX: DestReg = X86::EBX; break;
16299       case X86::SI: DestReg = X86::ESI; break;
16300       case X86::DI: DestReg = X86::EDI; break;
16301       case X86::BP: DestReg = X86::EBP; break;
16302       case X86::SP: DestReg = X86::ESP; break;
16303       }
16304       if (DestReg) {
16305         Res.first = DestReg;
16306         Res.second = &X86::GR32RegClass;
16307       }
16308     } else if (VT == MVT::i64) {
16309       unsigned DestReg = 0;
16310       switch (Res.first) {
16311       default: break;
16312       case X86::AX: DestReg = X86::RAX; break;
16313       case X86::DX: DestReg = X86::RDX; break;
16314       case X86::CX: DestReg = X86::RCX; break;
16315       case X86::BX: DestReg = X86::RBX; break;
16316       case X86::SI: DestReg = X86::RSI; break;
16317       case X86::DI: DestReg = X86::RDI; break;
16318       case X86::BP: DestReg = X86::RBP; break;
16319       case X86::SP: DestReg = X86::RSP; break;
16320       }
16321       if (DestReg) {
16322         Res.first = DestReg;
16323         Res.second = &X86::GR64RegClass;
16324       }
16325     }
16326   } else if (Res.second == &X86::FR32RegClass ||
16327              Res.second == &X86::FR64RegClass ||
16328              Res.second == &X86::VR128RegClass) {
16329     // Handle references to XMM physical registers that got mapped into the
16330     // wrong class.  This can happen with constraints like {xmm0} where the
16331     // target independent register mapper will just pick the first match it can
16332     // find, ignoring the required type.
16333
16334     if (VT == MVT::f32 || VT == MVT::i32)
16335       Res.second = &X86::FR32RegClass;
16336     else if (VT == MVT::f64 || VT == MVT::i64)
16337       Res.second = &X86::FR64RegClass;
16338     else if (X86::VR128RegClass.hasType(VT))
16339       Res.second = &X86::VR128RegClass;
16340     else if (X86::VR256RegClass.hasType(VT))
16341       Res.second = &X86::VR256RegClass;
16342   }
16343
16344   return Res;
16345 }