Remove call to setOperationAction for SETCC of v4f32. SETCC returns an integer type...
[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     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
873     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
874     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
875     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
876     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
877
878     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
879     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
880       MVT VT = (MVT::SimpleValueType)i;
881       // Do not attempt to custom lower non-power-of-2 vectors
882       if (!isPowerOf2_32(VT.getVectorNumElements()))
883         continue;
884       // Do not attempt to custom lower non-128-bit vectors
885       if (!VT.is128BitVector())
886         continue;
887       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
888       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
889       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
890     }
891
892     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
893     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
894     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
895     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
896     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
897     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
898
899     if (Subtarget->is64Bit()) {
900       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
901       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
902     }
903
904     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
905     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
906       MVT VT = (MVT::SimpleValueType)i;
907
908       // Do not attempt to promote non-128-bit vectors
909       if (!VT.is128BitVector())
910         continue;
911
912       setOperationAction(ISD::AND,    VT, Promote);
913       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
914       setOperationAction(ISD::OR,     VT, Promote);
915       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
916       setOperationAction(ISD::XOR,    VT, Promote);
917       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
918       setOperationAction(ISD::LOAD,   VT, Promote);
919       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
920       setOperationAction(ISD::SELECT, VT, Promote);
921       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
922     }
923
924     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
925
926     // Custom lower v2i64 and v2f64 selects.
927     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
928     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
929     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
930     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
931
932     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
933     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
934   }
935
936   if (Subtarget->hasSSE41()) {
937     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
938     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
939     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
940     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
941     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
942     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
943     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
944     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
945     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
946     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
947
948     // FIXME: Do we need to handle scalar-to-vector here?
949     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
950
951     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
952     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
953     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
954     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
955     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
956
957     // i8 and i16 vectors are custom , because the source register and source
958     // source memory operand types are not the same width.  f32 vectors are
959     // custom since the immediate controlling the insert encodes additional
960     // information.
961     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
963     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
964     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
965
966     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
967     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
968     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
969     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
970
971     // FIXME: these should be Legal but thats only for the case where
972     // the index is constant.  For now custom expand to deal with that.
973     if (Subtarget->is64Bit()) {
974       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
975       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
976     }
977   }
978
979   if (Subtarget->hasSSE2()) {
980     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
981     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
982
983     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
984     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
985
986     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
987     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
988
989     if (Subtarget->hasAVX2()) {
990       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
991       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
992
993       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
994       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
995
996       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
997     } else {
998       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
999       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1000
1001       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1002       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1003
1004       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1005     }
1006   }
1007
1008   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1009     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1010     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1011     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1012     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1013     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1014     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1015
1016     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1017     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1018     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1019
1020     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1021     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1022     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1023     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1024     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1025     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1026
1027     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1028     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1029     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1030     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1031     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1032     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1033
1034     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1035     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1036     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1037
1038     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1039     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1040
1041     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1042     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1043
1044     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1045     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1046
1047     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1048     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1049     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1050     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1051
1052     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1053     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1054     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1055
1056     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1057     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1058     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1059     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1060
1061     if (Subtarget->hasFMA()) {
1062       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1063       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1064       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1065       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1066       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1067       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1068     }
1069
1070     if (Subtarget->hasAVX2()) {
1071       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1072       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1073       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1074       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1075
1076       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1077       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1078       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1079       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1080
1081       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1082       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1083       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1084       // Don't lower v32i8 because there is no 128-bit byte mul
1085
1086       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1087
1088       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1089       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1090
1091       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1092       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1093
1094       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1095     } else {
1096       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1097       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1098       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1099       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1100
1101       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1102       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1103       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1104       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1105
1106       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1107       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1108       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1109       // Don't lower v32i8 because there is no 128-bit byte mul
1110
1111       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1112       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1113
1114       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1115       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1116
1117       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1118     }
1119
1120     // Custom lower several nodes for 256-bit types.
1121     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1122              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1123       MVT VT = (MVT::SimpleValueType)i;
1124
1125       // Extract subvector is special because the value type
1126       // (result) is 128-bit but the source is 256-bit wide.
1127       if (VT.is128BitVector())
1128         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1129
1130       // Do not attempt to custom lower other non-256-bit vectors
1131       if (!VT.is256BitVector())
1132         continue;
1133
1134       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1135       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1136       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1137       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1138       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1139       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1140       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1141     }
1142
1143     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1144     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1145       MVT VT = (MVT::SimpleValueType)i;
1146
1147       // Do not attempt to promote non-256-bit vectors
1148       if (!VT.is256BitVector())
1149         continue;
1150
1151       setOperationAction(ISD::AND,    VT, Promote);
1152       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1153       setOperationAction(ISD::OR,     VT, Promote);
1154       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1155       setOperationAction(ISD::XOR,    VT, Promote);
1156       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1157       setOperationAction(ISD::LOAD,   VT, Promote);
1158       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1159       setOperationAction(ISD::SELECT, VT, Promote);
1160       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1161     }
1162   }
1163
1164   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1165   // of this type with custom code.
1166   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1167            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1168     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1169                        Custom);
1170   }
1171
1172   // We want to custom lower some of our intrinsics.
1173   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1174   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1175
1176
1177   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1178   // handle type legalization for these operations here.
1179   //
1180   // FIXME: We really should do custom legalization for addition and
1181   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1182   // than generic legalization for 64-bit multiplication-with-overflow, though.
1183   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1184     // Add/Sub/Mul with overflow operations are custom lowered.
1185     MVT VT = IntVTs[i];
1186     setOperationAction(ISD::SADDO, VT, Custom);
1187     setOperationAction(ISD::UADDO, VT, Custom);
1188     setOperationAction(ISD::SSUBO, VT, Custom);
1189     setOperationAction(ISD::USUBO, VT, Custom);
1190     setOperationAction(ISD::SMULO, VT, Custom);
1191     setOperationAction(ISD::UMULO, VT, Custom);
1192   }
1193
1194   // There are no 8-bit 3-address imul/mul instructions
1195   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1196   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1197
1198   if (!Subtarget->is64Bit()) {
1199     // These libcalls are not available in 32-bit.
1200     setLibcallName(RTLIB::SHL_I128, 0);
1201     setLibcallName(RTLIB::SRL_I128, 0);
1202     setLibcallName(RTLIB::SRA_I128, 0);
1203   }
1204
1205   // We have target-specific dag combine patterns for the following nodes:
1206   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1207   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1208   setTargetDAGCombine(ISD::VSELECT);
1209   setTargetDAGCombine(ISD::SELECT);
1210   setTargetDAGCombine(ISD::SHL);
1211   setTargetDAGCombine(ISD::SRA);
1212   setTargetDAGCombine(ISD::SRL);
1213   setTargetDAGCombine(ISD::OR);
1214   setTargetDAGCombine(ISD::AND);
1215   setTargetDAGCombine(ISD::ADD);
1216   setTargetDAGCombine(ISD::FADD);
1217   setTargetDAGCombine(ISD::FSUB);
1218   setTargetDAGCombine(ISD::FMA);
1219   setTargetDAGCombine(ISD::SUB);
1220   setTargetDAGCombine(ISD::LOAD);
1221   setTargetDAGCombine(ISD::STORE);
1222   setTargetDAGCombine(ISD::ZERO_EXTEND);
1223   setTargetDAGCombine(ISD::ANY_EXTEND);
1224   setTargetDAGCombine(ISD::SIGN_EXTEND);
1225   setTargetDAGCombine(ISD::TRUNCATE);
1226   setTargetDAGCombine(ISD::UINT_TO_FP);
1227   setTargetDAGCombine(ISD::SINT_TO_FP);
1228   setTargetDAGCombine(ISD::SETCC);
1229   setTargetDAGCombine(ISD::FP_TO_SINT);
1230   if (Subtarget->is64Bit())
1231     setTargetDAGCombine(ISD::MUL);
1232   setTargetDAGCombine(ISD::XOR);
1233
1234   computeRegisterProperties();
1235
1236   // On Darwin, -Os means optimize for size without hurting performance,
1237   // do not reduce the limit.
1238   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1239   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1240   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1241   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1242   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1243   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1244   setPrefLoopAlignment(4); // 2^4 bytes.
1245   benefitFromCodePlacementOpt = true;
1246
1247   // Predictable cmov don't hurt on atom because it's in-order.
1248   predictableSelectIsExpensive = !Subtarget->isAtom();
1249
1250   setPrefFunctionAlignment(4); // 2^4 bytes.
1251 }
1252
1253
1254 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1255   if (!VT.isVector()) return MVT::i8;
1256   return VT.changeVectorElementTypeToInteger();
1257 }
1258
1259
1260 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1261 /// the desired ByVal argument alignment.
1262 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1263   if (MaxAlign == 16)
1264     return;
1265   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1266     if (VTy->getBitWidth() == 128)
1267       MaxAlign = 16;
1268   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1269     unsigned EltAlign = 0;
1270     getMaxByValAlign(ATy->getElementType(), EltAlign);
1271     if (EltAlign > MaxAlign)
1272       MaxAlign = EltAlign;
1273   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1274     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1275       unsigned EltAlign = 0;
1276       getMaxByValAlign(STy->getElementType(i), EltAlign);
1277       if (EltAlign > MaxAlign)
1278         MaxAlign = EltAlign;
1279       if (MaxAlign == 16)
1280         break;
1281     }
1282   }
1283 }
1284
1285 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1286 /// function arguments in the caller parameter area. For X86, aggregates
1287 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1288 /// are at 4-byte boundaries.
1289 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1290   if (Subtarget->is64Bit()) {
1291     // Max of 8 and alignment of type.
1292     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1293     if (TyAlign > 8)
1294       return TyAlign;
1295     return 8;
1296   }
1297
1298   unsigned Align = 4;
1299   if (Subtarget->hasSSE1())
1300     getMaxByValAlign(Ty, Align);
1301   return Align;
1302 }
1303
1304 /// getOptimalMemOpType - Returns the target specific optimal type for load
1305 /// and store operations as a result of memset, memcpy, and memmove
1306 /// lowering. If DstAlign is zero that means it's safe to destination
1307 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1308 /// means there isn't a need to check it against alignment requirement,
1309 /// probably because the source does not need to be loaded. If
1310 /// 'IsZeroVal' is true, that means it's safe to return a
1311 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1312 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1313 /// constant so it does not need to be loaded.
1314 /// It returns EVT::Other if the type should be determined using generic
1315 /// target-independent logic.
1316 EVT
1317 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1318                                        unsigned DstAlign, unsigned SrcAlign,
1319                                        bool IsZeroVal,
1320                                        bool MemcpyStrSrc,
1321                                        MachineFunction &MF) const {
1322   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1323   // linux.  This is because the stack realignment code can't handle certain
1324   // cases like PR2962.  This should be removed when PR2962 is fixed.
1325   const Function *F = MF.getFunction();
1326   if (IsZeroVal &&
1327       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1328     if (Size >= 16 &&
1329         (Subtarget->isUnalignedMemAccessFast() ||
1330          ((DstAlign == 0 || DstAlign >= 16) &&
1331           (SrcAlign == 0 || SrcAlign >= 16))) &&
1332         Subtarget->getStackAlignment() >= 16) {
1333       if (Subtarget->getStackAlignment() >= 32) {
1334         if (Subtarget->hasAVX2())
1335           return MVT::v8i32;
1336         if (Subtarget->hasAVX())
1337           return MVT::v8f32;
1338       }
1339       if (Subtarget->hasSSE2())
1340         return MVT::v4i32;
1341       if (Subtarget->hasSSE1())
1342         return MVT::v4f32;
1343     } else if (!MemcpyStrSrc && Size >= 8 &&
1344                !Subtarget->is64Bit() &&
1345                Subtarget->getStackAlignment() >= 8 &&
1346                Subtarget->hasSSE2()) {
1347       // Do not use f64 to lower memcpy if source is string constant. It's
1348       // better to use i32 to avoid the loads.
1349       return MVT::f64;
1350     }
1351   }
1352   if (Subtarget->is64Bit() && Size >= 8)
1353     return MVT::i64;
1354   return MVT::i32;
1355 }
1356
1357 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1358 /// current function.  The returned value is a member of the
1359 /// MachineJumpTableInfo::JTEntryKind enum.
1360 unsigned X86TargetLowering::getJumpTableEncoding() const {
1361   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1362   // symbol.
1363   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1364       Subtarget->isPICStyleGOT())
1365     return MachineJumpTableInfo::EK_Custom32;
1366
1367   // Otherwise, use the normal jump table encoding heuristics.
1368   return TargetLowering::getJumpTableEncoding();
1369 }
1370
1371 const MCExpr *
1372 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1373                                              const MachineBasicBlock *MBB,
1374                                              unsigned uid,MCContext &Ctx) const{
1375   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1376          Subtarget->isPICStyleGOT());
1377   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1378   // entries.
1379   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1380                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1381 }
1382
1383 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1384 /// jumptable.
1385 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1386                                                     SelectionDAG &DAG) const {
1387   if (!Subtarget->is64Bit())
1388     // This doesn't have DebugLoc associated with it, but is not really the
1389     // same as a Register.
1390     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1391   return Table;
1392 }
1393
1394 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1395 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1396 /// MCExpr.
1397 const MCExpr *X86TargetLowering::
1398 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1399                              MCContext &Ctx) const {
1400   // X86-64 uses RIP relative addressing based on the jump table label.
1401   if (Subtarget->isPICStyleRIPRel())
1402     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1403
1404   // Otherwise, the reference is relative to the PIC base.
1405   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1406 }
1407
1408 // FIXME: Why this routine is here? Move to RegInfo!
1409 std::pair<const TargetRegisterClass*, uint8_t>
1410 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1411   const TargetRegisterClass *RRC = 0;
1412   uint8_t Cost = 1;
1413   switch (VT.getSimpleVT().SimpleTy) {
1414   default:
1415     return TargetLowering::findRepresentativeClass(VT);
1416   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1417     RRC = Subtarget->is64Bit() ?
1418       (const TargetRegisterClass*)&X86::GR64RegClass :
1419       (const TargetRegisterClass*)&X86::GR32RegClass;
1420     break;
1421   case MVT::x86mmx:
1422     RRC = &X86::VR64RegClass;
1423     break;
1424   case MVT::f32: case MVT::f64:
1425   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1426   case MVT::v4f32: case MVT::v2f64:
1427   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1428   case MVT::v4f64:
1429     RRC = &X86::VR128RegClass;
1430     break;
1431   }
1432   return std::make_pair(RRC, Cost);
1433 }
1434
1435 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1436                                                unsigned &Offset) const {
1437   if (!Subtarget->isTargetLinux())
1438     return false;
1439
1440   if (Subtarget->is64Bit()) {
1441     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1442     Offset = 0x28;
1443     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1444       AddressSpace = 256;
1445     else
1446       AddressSpace = 257;
1447   } else {
1448     // %gs:0x14 on i386
1449     Offset = 0x14;
1450     AddressSpace = 256;
1451   }
1452   return true;
1453 }
1454
1455
1456 //===----------------------------------------------------------------------===//
1457 //               Return Value Calling Convention Implementation
1458 //===----------------------------------------------------------------------===//
1459
1460 #include "X86GenCallingConv.inc"
1461
1462 bool
1463 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1464                                   MachineFunction &MF, bool isVarArg,
1465                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1466                         LLVMContext &Context) const {
1467   SmallVector<CCValAssign, 16> RVLocs;
1468   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1469                  RVLocs, Context);
1470   return CCInfo.CheckReturn(Outs, RetCC_X86);
1471 }
1472
1473 SDValue
1474 X86TargetLowering::LowerReturn(SDValue Chain,
1475                                CallingConv::ID CallConv, bool isVarArg,
1476                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1477                                const SmallVectorImpl<SDValue> &OutVals,
1478                                DebugLoc dl, SelectionDAG &DAG) const {
1479   MachineFunction &MF = DAG.getMachineFunction();
1480   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1481
1482   SmallVector<CCValAssign, 16> RVLocs;
1483   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1484                  RVLocs, *DAG.getContext());
1485   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1486
1487   // Add the regs to the liveout set for the function.
1488   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1489   for (unsigned i = 0; i != RVLocs.size(); ++i)
1490     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1491       MRI.addLiveOut(RVLocs[i].getLocReg());
1492
1493   SDValue Flag;
1494
1495   SmallVector<SDValue, 6> RetOps;
1496   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1497   // Operand #1 = Bytes To Pop
1498   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1499                    MVT::i16));
1500
1501   // Copy the result values into the output registers.
1502   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1503     CCValAssign &VA = RVLocs[i];
1504     assert(VA.isRegLoc() && "Can only return in registers!");
1505     SDValue ValToCopy = OutVals[i];
1506     EVT ValVT = ValToCopy.getValueType();
1507
1508     // Promote values to the appropriate types
1509     if (VA.getLocInfo() == CCValAssign::SExt)
1510       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1511     else if (VA.getLocInfo() == CCValAssign::ZExt)
1512       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1513     else if (VA.getLocInfo() == CCValAssign::AExt)
1514       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1515     else if (VA.getLocInfo() == CCValAssign::BCvt)
1516       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1517
1518     // If this is x86-64, and we disabled SSE, we can't return FP values,
1519     // or SSE or MMX vectors.
1520     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1521          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1522           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1523       report_fatal_error("SSE register return with SSE disabled");
1524     }
1525     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1526     // llvm-gcc has never done it right and no one has noticed, so this
1527     // should be OK for now.
1528     if (ValVT == MVT::f64 &&
1529         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1530       report_fatal_error("SSE2 register return with SSE2 disabled");
1531
1532     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1533     // the RET instruction and handled by the FP Stackifier.
1534     if (VA.getLocReg() == X86::ST0 ||
1535         VA.getLocReg() == X86::ST1) {
1536       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1537       // change the value to the FP stack register class.
1538       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1539         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1540       RetOps.push_back(ValToCopy);
1541       // Don't emit a copytoreg.
1542       continue;
1543     }
1544
1545     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1546     // which is returned in RAX / RDX.
1547     if (Subtarget->is64Bit()) {
1548       if (ValVT == MVT::x86mmx) {
1549         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1550           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1551           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1552                                   ValToCopy);
1553           // If we don't have SSE2 available, convert to v4f32 so the generated
1554           // register is legal.
1555           if (!Subtarget->hasSSE2())
1556             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1557         }
1558       }
1559     }
1560
1561     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1562     Flag = Chain.getValue(1);
1563   }
1564
1565   // The x86-64 ABI for returning structs by value requires that we copy
1566   // the sret argument into %rax for the return. We saved the argument into
1567   // a virtual register in the entry block, so now we copy the value out
1568   // and into %rax.
1569   if (Subtarget->is64Bit() &&
1570       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1571     MachineFunction &MF = DAG.getMachineFunction();
1572     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1573     unsigned Reg = FuncInfo->getSRetReturnReg();
1574     assert(Reg &&
1575            "SRetReturnReg should have been set in LowerFormalArguments().");
1576     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1577
1578     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1579     Flag = Chain.getValue(1);
1580
1581     // RAX now acts like a return value.
1582     MRI.addLiveOut(X86::RAX);
1583   }
1584
1585   RetOps[0] = Chain;  // Update chain.
1586
1587   // Add the flag if we have it.
1588   if (Flag.getNode())
1589     RetOps.push_back(Flag);
1590
1591   return DAG.getNode(X86ISD::RET_FLAG, dl,
1592                      MVT::Other, &RetOps[0], RetOps.size());
1593 }
1594
1595 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1596   if (N->getNumValues() != 1)
1597     return false;
1598   if (!N->hasNUsesOfValue(1, 0))
1599     return false;
1600
1601   SDValue TCChain = Chain;
1602   SDNode *Copy = *N->use_begin();
1603   if (Copy->getOpcode() == ISD::CopyToReg) {
1604     // If the copy has a glue operand, we conservatively assume it isn't safe to
1605     // perform a tail call.
1606     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1607       return false;
1608     TCChain = Copy->getOperand(0);
1609   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1610     return false;
1611
1612   bool HasRet = false;
1613   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1614        UI != UE; ++UI) {
1615     if (UI->getOpcode() != X86ISD::RET_FLAG)
1616       return false;
1617     HasRet = true;
1618   }
1619
1620   if (!HasRet)
1621     return false;
1622
1623   Chain = TCChain;
1624   return true;
1625 }
1626
1627 EVT
1628 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1629                                             ISD::NodeType ExtendKind) const {
1630   MVT ReturnMVT;
1631   // TODO: Is this also valid on 32-bit?
1632   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1633     ReturnMVT = MVT::i8;
1634   else
1635     ReturnMVT = MVT::i32;
1636
1637   EVT MinVT = getRegisterType(Context, ReturnMVT);
1638   return VT.bitsLT(MinVT) ? MinVT : VT;
1639 }
1640
1641 /// LowerCallResult - Lower the result values of a call into the
1642 /// appropriate copies out of appropriate physical registers.
1643 ///
1644 SDValue
1645 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1646                                    CallingConv::ID CallConv, bool isVarArg,
1647                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1648                                    DebugLoc dl, SelectionDAG &DAG,
1649                                    SmallVectorImpl<SDValue> &InVals) const {
1650
1651   // Assign locations to each value returned by this call.
1652   SmallVector<CCValAssign, 16> RVLocs;
1653   bool Is64Bit = Subtarget->is64Bit();
1654   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1655                  getTargetMachine(), RVLocs, *DAG.getContext());
1656   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1657
1658   // Copy all of the result registers out of their specified physreg.
1659   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1660     CCValAssign &VA = RVLocs[i];
1661     EVT CopyVT = VA.getValVT();
1662
1663     // If this is x86-64, and we disabled SSE, we can't return FP values
1664     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1665         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1666       report_fatal_error("SSE register return with SSE disabled");
1667     }
1668
1669     SDValue Val;
1670
1671     // If this is a call to a function that returns an fp value on the floating
1672     // point stack, we must guarantee the value is popped from the stack, so
1673     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1674     // if the return value is not used. We use the FpPOP_RETVAL instruction
1675     // instead.
1676     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1677       // If we prefer to use the value in xmm registers, copy it out as f80 and
1678       // use a truncate to move it from fp stack reg to xmm reg.
1679       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1680       SDValue Ops[] = { Chain, InFlag };
1681       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1682                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1683       Val = Chain.getValue(0);
1684
1685       // Round the f80 to the right size, which also moves it to the appropriate
1686       // xmm register.
1687       if (CopyVT != VA.getValVT())
1688         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1689                           // This truncation won't change the value.
1690                           DAG.getIntPtrConstant(1));
1691     } else {
1692       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1693                                  CopyVT, InFlag).getValue(1);
1694       Val = Chain.getValue(0);
1695     }
1696     InFlag = Chain.getValue(2);
1697     InVals.push_back(Val);
1698   }
1699
1700   return Chain;
1701 }
1702
1703
1704 //===----------------------------------------------------------------------===//
1705 //                C & StdCall & Fast Calling Convention implementation
1706 //===----------------------------------------------------------------------===//
1707 //  StdCall calling convention seems to be standard for many Windows' API
1708 //  routines and around. It differs from C calling convention just a little:
1709 //  callee should clean up the stack, not caller. Symbols should be also
1710 //  decorated in some fancy way :) It doesn't support any vector arguments.
1711 //  For info on fast calling convention see Fast Calling Convention (tail call)
1712 //  implementation LowerX86_32FastCCCallTo.
1713
1714 /// CallIsStructReturn - Determines whether a call uses struct return
1715 /// semantics.
1716 enum StructReturnType {
1717   NotStructReturn,
1718   RegStructReturn,
1719   StackStructReturn
1720 };
1721 static StructReturnType
1722 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1723   if (Outs.empty())
1724     return NotStructReturn;
1725
1726   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1727   if (!Flags.isSRet())
1728     return NotStructReturn;
1729   if (Flags.isInReg())
1730     return RegStructReturn;
1731   return StackStructReturn;
1732 }
1733
1734 /// ArgsAreStructReturn - Determines whether a function uses struct
1735 /// return semantics.
1736 static StructReturnType
1737 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1738   if (Ins.empty())
1739     return NotStructReturn;
1740
1741   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1742   if (!Flags.isSRet())
1743     return NotStructReturn;
1744   if (Flags.isInReg())
1745     return RegStructReturn;
1746   return StackStructReturn;
1747 }
1748
1749 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1750 /// by "Src" to address "Dst" with size and alignment information specified by
1751 /// the specific parameter attribute. The copy will be passed as a byval
1752 /// function parameter.
1753 static SDValue
1754 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1755                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1756                           DebugLoc dl) {
1757   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1758
1759   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1760                        /*isVolatile*/false, /*AlwaysInline=*/true,
1761                        MachinePointerInfo(), MachinePointerInfo());
1762 }
1763
1764 /// IsTailCallConvention - Return true if the calling convention is one that
1765 /// supports tail call optimization.
1766 static bool IsTailCallConvention(CallingConv::ID CC) {
1767   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1768 }
1769
1770 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1771   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1772     return false;
1773
1774   CallSite CS(CI);
1775   CallingConv::ID CalleeCC = CS.getCallingConv();
1776   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1777     return false;
1778
1779   return true;
1780 }
1781
1782 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1783 /// a tailcall target by changing its ABI.
1784 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1785                                    bool GuaranteedTailCallOpt) {
1786   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1787 }
1788
1789 SDValue
1790 X86TargetLowering::LowerMemArgument(SDValue Chain,
1791                                     CallingConv::ID CallConv,
1792                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1793                                     DebugLoc dl, SelectionDAG &DAG,
1794                                     const CCValAssign &VA,
1795                                     MachineFrameInfo *MFI,
1796                                     unsigned i) const {
1797   // Create the nodes corresponding to a load from this parameter slot.
1798   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1799   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1800                               getTargetMachine().Options.GuaranteedTailCallOpt);
1801   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1802   EVT ValVT;
1803
1804   // If value is passed by pointer we have address passed instead of the value
1805   // itself.
1806   if (VA.getLocInfo() == CCValAssign::Indirect)
1807     ValVT = VA.getLocVT();
1808   else
1809     ValVT = VA.getValVT();
1810
1811   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1812   // changed with more analysis.
1813   // In case of tail call optimization mark all arguments mutable. Since they
1814   // could be overwritten by lowering of arguments in case of a tail call.
1815   if (Flags.isByVal()) {
1816     unsigned Bytes = Flags.getByValSize();
1817     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1818     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1819     return DAG.getFrameIndex(FI, getPointerTy());
1820   } else {
1821     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1822                                     VA.getLocMemOffset(), isImmutable);
1823     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1824     return DAG.getLoad(ValVT, dl, Chain, FIN,
1825                        MachinePointerInfo::getFixedStack(FI),
1826                        false, false, false, 0);
1827   }
1828 }
1829
1830 SDValue
1831 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1832                                         CallingConv::ID CallConv,
1833                                         bool isVarArg,
1834                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1835                                         DebugLoc dl,
1836                                         SelectionDAG &DAG,
1837                                         SmallVectorImpl<SDValue> &InVals)
1838                                           const {
1839   MachineFunction &MF = DAG.getMachineFunction();
1840   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1841
1842   const Function* Fn = MF.getFunction();
1843   if (Fn->hasExternalLinkage() &&
1844       Subtarget->isTargetCygMing() &&
1845       Fn->getName() == "main")
1846     FuncInfo->setForceFramePointer(true);
1847
1848   MachineFrameInfo *MFI = MF.getFrameInfo();
1849   bool Is64Bit = Subtarget->is64Bit();
1850   bool IsWindows = Subtarget->isTargetWindows();
1851   bool IsWin64 = Subtarget->isTargetWin64();
1852
1853   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1854          "Var args not supported with calling convention fastcc or ghc");
1855
1856   // Assign locations to all of the incoming arguments.
1857   SmallVector<CCValAssign, 16> ArgLocs;
1858   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1859                  ArgLocs, *DAG.getContext());
1860
1861   // Allocate shadow area for Win64
1862   if (IsWin64) {
1863     CCInfo.AllocateStack(32, 8);
1864   }
1865
1866   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1867
1868   unsigned LastVal = ~0U;
1869   SDValue ArgValue;
1870   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1871     CCValAssign &VA = ArgLocs[i];
1872     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1873     // places.
1874     assert(VA.getValNo() != LastVal &&
1875            "Don't support value assigned to multiple locs yet");
1876     (void)LastVal;
1877     LastVal = VA.getValNo();
1878
1879     if (VA.isRegLoc()) {
1880       EVT RegVT = VA.getLocVT();
1881       const TargetRegisterClass *RC;
1882       if (RegVT == MVT::i32)
1883         RC = &X86::GR32RegClass;
1884       else if (Is64Bit && RegVT == MVT::i64)
1885         RC = &X86::GR64RegClass;
1886       else if (RegVT == MVT::f32)
1887         RC = &X86::FR32RegClass;
1888       else if (RegVT == MVT::f64)
1889         RC = &X86::FR64RegClass;
1890       else if (RegVT.is256BitVector())
1891         RC = &X86::VR256RegClass;
1892       else if (RegVT.is128BitVector())
1893         RC = &X86::VR128RegClass;
1894       else if (RegVT == MVT::x86mmx)
1895         RC = &X86::VR64RegClass;
1896       else
1897         llvm_unreachable("Unknown argument type!");
1898
1899       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1900       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1901
1902       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1903       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1904       // right size.
1905       if (VA.getLocInfo() == CCValAssign::SExt)
1906         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1907                                DAG.getValueType(VA.getValVT()));
1908       else if (VA.getLocInfo() == CCValAssign::ZExt)
1909         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1910                                DAG.getValueType(VA.getValVT()));
1911       else if (VA.getLocInfo() == CCValAssign::BCvt)
1912         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1913
1914       if (VA.isExtInLoc()) {
1915         // Handle MMX values passed in XMM regs.
1916         if (RegVT.isVector()) {
1917           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1918                                  ArgValue);
1919         } else
1920           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1921       }
1922     } else {
1923       assert(VA.isMemLoc());
1924       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1925     }
1926
1927     // If value is passed via pointer - do a load.
1928     if (VA.getLocInfo() == CCValAssign::Indirect)
1929       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1930                              MachinePointerInfo(), false, false, false, 0);
1931
1932     InVals.push_back(ArgValue);
1933   }
1934
1935   // The x86-64 ABI for returning structs by value requires that we copy
1936   // the sret argument into %rax for the return. Save the argument into
1937   // a virtual register so that we can access it from the return points.
1938   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1939     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1940     unsigned Reg = FuncInfo->getSRetReturnReg();
1941     if (!Reg) {
1942       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1943       FuncInfo->setSRetReturnReg(Reg);
1944     }
1945     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1946     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1947   }
1948
1949   unsigned StackSize = CCInfo.getNextStackOffset();
1950   // Align stack specially for tail calls.
1951   if (FuncIsMadeTailCallSafe(CallConv,
1952                              MF.getTarget().Options.GuaranteedTailCallOpt))
1953     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1954
1955   // If the function takes variable number of arguments, make a frame index for
1956   // the start of the first vararg value... for expansion of llvm.va_start.
1957   if (isVarArg) {
1958     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1959                     CallConv != CallingConv::X86_ThisCall)) {
1960       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1961     }
1962     if (Is64Bit) {
1963       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1964
1965       // FIXME: We should really autogenerate these arrays
1966       static const uint16_t GPR64ArgRegsWin64[] = {
1967         X86::RCX, X86::RDX, X86::R8,  X86::R9
1968       };
1969       static const uint16_t GPR64ArgRegs64Bit[] = {
1970         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1971       };
1972       static const uint16_t XMMArgRegs64Bit[] = {
1973         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1974         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1975       };
1976       const uint16_t *GPR64ArgRegs;
1977       unsigned NumXMMRegs = 0;
1978
1979       if (IsWin64) {
1980         // The XMM registers which might contain var arg parameters are shadowed
1981         // in their paired GPR.  So we only need to save the GPR to their home
1982         // slots.
1983         TotalNumIntRegs = 4;
1984         GPR64ArgRegs = GPR64ArgRegsWin64;
1985       } else {
1986         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1987         GPR64ArgRegs = GPR64ArgRegs64Bit;
1988
1989         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1990                                                 TotalNumXMMRegs);
1991       }
1992       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1993                                                        TotalNumIntRegs);
1994
1995       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1996       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1997              "SSE register cannot be used when SSE is disabled!");
1998       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1999                NoImplicitFloatOps) &&
2000              "SSE register cannot be used when SSE is disabled!");
2001       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2002           !Subtarget->hasSSE1())
2003         // Kernel mode asks for SSE to be disabled, so don't push them
2004         // on the stack.
2005         TotalNumXMMRegs = 0;
2006
2007       if (IsWin64) {
2008         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2009         // Get to the caller-allocated home save location.  Add 8 to account
2010         // for the return address.
2011         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2012         FuncInfo->setRegSaveFrameIndex(
2013           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2014         // Fixup to set vararg frame on shadow area (4 x i64).
2015         if (NumIntRegs < 4)
2016           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2017       } else {
2018         // For X86-64, if there are vararg parameters that are passed via
2019         // registers, then we must store them to their spots on the stack so
2020         // they may be loaded by deferencing the result of va_next.
2021         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2022         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2023         FuncInfo->setRegSaveFrameIndex(
2024           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2025                                false));
2026       }
2027
2028       // Store the integer parameter registers.
2029       SmallVector<SDValue, 8> MemOps;
2030       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2031                                         getPointerTy());
2032       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2033       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2034         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2035                                   DAG.getIntPtrConstant(Offset));
2036         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2037                                      &X86::GR64RegClass);
2038         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2039         SDValue Store =
2040           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2041                        MachinePointerInfo::getFixedStack(
2042                          FuncInfo->getRegSaveFrameIndex(), Offset),
2043                        false, false, 0);
2044         MemOps.push_back(Store);
2045         Offset += 8;
2046       }
2047
2048       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2049         // Now store the XMM (fp + vector) parameter registers.
2050         SmallVector<SDValue, 11> SaveXMMOps;
2051         SaveXMMOps.push_back(Chain);
2052
2053         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2054         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2055         SaveXMMOps.push_back(ALVal);
2056
2057         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2058                                FuncInfo->getRegSaveFrameIndex()));
2059         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2060                                FuncInfo->getVarArgsFPOffset()));
2061
2062         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2063           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2064                                        &X86::VR128RegClass);
2065           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2066           SaveXMMOps.push_back(Val);
2067         }
2068         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2069                                      MVT::Other,
2070                                      &SaveXMMOps[0], SaveXMMOps.size()));
2071       }
2072
2073       if (!MemOps.empty())
2074         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2075                             &MemOps[0], MemOps.size());
2076     }
2077   }
2078
2079   // Some CCs need callee pop.
2080   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2081                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2082     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2083   } else {
2084     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2085     // If this is an sret function, the return should pop the hidden pointer.
2086     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2087         argsAreStructReturn(Ins) == StackStructReturn)
2088       FuncInfo->setBytesToPopOnReturn(4);
2089   }
2090
2091   if (!Is64Bit) {
2092     // RegSaveFrameIndex is X86-64 only.
2093     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2094     if (CallConv == CallingConv::X86_FastCall ||
2095         CallConv == CallingConv::X86_ThisCall)
2096       // fastcc functions can't have varargs.
2097       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2098   }
2099
2100   FuncInfo->setArgumentStackSize(StackSize);
2101
2102   return Chain;
2103 }
2104
2105 SDValue
2106 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2107                                     SDValue StackPtr, SDValue Arg,
2108                                     DebugLoc dl, SelectionDAG &DAG,
2109                                     const CCValAssign &VA,
2110                                     ISD::ArgFlagsTy Flags) const {
2111   unsigned LocMemOffset = VA.getLocMemOffset();
2112   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2113   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2114   if (Flags.isByVal())
2115     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2116
2117   return DAG.getStore(Chain, dl, Arg, PtrOff,
2118                       MachinePointerInfo::getStack(LocMemOffset),
2119                       false, false, 0);
2120 }
2121
2122 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2123 /// optimization is performed and it is required.
2124 SDValue
2125 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2126                                            SDValue &OutRetAddr, SDValue Chain,
2127                                            bool IsTailCall, bool Is64Bit,
2128                                            int FPDiff, DebugLoc dl) const {
2129   // Adjust the Return address stack slot.
2130   EVT VT = getPointerTy();
2131   OutRetAddr = getReturnAddressFrameIndex(DAG);
2132
2133   // Load the "old" Return address.
2134   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2135                            false, false, false, 0);
2136   return SDValue(OutRetAddr.getNode(), 1);
2137 }
2138
2139 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2140 /// optimization is performed and it is required (FPDiff!=0).
2141 static SDValue
2142 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2143                          SDValue Chain, SDValue RetAddrFrIdx,
2144                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2145   // Store the return address to the appropriate stack slot.
2146   if (!FPDiff) return Chain;
2147   // Calculate the new stack slot for the return address.
2148   int SlotSize = Is64Bit ? 8 : 4;
2149   int NewReturnAddrFI =
2150     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2151   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2152   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2153   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2154                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2155                        false, false, 0);
2156   return Chain;
2157 }
2158
2159 SDValue
2160 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2161                              SmallVectorImpl<SDValue> &InVals) const {
2162   SelectionDAG &DAG                     = CLI.DAG;
2163   DebugLoc &dl                          = CLI.DL;
2164   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2165   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2166   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2167   SDValue Chain                         = CLI.Chain;
2168   SDValue Callee                        = CLI.Callee;
2169   CallingConv::ID CallConv              = CLI.CallConv;
2170   bool &isTailCall                      = CLI.IsTailCall;
2171   bool isVarArg                         = CLI.IsVarArg;
2172
2173   MachineFunction &MF = DAG.getMachineFunction();
2174   bool Is64Bit        = Subtarget->is64Bit();
2175   bool IsWin64        = Subtarget->isTargetWin64();
2176   bool IsWindows      = Subtarget->isTargetWindows();
2177   StructReturnType SR = callIsStructReturn(Outs);
2178   bool IsSibcall      = false;
2179
2180   if (MF.getTarget().Options.DisableTailCalls)
2181     isTailCall = false;
2182
2183   if (isTailCall) {
2184     // Check if it's really possible to do a tail call.
2185     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2186                     isVarArg, SR != NotStructReturn,
2187                     MF.getFunction()->hasStructRetAttr(),
2188                     Outs, OutVals, Ins, DAG);
2189
2190     // Sibcalls are automatically detected tailcalls which do not require
2191     // ABI changes.
2192     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2193       IsSibcall = true;
2194
2195     if (isTailCall)
2196       ++NumTailCalls;
2197   }
2198
2199   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2200          "Var args not supported with calling convention fastcc or ghc");
2201
2202   // Analyze operands of the call, assigning locations to each operand.
2203   SmallVector<CCValAssign, 16> ArgLocs;
2204   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2205                  ArgLocs, *DAG.getContext());
2206
2207   // Allocate shadow area for Win64
2208   if (IsWin64) {
2209     CCInfo.AllocateStack(32, 8);
2210   }
2211
2212   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2213
2214   // Get a count of how many bytes are to be pushed on the stack.
2215   unsigned NumBytes = CCInfo.getNextStackOffset();
2216   if (IsSibcall)
2217     // This is a sibcall. The memory operands are available in caller's
2218     // own caller's stack.
2219     NumBytes = 0;
2220   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2221            IsTailCallConvention(CallConv))
2222     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2223
2224   int FPDiff = 0;
2225   if (isTailCall && !IsSibcall) {
2226     // Lower arguments at fp - stackoffset + fpdiff.
2227     unsigned NumBytesCallerPushed =
2228       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2229     FPDiff = NumBytesCallerPushed - NumBytes;
2230
2231     // Set the delta of movement of the returnaddr stackslot.
2232     // But only set if delta is greater than previous delta.
2233     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2234       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2235   }
2236
2237   if (!IsSibcall)
2238     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2239
2240   SDValue RetAddrFrIdx;
2241   // Load return address for tail calls.
2242   if (isTailCall && FPDiff)
2243     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2244                                     Is64Bit, FPDiff, dl);
2245
2246   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2247   SmallVector<SDValue, 8> MemOpChains;
2248   SDValue StackPtr;
2249
2250   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2251   // of tail call optimization arguments are handle later.
2252   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2253     CCValAssign &VA = ArgLocs[i];
2254     EVT RegVT = VA.getLocVT();
2255     SDValue Arg = OutVals[i];
2256     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2257     bool isByVal = Flags.isByVal();
2258
2259     // Promote the value if needed.
2260     switch (VA.getLocInfo()) {
2261     default: llvm_unreachable("Unknown loc info!");
2262     case CCValAssign::Full: break;
2263     case CCValAssign::SExt:
2264       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2265       break;
2266     case CCValAssign::ZExt:
2267       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2268       break;
2269     case CCValAssign::AExt:
2270       if (RegVT.is128BitVector()) {
2271         // Special case: passing MMX values in XMM registers.
2272         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2273         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2274         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2275       } else
2276         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2277       break;
2278     case CCValAssign::BCvt:
2279       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2280       break;
2281     case CCValAssign::Indirect: {
2282       // Store the argument.
2283       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2284       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2285       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2286                            MachinePointerInfo::getFixedStack(FI),
2287                            false, false, 0);
2288       Arg = SpillSlot;
2289       break;
2290     }
2291     }
2292
2293     if (VA.isRegLoc()) {
2294       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2295       if (isVarArg && IsWin64) {
2296         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2297         // shadow reg if callee is a varargs function.
2298         unsigned ShadowReg = 0;
2299         switch (VA.getLocReg()) {
2300         case X86::XMM0: ShadowReg = X86::RCX; break;
2301         case X86::XMM1: ShadowReg = X86::RDX; break;
2302         case X86::XMM2: ShadowReg = X86::R8; break;
2303         case X86::XMM3: ShadowReg = X86::R9; break;
2304         }
2305         if (ShadowReg)
2306           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2307       }
2308     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2309       assert(VA.isMemLoc());
2310       if (StackPtr.getNode() == 0)
2311         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2312       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2313                                              dl, DAG, VA, Flags));
2314     }
2315   }
2316
2317   if (!MemOpChains.empty())
2318     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2319                         &MemOpChains[0], MemOpChains.size());
2320
2321   if (Subtarget->isPICStyleGOT()) {
2322     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2323     // GOT pointer.
2324     if (!isTailCall) {
2325       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2326                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2327     } else {
2328       // If we are tail calling and generating PIC/GOT style code load the
2329       // address of the callee into ECX. The value in ecx is used as target of
2330       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2331       // for tail calls on PIC/GOT architectures. Normally we would just put the
2332       // address of GOT into ebx and then call target@PLT. But for tail calls
2333       // ebx would be restored (since ebx is callee saved) before jumping to the
2334       // target@PLT.
2335
2336       // Note: The actual moving to ECX is done further down.
2337       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2338       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2339           !G->getGlobal()->hasProtectedVisibility())
2340         Callee = LowerGlobalAddress(Callee, DAG);
2341       else if (isa<ExternalSymbolSDNode>(Callee))
2342         Callee = LowerExternalSymbol(Callee, DAG);
2343     }
2344   }
2345
2346   if (Is64Bit && isVarArg && !IsWin64) {
2347     // From AMD64 ABI document:
2348     // For calls that may call functions that use varargs or stdargs
2349     // (prototype-less calls or calls to functions containing ellipsis (...) in
2350     // the declaration) %al is used as hidden argument to specify the number
2351     // of SSE registers used. The contents of %al do not need to match exactly
2352     // the number of registers, but must be an ubound on the number of SSE
2353     // registers used and is in the range 0 - 8 inclusive.
2354
2355     // Count the number of XMM registers allocated.
2356     static const uint16_t XMMArgRegs[] = {
2357       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2358       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2359     };
2360     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2361     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2362            && "SSE registers cannot be used when SSE is disabled");
2363
2364     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2365                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2366   }
2367
2368   // For tail calls lower the arguments to the 'real' stack slot.
2369   if (isTailCall) {
2370     // Force all the incoming stack arguments to be loaded from the stack
2371     // before any new outgoing arguments are stored to the stack, because the
2372     // outgoing stack slots may alias the incoming argument stack slots, and
2373     // the alias isn't otherwise explicit. This is slightly more conservative
2374     // than necessary, because it means that each store effectively depends
2375     // on every argument instead of just those arguments it would clobber.
2376     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2377
2378     SmallVector<SDValue, 8> MemOpChains2;
2379     SDValue FIN;
2380     int FI = 0;
2381     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2382       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2383         CCValAssign &VA = ArgLocs[i];
2384         if (VA.isRegLoc())
2385           continue;
2386         assert(VA.isMemLoc());
2387         SDValue Arg = OutVals[i];
2388         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2389         // Create frame index.
2390         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2391         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2392         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2393         FIN = DAG.getFrameIndex(FI, getPointerTy());
2394
2395         if (Flags.isByVal()) {
2396           // Copy relative to framepointer.
2397           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2398           if (StackPtr.getNode() == 0)
2399             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2400                                           getPointerTy());
2401           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2402
2403           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2404                                                            ArgChain,
2405                                                            Flags, DAG, dl));
2406         } else {
2407           // Store relative to framepointer.
2408           MemOpChains2.push_back(
2409             DAG.getStore(ArgChain, dl, Arg, FIN,
2410                          MachinePointerInfo::getFixedStack(FI),
2411                          false, false, 0));
2412         }
2413       }
2414     }
2415
2416     if (!MemOpChains2.empty())
2417       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2418                           &MemOpChains2[0], MemOpChains2.size());
2419
2420     // Store the return address to the appropriate stack slot.
2421     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2422                                      FPDiff, dl);
2423   }
2424
2425   // Build a sequence of copy-to-reg nodes chained together with token chain
2426   // and flag operands which copy the outgoing args into registers.
2427   SDValue InFlag;
2428   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2429     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2430                              RegsToPass[i].second, InFlag);
2431     InFlag = Chain.getValue(1);
2432   }
2433
2434   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2435     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2436     // In the 64-bit large code model, we have to make all calls
2437     // through a register, since the call instruction's 32-bit
2438     // pc-relative offset may not be large enough to hold the whole
2439     // address.
2440   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2441     // If the callee is a GlobalAddress node (quite common, every direct call
2442     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2443     // it.
2444
2445     // We should use extra load for direct calls to dllimported functions in
2446     // non-JIT mode.
2447     const GlobalValue *GV = G->getGlobal();
2448     if (!GV->hasDLLImportLinkage()) {
2449       unsigned char OpFlags = 0;
2450       bool ExtraLoad = false;
2451       unsigned WrapperKind = ISD::DELETED_NODE;
2452
2453       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2454       // external symbols most go through the PLT in PIC mode.  If the symbol
2455       // has hidden or protected visibility, or if it is static or local, then
2456       // we don't need to use the PLT - we can directly call it.
2457       if (Subtarget->isTargetELF() &&
2458           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2459           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2460         OpFlags = X86II::MO_PLT;
2461       } else if (Subtarget->isPICStyleStubAny() &&
2462                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2463                  (!Subtarget->getTargetTriple().isMacOSX() ||
2464                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2465         // PC-relative references to external symbols should go through $stub,
2466         // unless we're building with the leopard linker or later, which
2467         // automatically synthesizes these stubs.
2468         OpFlags = X86II::MO_DARWIN_STUB;
2469       } else if (Subtarget->isPICStyleRIPRel() &&
2470                  isa<Function>(GV) &&
2471                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2472         // If the function is marked as non-lazy, generate an indirect call
2473         // which loads from the GOT directly. This avoids runtime overhead
2474         // at the cost of eager binding (and one extra byte of encoding).
2475         OpFlags = X86II::MO_GOTPCREL;
2476         WrapperKind = X86ISD::WrapperRIP;
2477         ExtraLoad = true;
2478       }
2479
2480       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2481                                           G->getOffset(), OpFlags);
2482
2483       // Add a wrapper if needed.
2484       if (WrapperKind != ISD::DELETED_NODE)
2485         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2486       // Add extra indirection if needed.
2487       if (ExtraLoad)
2488         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2489                              MachinePointerInfo::getGOT(),
2490                              false, false, false, 0);
2491     }
2492   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2493     unsigned char OpFlags = 0;
2494
2495     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2496     // external symbols should go through the PLT.
2497     if (Subtarget->isTargetELF() &&
2498         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2499       OpFlags = X86II::MO_PLT;
2500     } else if (Subtarget->isPICStyleStubAny() &&
2501                (!Subtarget->getTargetTriple().isMacOSX() ||
2502                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2503       // PC-relative references to external symbols should go through $stub,
2504       // unless we're building with the leopard linker or later, which
2505       // automatically synthesizes these stubs.
2506       OpFlags = X86II::MO_DARWIN_STUB;
2507     }
2508
2509     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2510                                          OpFlags);
2511   }
2512
2513   // Returns a chain & a flag for retval copy to use.
2514   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2515   SmallVector<SDValue, 8> Ops;
2516
2517   if (!IsSibcall && isTailCall) {
2518     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2519                            DAG.getIntPtrConstant(0, true), InFlag);
2520     InFlag = Chain.getValue(1);
2521   }
2522
2523   Ops.push_back(Chain);
2524   Ops.push_back(Callee);
2525
2526   if (isTailCall)
2527     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2528
2529   // Add argument registers to the end of the list so that they are known live
2530   // into the call.
2531   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2532     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2533                                   RegsToPass[i].second.getValueType()));
2534
2535   // Add a register mask operand representing the call-preserved registers.
2536   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2537   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2538   assert(Mask && "Missing call preserved mask for calling convention");
2539   Ops.push_back(DAG.getRegisterMask(Mask));
2540
2541   if (InFlag.getNode())
2542     Ops.push_back(InFlag);
2543
2544   if (isTailCall) {
2545     // We used to do:
2546     //// If this is the first return lowered for this function, add the regs
2547     //// to the liveout set for the function.
2548     // This isn't right, although it's probably harmless on x86; liveouts
2549     // should be computed from returns not tail calls.  Consider a void
2550     // function making a tail call to a function returning int.
2551     return DAG.getNode(X86ISD::TC_RETURN, dl,
2552                        NodeTys, &Ops[0], Ops.size());
2553   }
2554
2555   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2556   InFlag = Chain.getValue(1);
2557
2558   // Create the CALLSEQ_END node.
2559   unsigned NumBytesForCalleeToPush;
2560   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2561                        getTargetMachine().Options.GuaranteedTailCallOpt))
2562     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2563   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2564            SR == StackStructReturn)
2565     // If this is a call to a struct-return function, the callee
2566     // pops the hidden struct pointer, so we have to push it back.
2567     // This is common for Darwin/X86, Linux & Mingw32 targets.
2568     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2569     NumBytesForCalleeToPush = 4;
2570   else
2571     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2572
2573   // Returns a flag for retval copy to use.
2574   if (!IsSibcall) {
2575     Chain = DAG.getCALLSEQ_END(Chain,
2576                                DAG.getIntPtrConstant(NumBytes, true),
2577                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2578                                                      true),
2579                                InFlag);
2580     InFlag = Chain.getValue(1);
2581   }
2582
2583   // Handle result values, copying them out of physregs into vregs that we
2584   // return.
2585   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2586                          Ins, dl, DAG, InVals);
2587 }
2588
2589
2590 //===----------------------------------------------------------------------===//
2591 //                Fast Calling Convention (tail call) implementation
2592 //===----------------------------------------------------------------------===//
2593
2594 //  Like std call, callee cleans arguments, convention except that ECX is
2595 //  reserved for storing the tail called function address. Only 2 registers are
2596 //  free for argument passing (inreg). Tail call optimization is performed
2597 //  provided:
2598 //                * tailcallopt is enabled
2599 //                * caller/callee are fastcc
2600 //  On X86_64 architecture with GOT-style position independent code only local
2601 //  (within module) calls are supported at the moment.
2602 //  To keep the stack aligned according to platform abi the function
2603 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2604 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2605 //  If a tail called function callee has more arguments than the caller the
2606 //  caller needs to make sure that there is room to move the RETADDR to. This is
2607 //  achieved by reserving an area the size of the argument delta right after the
2608 //  original REtADDR, but before the saved framepointer or the spilled registers
2609 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2610 //  stack layout:
2611 //    arg1
2612 //    arg2
2613 //    RETADDR
2614 //    [ new RETADDR
2615 //      move area ]
2616 //    (possible EBP)
2617 //    ESI
2618 //    EDI
2619 //    local1 ..
2620
2621 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2622 /// for a 16 byte align requirement.
2623 unsigned
2624 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2625                                                SelectionDAG& DAG) const {
2626   MachineFunction &MF = DAG.getMachineFunction();
2627   const TargetMachine &TM = MF.getTarget();
2628   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2629   unsigned StackAlignment = TFI.getStackAlignment();
2630   uint64_t AlignMask = StackAlignment - 1;
2631   int64_t Offset = StackSize;
2632   uint64_t SlotSize = TD->getPointerSize();
2633   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2634     // Number smaller than 12 so just add the difference.
2635     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2636   } else {
2637     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2638     Offset = ((~AlignMask) & Offset) + StackAlignment +
2639       (StackAlignment-SlotSize);
2640   }
2641   return Offset;
2642 }
2643
2644 /// MatchingStackOffset - Return true if the given stack call argument is
2645 /// already available in the same position (relatively) of the caller's
2646 /// incoming argument stack.
2647 static
2648 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2649                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2650                          const X86InstrInfo *TII) {
2651   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2652   int FI = INT_MAX;
2653   if (Arg.getOpcode() == ISD::CopyFromReg) {
2654     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2655     if (!TargetRegisterInfo::isVirtualRegister(VR))
2656       return false;
2657     MachineInstr *Def = MRI->getVRegDef(VR);
2658     if (!Def)
2659       return false;
2660     if (!Flags.isByVal()) {
2661       if (!TII->isLoadFromStackSlot(Def, FI))
2662         return false;
2663     } else {
2664       unsigned Opcode = Def->getOpcode();
2665       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2666           Def->getOperand(1).isFI()) {
2667         FI = Def->getOperand(1).getIndex();
2668         Bytes = Flags.getByValSize();
2669       } else
2670         return false;
2671     }
2672   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2673     if (Flags.isByVal())
2674       // ByVal argument is passed in as a pointer but it's now being
2675       // dereferenced. e.g.
2676       // define @foo(%struct.X* %A) {
2677       //   tail call @bar(%struct.X* byval %A)
2678       // }
2679       return false;
2680     SDValue Ptr = Ld->getBasePtr();
2681     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2682     if (!FINode)
2683       return false;
2684     FI = FINode->getIndex();
2685   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2686     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2687     FI = FINode->getIndex();
2688     Bytes = Flags.getByValSize();
2689   } else
2690     return false;
2691
2692   assert(FI != INT_MAX);
2693   if (!MFI->isFixedObjectIndex(FI))
2694     return false;
2695   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2696 }
2697
2698 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2699 /// for tail call optimization. Targets which want to do tail call
2700 /// optimization should implement this function.
2701 bool
2702 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2703                                                      CallingConv::ID CalleeCC,
2704                                                      bool isVarArg,
2705                                                      bool isCalleeStructRet,
2706                                                      bool isCallerStructRet,
2707                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2708                                     const SmallVectorImpl<SDValue> &OutVals,
2709                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2710                                                      SelectionDAG& DAG) const {
2711   if (!IsTailCallConvention(CalleeCC) &&
2712       CalleeCC != CallingConv::C)
2713     return false;
2714
2715   // If -tailcallopt is specified, make fastcc functions tail-callable.
2716   const MachineFunction &MF = DAG.getMachineFunction();
2717   const Function *CallerF = DAG.getMachineFunction().getFunction();
2718   CallingConv::ID CallerCC = CallerF->getCallingConv();
2719   bool CCMatch = CallerCC == CalleeCC;
2720
2721   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2722     if (IsTailCallConvention(CalleeCC) && CCMatch)
2723       return true;
2724     return false;
2725   }
2726
2727   // Look for obvious safe cases to perform tail call optimization that do not
2728   // require ABI changes. This is what gcc calls sibcall.
2729
2730   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2731   // emit a special epilogue.
2732   if (RegInfo->needsStackRealignment(MF))
2733     return false;
2734
2735   // Also avoid sibcall optimization if either caller or callee uses struct
2736   // return semantics.
2737   if (isCalleeStructRet || isCallerStructRet)
2738     return false;
2739
2740   // An stdcall caller is expected to clean up its arguments; the callee
2741   // isn't going to do that.
2742   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2743     return false;
2744
2745   // Do not sibcall optimize vararg calls unless all arguments are passed via
2746   // registers.
2747   if (isVarArg && !Outs.empty()) {
2748
2749     // Optimizing for varargs on Win64 is unlikely to be safe without
2750     // additional testing.
2751     if (Subtarget->isTargetWin64())
2752       return false;
2753
2754     SmallVector<CCValAssign, 16> ArgLocs;
2755     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2756                    getTargetMachine(), ArgLocs, *DAG.getContext());
2757
2758     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2759     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2760       if (!ArgLocs[i].isRegLoc())
2761         return false;
2762   }
2763
2764   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2765   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2766   // this into a sibcall.
2767   bool Unused = false;
2768   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2769     if (!Ins[i].Used) {
2770       Unused = true;
2771       break;
2772     }
2773   }
2774   if (Unused) {
2775     SmallVector<CCValAssign, 16> RVLocs;
2776     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2777                    getTargetMachine(), RVLocs, *DAG.getContext());
2778     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2779     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2780       CCValAssign &VA = RVLocs[i];
2781       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2782         return false;
2783     }
2784   }
2785
2786   // If the calling conventions do not match, then we'd better make sure the
2787   // results are returned in the same way as what the caller expects.
2788   if (!CCMatch) {
2789     SmallVector<CCValAssign, 16> RVLocs1;
2790     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2791                     getTargetMachine(), RVLocs1, *DAG.getContext());
2792     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2793
2794     SmallVector<CCValAssign, 16> RVLocs2;
2795     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2796                     getTargetMachine(), RVLocs2, *DAG.getContext());
2797     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2798
2799     if (RVLocs1.size() != RVLocs2.size())
2800       return false;
2801     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2802       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2803         return false;
2804       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2805         return false;
2806       if (RVLocs1[i].isRegLoc()) {
2807         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2808           return false;
2809       } else {
2810         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2811           return false;
2812       }
2813     }
2814   }
2815
2816   // If the callee takes no arguments then go on to check the results of the
2817   // call.
2818   if (!Outs.empty()) {
2819     // Check if stack adjustment is needed. For now, do not do this if any
2820     // argument is passed on the stack.
2821     SmallVector<CCValAssign, 16> ArgLocs;
2822     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2823                    getTargetMachine(), ArgLocs, *DAG.getContext());
2824
2825     // Allocate shadow area for Win64
2826     if (Subtarget->isTargetWin64()) {
2827       CCInfo.AllocateStack(32, 8);
2828     }
2829
2830     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2831     if (CCInfo.getNextStackOffset()) {
2832       MachineFunction &MF = DAG.getMachineFunction();
2833       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2834         return false;
2835
2836       // Check if the arguments are already laid out in the right way as
2837       // the caller's fixed stack objects.
2838       MachineFrameInfo *MFI = MF.getFrameInfo();
2839       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2840       const X86InstrInfo *TII =
2841         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2842       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2843         CCValAssign &VA = ArgLocs[i];
2844         SDValue Arg = OutVals[i];
2845         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2846         if (VA.getLocInfo() == CCValAssign::Indirect)
2847           return false;
2848         if (!VA.isRegLoc()) {
2849           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2850                                    MFI, MRI, TII))
2851             return false;
2852         }
2853       }
2854     }
2855
2856     // If the tailcall address may be in a register, then make sure it's
2857     // possible to register allocate for it. In 32-bit, the call address can
2858     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2859     // callee-saved registers are restored. These happen to be the same
2860     // registers used to pass 'inreg' arguments so watch out for those.
2861     if (!Subtarget->is64Bit() &&
2862         !isa<GlobalAddressSDNode>(Callee) &&
2863         !isa<ExternalSymbolSDNode>(Callee)) {
2864       unsigned NumInRegs = 0;
2865       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2866         CCValAssign &VA = ArgLocs[i];
2867         if (!VA.isRegLoc())
2868           continue;
2869         unsigned Reg = VA.getLocReg();
2870         switch (Reg) {
2871         default: break;
2872         case X86::EAX: case X86::EDX: case X86::ECX:
2873           if (++NumInRegs == 3)
2874             return false;
2875           break;
2876         }
2877       }
2878     }
2879   }
2880
2881   return true;
2882 }
2883
2884 FastISel *
2885 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2886                                   const TargetLibraryInfo *libInfo) const {
2887   return X86::createFastISel(funcInfo, libInfo);
2888 }
2889
2890
2891 //===----------------------------------------------------------------------===//
2892 //                           Other Lowering Hooks
2893 //===----------------------------------------------------------------------===//
2894
2895 static bool MayFoldLoad(SDValue Op) {
2896   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2897 }
2898
2899 static bool MayFoldIntoStore(SDValue Op) {
2900   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2901 }
2902
2903 static bool isTargetShuffle(unsigned Opcode) {
2904   switch(Opcode) {
2905   default: return false;
2906   case X86ISD::PSHUFD:
2907   case X86ISD::PSHUFHW:
2908   case X86ISD::PSHUFLW:
2909   case X86ISD::SHUFP:
2910   case X86ISD::PALIGN:
2911   case X86ISD::MOVLHPS:
2912   case X86ISD::MOVLHPD:
2913   case X86ISD::MOVHLPS:
2914   case X86ISD::MOVLPS:
2915   case X86ISD::MOVLPD:
2916   case X86ISD::MOVSHDUP:
2917   case X86ISD::MOVSLDUP:
2918   case X86ISD::MOVDDUP:
2919   case X86ISD::MOVSS:
2920   case X86ISD::MOVSD:
2921   case X86ISD::UNPCKL:
2922   case X86ISD::UNPCKH:
2923   case X86ISD::VPERMILP:
2924   case X86ISD::VPERM2X128:
2925   case X86ISD::VPERMI:
2926     return true;
2927   }
2928 }
2929
2930 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2931                                     SDValue V1, SelectionDAG &DAG) {
2932   switch(Opc) {
2933   default: llvm_unreachable("Unknown x86 shuffle node");
2934   case X86ISD::MOVSHDUP:
2935   case X86ISD::MOVSLDUP:
2936   case X86ISD::MOVDDUP:
2937     return DAG.getNode(Opc, dl, VT, V1);
2938   }
2939 }
2940
2941 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2942                                     SDValue V1, unsigned TargetMask,
2943                                     SelectionDAG &DAG) {
2944   switch(Opc) {
2945   default: llvm_unreachable("Unknown x86 shuffle node");
2946   case X86ISD::PSHUFD:
2947   case X86ISD::PSHUFHW:
2948   case X86ISD::PSHUFLW:
2949   case X86ISD::VPERMILP:
2950   case X86ISD::VPERMI:
2951     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2952   }
2953 }
2954
2955 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2956                                     SDValue V1, SDValue V2, unsigned TargetMask,
2957                                     SelectionDAG &DAG) {
2958   switch(Opc) {
2959   default: llvm_unreachable("Unknown x86 shuffle node");
2960   case X86ISD::PALIGN:
2961   case X86ISD::SHUFP:
2962   case X86ISD::VPERM2X128:
2963     return DAG.getNode(Opc, dl, VT, V1, V2,
2964                        DAG.getConstant(TargetMask, MVT::i8));
2965   }
2966 }
2967
2968 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2969                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2970   switch(Opc) {
2971   default: llvm_unreachable("Unknown x86 shuffle node");
2972   case X86ISD::MOVLHPS:
2973   case X86ISD::MOVLHPD:
2974   case X86ISD::MOVHLPS:
2975   case X86ISD::MOVLPS:
2976   case X86ISD::MOVLPD:
2977   case X86ISD::MOVSS:
2978   case X86ISD::MOVSD:
2979   case X86ISD::UNPCKL:
2980   case X86ISD::UNPCKH:
2981     return DAG.getNode(Opc, dl, VT, V1, V2);
2982   }
2983 }
2984
2985 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2986   MachineFunction &MF = DAG.getMachineFunction();
2987   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2988   int ReturnAddrIndex = FuncInfo->getRAIndex();
2989
2990   if (ReturnAddrIndex == 0) {
2991     // Set up a frame object for the return address.
2992     uint64_t SlotSize = TD->getPointerSize();
2993     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2994                                                            false);
2995     FuncInfo->setRAIndex(ReturnAddrIndex);
2996   }
2997
2998   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2999 }
3000
3001
3002 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3003                                        bool hasSymbolicDisplacement) {
3004   // Offset should fit into 32 bit immediate field.
3005   if (!isInt<32>(Offset))
3006     return false;
3007
3008   // If we don't have a symbolic displacement - we don't have any extra
3009   // restrictions.
3010   if (!hasSymbolicDisplacement)
3011     return true;
3012
3013   // FIXME: Some tweaks might be needed for medium code model.
3014   if (M != CodeModel::Small && M != CodeModel::Kernel)
3015     return false;
3016
3017   // For small code model we assume that latest object is 16MB before end of 31
3018   // bits boundary. We may also accept pretty large negative constants knowing
3019   // that all objects are in the positive half of address space.
3020   if (M == CodeModel::Small && Offset < 16*1024*1024)
3021     return true;
3022
3023   // For kernel code model we know that all object resist in the negative half
3024   // of 32bits address space. We may not accept negative offsets, since they may
3025   // be just off and we may accept pretty large positive ones.
3026   if (M == CodeModel::Kernel && Offset > 0)
3027     return true;
3028
3029   return false;
3030 }
3031
3032 /// isCalleePop - Determines whether the callee is required to pop its
3033 /// own arguments. Callee pop is necessary to support tail calls.
3034 bool X86::isCalleePop(CallingConv::ID CallingConv,
3035                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3036   if (IsVarArg)
3037     return false;
3038
3039   switch (CallingConv) {
3040   default:
3041     return false;
3042   case CallingConv::X86_StdCall:
3043     return !is64Bit;
3044   case CallingConv::X86_FastCall:
3045     return !is64Bit;
3046   case CallingConv::X86_ThisCall:
3047     return !is64Bit;
3048   case CallingConv::Fast:
3049     return TailCallOpt;
3050   case CallingConv::GHC:
3051     return TailCallOpt;
3052   }
3053 }
3054
3055 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3056 /// specific condition code, returning the condition code and the LHS/RHS of the
3057 /// comparison to make.
3058 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3059                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3060   if (!isFP) {
3061     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3062       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3063         // X > -1   -> X == 0, jump !sign.
3064         RHS = DAG.getConstant(0, RHS.getValueType());
3065         return X86::COND_NS;
3066       }
3067       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3068         // X < 0   -> X == 0, jump on sign.
3069         return X86::COND_S;
3070       }
3071       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3072         // X < 1   -> X <= 0
3073         RHS = DAG.getConstant(0, RHS.getValueType());
3074         return X86::COND_LE;
3075       }
3076     }
3077
3078     switch (SetCCOpcode) {
3079     default: llvm_unreachable("Invalid integer condition!");
3080     case ISD::SETEQ:  return X86::COND_E;
3081     case ISD::SETGT:  return X86::COND_G;
3082     case ISD::SETGE:  return X86::COND_GE;
3083     case ISD::SETLT:  return X86::COND_L;
3084     case ISD::SETLE:  return X86::COND_LE;
3085     case ISD::SETNE:  return X86::COND_NE;
3086     case ISD::SETULT: return X86::COND_B;
3087     case ISD::SETUGT: return X86::COND_A;
3088     case ISD::SETULE: return X86::COND_BE;
3089     case ISD::SETUGE: return X86::COND_AE;
3090     }
3091   }
3092
3093   // First determine if it is required or is profitable to flip the operands.
3094
3095   // If LHS is a foldable load, but RHS is not, flip the condition.
3096   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3097       !ISD::isNON_EXTLoad(RHS.getNode())) {
3098     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3099     std::swap(LHS, RHS);
3100   }
3101
3102   switch (SetCCOpcode) {
3103   default: break;
3104   case ISD::SETOLT:
3105   case ISD::SETOLE:
3106   case ISD::SETUGT:
3107   case ISD::SETUGE:
3108     std::swap(LHS, RHS);
3109     break;
3110   }
3111
3112   // On a floating point condition, the flags are set as follows:
3113   // ZF  PF  CF   op
3114   //  0 | 0 | 0 | X > Y
3115   //  0 | 0 | 1 | X < Y
3116   //  1 | 0 | 0 | X == Y
3117   //  1 | 1 | 1 | unordered
3118   switch (SetCCOpcode) {
3119   default: llvm_unreachable("Condcode should be pre-legalized away");
3120   case ISD::SETUEQ:
3121   case ISD::SETEQ:   return X86::COND_E;
3122   case ISD::SETOLT:              // flipped
3123   case ISD::SETOGT:
3124   case ISD::SETGT:   return X86::COND_A;
3125   case ISD::SETOLE:              // flipped
3126   case ISD::SETOGE:
3127   case ISD::SETGE:   return X86::COND_AE;
3128   case ISD::SETUGT:              // flipped
3129   case ISD::SETULT:
3130   case ISD::SETLT:   return X86::COND_B;
3131   case ISD::SETUGE:              // flipped
3132   case ISD::SETULE:
3133   case ISD::SETLE:   return X86::COND_BE;
3134   case ISD::SETONE:
3135   case ISD::SETNE:   return X86::COND_NE;
3136   case ISD::SETUO:   return X86::COND_P;
3137   case ISD::SETO:    return X86::COND_NP;
3138   case ISD::SETOEQ:
3139   case ISD::SETUNE:  return X86::COND_INVALID;
3140   }
3141 }
3142
3143 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3144 /// code. Current x86 isa includes the following FP cmov instructions:
3145 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3146 static bool hasFPCMov(unsigned X86CC) {
3147   switch (X86CC) {
3148   default:
3149     return false;
3150   case X86::COND_B:
3151   case X86::COND_BE:
3152   case X86::COND_E:
3153   case X86::COND_P:
3154   case X86::COND_A:
3155   case X86::COND_AE:
3156   case X86::COND_NE:
3157   case X86::COND_NP:
3158     return true;
3159   }
3160 }
3161
3162 /// isFPImmLegal - Returns true if the target can instruction select the
3163 /// specified FP immediate natively. If false, the legalizer will
3164 /// materialize the FP immediate as a load from a constant pool.
3165 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3166   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3167     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3168       return true;
3169   }
3170   return false;
3171 }
3172
3173 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3174 /// the specified range (L, H].
3175 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3176   return (Val < 0) || (Val >= Low && Val < Hi);
3177 }
3178
3179 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3180 /// specified value.
3181 static bool isUndefOrEqual(int Val, int CmpVal) {
3182   if (Val < 0 || Val == CmpVal)
3183     return true;
3184   return false;
3185 }
3186
3187 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3188 /// from position Pos and ending in Pos+Size, falls within the specified
3189 /// sequential range (L, L+Pos]. or is undef.
3190 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3191                                        unsigned Pos, unsigned Size, int Low) {
3192   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3193     if (!isUndefOrEqual(Mask[i], Low))
3194       return false;
3195   return true;
3196 }
3197
3198 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3199 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3200 /// the second operand.
3201 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3202   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3203     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3204   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3205     return (Mask[0] < 2 && Mask[1] < 2);
3206   return false;
3207 }
3208
3209 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3210 /// is suitable for input to PSHUFHW.
3211 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3212   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3213     return false;
3214
3215   // Lower quadword copied in order or undef.
3216   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3217     return false;
3218
3219   // Upper quadword shuffled.
3220   for (unsigned i = 4; i != 8; ++i)
3221     if (!isUndefOrInRange(Mask[i], 4, 8))
3222       return false;
3223
3224   if (VT == MVT::v16i16) {
3225     // Lower quadword copied in order or undef.
3226     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3227       return false;
3228
3229     // Upper quadword shuffled.
3230     for (unsigned i = 12; i != 16; ++i)
3231       if (!isUndefOrInRange(Mask[i], 12, 16))
3232         return false;
3233   }
3234
3235   return true;
3236 }
3237
3238 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3239 /// is suitable for input to PSHUFLW.
3240 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3241   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3242     return false;
3243
3244   // Upper quadword copied in order.
3245   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3246     return false;
3247
3248   // Lower quadword shuffled.
3249   for (unsigned i = 0; i != 4; ++i)
3250     if (!isUndefOrInRange(Mask[i], 0, 4))
3251       return false;
3252
3253   if (VT == MVT::v16i16) {
3254     // Upper quadword copied in order.
3255     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3256       return false;
3257
3258     // Lower quadword shuffled.
3259     for (unsigned i = 8; i != 12; ++i)
3260       if (!isUndefOrInRange(Mask[i], 8, 12))
3261         return false;
3262   }
3263
3264   return true;
3265 }
3266
3267 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3268 /// is suitable for input to PALIGNR.
3269 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3270                           const X86Subtarget *Subtarget) {
3271   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3272       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3273     return false;
3274
3275   unsigned NumElts = VT.getVectorNumElements();
3276   unsigned NumLanes = VT.getSizeInBits()/128;
3277   unsigned NumLaneElts = NumElts/NumLanes;
3278
3279   // Do not handle 64-bit element shuffles with palignr.
3280   if (NumLaneElts == 2)
3281     return false;
3282
3283   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3284     unsigned i;
3285     for (i = 0; i != NumLaneElts; ++i) {
3286       if (Mask[i+l] >= 0)
3287         break;
3288     }
3289
3290     // Lane is all undef, go to next lane
3291     if (i == NumLaneElts)
3292       continue;
3293
3294     int Start = Mask[i+l];
3295
3296     // Make sure its in this lane in one of the sources
3297     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3298         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3299       return false;
3300
3301     // If not lane 0, then we must match lane 0
3302     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3303       return false;
3304
3305     // Correct second source to be contiguous with first source
3306     if (Start >= (int)NumElts)
3307       Start -= NumElts - NumLaneElts;
3308
3309     // Make sure we're shifting in the right direction.
3310     if (Start <= (int)(i+l))
3311       return false;
3312
3313     Start -= i;
3314
3315     // Check the rest of the elements to see if they are consecutive.
3316     for (++i; i != NumLaneElts; ++i) {
3317       int Idx = Mask[i+l];
3318
3319       // Make sure its in this lane
3320       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3321           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3322         return false;
3323
3324       // If not lane 0, then we must match lane 0
3325       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3326         return false;
3327
3328       if (Idx >= (int)NumElts)
3329         Idx -= NumElts - NumLaneElts;
3330
3331       if (!isUndefOrEqual(Idx, Start+i))
3332         return false;
3333
3334     }
3335   }
3336
3337   return true;
3338 }
3339
3340 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3341 /// the two vector operands have swapped position.
3342 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3343                                      unsigned NumElems) {
3344   for (unsigned i = 0; i != NumElems; ++i) {
3345     int idx = Mask[i];
3346     if (idx < 0)
3347       continue;
3348     else if (idx < (int)NumElems)
3349       Mask[i] = idx + NumElems;
3350     else
3351       Mask[i] = idx - NumElems;
3352   }
3353 }
3354
3355 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3356 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3357 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3358 /// reverse of what x86 shuffles want.
3359 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3360                         bool Commuted = false) {
3361   if (!HasAVX && VT.getSizeInBits() == 256)
3362     return false;
3363
3364   unsigned NumElems = VT.getVectorNumElements();
3365   unsigned NumLanes = VT.getSizeInBits()/128;
3366   unsigned NumLaneElems = NumElems/NumLanes;
3367
3368   if (NumLaneElems != 2 && NumLaneElems != 4)
3369     return false;
3370
3371   // VSHUFPSY divides the resulting vector into 4 chunks.
3372   // The sources are also splitted into 4 chunks, and each destination
3373   // chunk must come from a different source chunk.
3374   //
3375   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3376   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3377   //
3378   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3379   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3380   //
3381   // VSHUFPDY divides the resulting vector into 4 chunks.
3382   // The sources are also splitted into 4 chunks, and each destination
3383   // chunk must come from a different source chunk.
3384   //
3385   //  SRC1 =>      X3       X2       X1       X0
3386   //  SRC2 =>      Y3       Y2       Y1       Y0
3387   //
3388   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3389   //
3390   unsigned HalfLaneElems = NumLaneElems/2;
3391   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3392     for (unsigned i = 0; i != NumLaneElems; ++i) {
3393       int Idx = Mask[i+l];
3394       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3395       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3396         return false;
3397       // For VSHUFPSY, the mask of the second half must be the same as the
3398       // first but with the appropriate offsets. This works in the same way as
3399       // VPERMILPS works with masks.
3400       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3401         continue;
3402       if (!isUndefOrEqual(Idx, Mask[i]+l))
3403         return false;
3404     }
3405   }
3406
3407   return true;
3408 }
3409
3410 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3411 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3412 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3413   if (!VT.is128BitVector())
3414     return false;
3415
3416   unsigned NumElems = VT.getVectorNumElements();
3417
3418   if (NumElems != 4)
3419     return false;
3420
3421   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3422   return isUndefOrEqual(Mask[0], 6) &&
3423          isUndefOrEqual(Mask[1], 7) &&
3424          isUndefOrEqual(Mask[2], 2) &&
3425          isUndefOrEqual(Mask[3], 3);
3426 }
3427
3428 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3429 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3430 /// <2, 3, 2, 3>
3431 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3432   if (!VT.is128BitVector())
3433     return false;
3434
3435   unsigned NumElems = VT.getVectorNumElements();
3436
3437   if (NumElems != 4)
3438     return false;
3439
3440   return isUndefOrEqual(Mask[0], 2) &&
3441          isUndefOrEqual(Mask[1], 3) &&
3442          isUndefOrEqual(Mask[2], 2) &&
3443          isUndefOrEqual(Mask[3], 3);
3444 }
3445
3446 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3447 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3448 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3449   if (!VT.is128BitVector())
3450     return false;
3451
3452   unsigned NumElems = VT.getVectorNumElements();
3453
3454   if (NumElems != 2 && NumElems != 4)
3455     return false;
3456
3457   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3458     if (!isUndefOrEqual(Mask[i], i + NumElems))
3459       return false;
3460
3461   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3462     if (!isUndefOrEqual(Mask[i], i))
3463       return false;
3464
3465   return true;
3466 }
3467
3468 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3469 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3470 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3471   if (!VT.is128BitVector())
3472     return false;
3473
3474   unsigned NumElems = VT.getVectorNumElements();
3475
3476   if (NumElems != 2 && NumElems != 4)
3477     return false;
3478
3479   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3480     if (!isUndefOrEqual(Mask[i], i))
3481       return false;
3482
3483   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3484     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3485       return false;
3486
3487   return true;
3488 }
3489
3490 //
3491 // Some special combinations that can be optimized.
3492 //
3493 static
3494 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3495                                SelectionDAG &DAG) {
3496   EVT VT = SVOp->getValueType(0);
3497   DebugLoc dl = SVOp->getDebugLoc();
3498
3499   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3500     return SDValue();
3501
3502   ArrayRef<int> Mask = SVOp->getMask();
3503
3504   // These are the special masks that may be optimized.
3505   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3506   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3507   bool MatchEvenMask = true;
3508   bool MatchOddMask  = true;
3509   for (int i=0; i<8; ++i) {
3510     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3511       MatchEvenMask = false;
3512     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3513       MatchOddMask = false;
3514   }
3515   static const int CompactionMaskEven[] = {0, 2, -1, -1, 4, 6, -1, -1};
3516   static const int CompactionMaskOdd [] = {1, 3, -1, -1, 5, 7, -1, -1};
3517
3518   const int *CompactionMask;
3519   if (MatchEvenMask)
3520     CompactionMask = CompactionMaskEven;
3521   else if (MatchOddMask)
3522     CompactionMask = CompactionMaskOdd;
3523   else
3524     return SDValue();
3525
3526   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3527
3528   SDValue Op0 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(0),
3529                                      UndefNode, CompactionMask);
3530   SDValue Op1 = DAG.getVectorShuffle(VT, dl, SVOp->getOperand(1),
3531                                      UndefNode, CompactionMask);
3532   static const int UnpackMask[] = {0, 8, 1, 9, 4, 12, 5, 13};
3533   return DAG.getVectorShuffle(VT, dl, Op0, Op1, UnpackMask);
3534 }
3535
3536 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3537 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3538 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3539                          bool HasAVX2, bool V2IsSplat = false) {
3540   unsigned NumElts = VT.getVectorNumElements();
3541
3542   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3543          "Unsupported vector type for unpckh");
3544
3545   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3546       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3547     return false;
3548
3549   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3550   // independently on 128-bit lanes.
3551   unsigned NumLanes = VT.getSizeInBits()/128;
3552   unsigned NumLaneElts = NumElts/NumLanes;
3553
3554   for (unsigned l = 0; l != NumLanes; ++l) {
3555     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3556          i != (l+1)*NumLaneElts;
3557          i += 2, ++j) {
3558       int BitI  = Mask[i];
3559       int BitI1 = Mask[i+1];
3560       if (!isUndefOrEqual(BitI, j))
3561         return false;
3562       if (V2IsSplat) {
3563         if (!isUndefOrEqual(BitI1, NumElts))
3564           return false;
3565       } else {
3566         if (!isUndefOrEqual(BitI1, j + NumElts))
3567           return false;
3568       }
3569     }
3570   }
3571
3572   return true;
3573 }
3574
3575 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3576 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3577 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3578                          bool HasAVX2, bool V2IsSplat = false) {
3579   unsigned NumElts = VT.getVectorNumElements();
3580
3581   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3582          "Unsupported vector type for unpckh");
3583
3584   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3585       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3586     return false;
3587
3588   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3589   // independently on 128-bit lanes.
3590   unsigned NumLanes = VT.getSizeInBits()/128;
3591   unsigned NumLaneElts = NumElts/NumLanes;
3592
3593   for (unsigned l = 0; l != NumLanes; ++l) {
3594     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3595          i != (l+1)*NumLaneElts; i += 2, ++j) {
3596       int BitI  = Mask[i];
3597       int BitI1 = Mask[i+1];
3598       if (!isUndefOrEqual(BitI, j))
3599         return false;
3600       if (V2IsSplat) {
3601         if (isUndefOrEqual(BitI1, NumElts))
3602           return false;
3603       } else {
3604         if (!isUndefOrEqual(BitI1, j+NumElts))
3605           return false;
3606       }
3607     }
3608   }
3609   return true;
3610 }
3611
3612 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3613 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3614 /// <0, 0, 1, 1>
3615 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3616                                   bool HasAVX2) {
3617   unsigned NumElts = VT.getVectorNumElements();
3618
3619   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3620          "Unsupported vector type for unpckh");
3621
3622   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3623       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3624     return false;
3625
3626   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3627   // FIXME: Need a better way to get rid of this, there's no latency difference
3628   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3629   // the former later. We should also remove the "_undef" special mask.
3630   if (NumElts == 4 && VT.getSizeInBits() == 256)
3631     return false;
3632
3633   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3634   // independently on 128-bit lanes.
3635   unsigned NumLanes = VT.getSizeInBits()/128;
3636   unsigned NumLaneElts = NumElts/NumLanes;
3637
3638   for (unsigned l = 0; l != NumLanes; ++l) {
3639     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3640          i != (l+1)*NumLaneElts;
3641          i += 2, ++j) {
3642       int BitI  = Mask[i];
3643       int BitI1 = Mask[i+1];
3644
3645       if (!isUndefOrEqual(BitI, j))
3646         return false;
3647       if (!isUndefOrEqual(BitI1, j))
3648         return false;
3649     }
3650   }
3651
3652   return true;
3653 }
3654
3655 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3656 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3657 /// <2, 2, 3, 3>
3658 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3659   unsigned NumElts = VT.getVectorNumElements();
3660
3661   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3662          "Unsupported vector type for unpckh");
3663
3664   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3665       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3666     return false;
3667
3668   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3669   // independently on 128-bit lanes.
3670   unsigned NumLanes = VT.getSizeInBits()/128;
3671   unsigned NumLaneElts = NumElts/NumLanes;
3672
3673   for (unsigned l = 0; l != NumLanes; ++l) {
3674     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3675          i != (l+1)*NumLaneElts; i += 2, ++j) {
3676       int BitI  = Mask[i];
3677       int BitI1 = Mask[i+1];
3678       if (!isUndefOrEqual(BitI, j))
3679         return false;
3680       if (!isUndefOrEqual(BitI1, j))
3681         return false;
3682     }
3683   }
3684   return true;
3685 }
3686
3687 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3688 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3689 /// MOVSD, and MOVD, i.e. setting the lowest element.
3690 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3691   if (VT.getVectorElementType().getSizeInBits() < 32)
3692     return false;
3693   if (!VT.is128BitVector())
3694     return false;
3695
3696   unsigned NumElts = VT.getVectorNumElements();
3697
3698   if (!isUndefOrEqual(Mask[0], NumElts))
3699     return false;
3700
3701   for (unsigned i = 1; i != NumElts; ++i)
3702     if (!isUndefOrEqual(Mask[i], i))
3703       return false;
3704
3705   return true;
3706 }
3707
3708 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3709 /// as permutations between 128-bit chunks or halves. As an example: this
3710 /// shuffle bellow:
3711 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3712 /// The first half comes from the second half of V1 and the second half from the
3713 /// the second half of V2.
3714 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3715   if (!HasAVX || !VT.is256BitVector())
3716     return false;
3717
3718   // The shuffle result is divided into half A and half B. In total the two
3719   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3720   // B must come from C, D, E or F.
3721   unsigned HalfSize = VT.getVectorNumElements()/2;
3722   bool MatchA = false, MatchB = false;
3723
3724   // Check if A comes from one of C, D, E, F.
3725   for (unsigned Half = 0; Half != 4; ++Half) {
3726     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3727       MatchA = true;
3728       break;
3729     }
3730   }
3731
3732   // Check if B comes from one of C, D, E, F.
3733   for (unsigned Half = 0; Half != 4; ++Half) {
3734     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3735       MatchB = true;
3736       break;
3737     }
3738   }
3739
3740   return MatchA && MatchB;
3741 }
3742
3743 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3744 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3745 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3746   EVT VT = SVOp->getValueType(0);
3747
3748   unsigned HalfSize = VT.getVectorNumElements()/2;
3749
3750   unsigned FstHalf = 0, SndHalf = 0;
3751   for (unsigned i = 0; i < HalfSize; ++i) {
3752     if (SVOp->getMaskElt(i) > 0) {
3753       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3754       break;
3755     }
3756   }
3757   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3758     if (SVOp->getMaskElt(i) > 0) {
3759       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3760       break;
3761     }
3762   }
3763
3764   return (FstHalf | (SndHalf << 4));
3765 }
3766
3767 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3768 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3769 /// Note that VPERMIL mask matching is different depending whether theunderlying
3770 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3771 /// to the same elements of the low, but to the higher half of the source.
3772 /// In VPERMILPD the two lanes could be shuffled independently of each other
3773 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3774 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3775   if (!HasAVX)
3776     return false;
3777
3778   unsigned NumElts = VT.getVectorNumElements();
3779   // Only match 256-bit with 32/64-bit types
3780   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3781     return false;
3782
3783   unsigned NumLanes = VT.getSizeInBits()/128;
3784   unsigned LaneSize = NumElts/NumLanes;
3785   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3786     for (unsigned i = 0; i != LaneSize; ++i) {
3787       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3788         return false;
3789       if (NumElts != 8 || l == 0)
3790         continue;
3791       // VPERMILPS handling
3792       if (Mask[i] < 0)
3793         continue;
3794       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3795         return false;
3796     }
3797   }
3798
3799   return true;
3800 }
3801
3802 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3803 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3804 /// element of vector 2 and the other elements to come from vector 1 in order.
3805 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3806                                bool V2IsSplat = false, bool V2IsUndef = false) {
3807   if (!VT.is128BitVector())
3808     return false;
3809
3810   unsigned NumOps = VT.getVectorNumElements();
3811   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3812     return false;
3813
3814   if (!isUndefOrEqual(Mask[0], 0))
3815     return false;
3816
3817   for (unsigned i = 1; i != NumOps; ++i)
3818     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3819           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3820           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3821       return false;
3822
3823   return true;
3824 }
3825
3826 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3827 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3828 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3829 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3830                            const X86Subtarget *Subtarget) {
3831   if (!Subtarget->hasSSE3())
3832     return false;
3833
3834   unsigned NumElems = VT.getVectorNumElements();
3835
3836   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3837       (VT.getSizeInBits() == 256 && NumElems != 8))
3838     return false;
3839
3840   // "i+1" is the value the indexed mask element must have
3841   for (unsigned i = 0; i != NumElems; i += 2)
3842     if (!isUndefOrEqual(Mask[i], i+1) ||
3843         !isUndefOrEqual(Mask[i+1], i+1))
3844       return false;
3845
3846   return true;
3847 }
3848
3849 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3850 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3851 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3852 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3853                            const X86Subtarget *Subtarget) {
3854   if (!Subtarget->hasSSE3())
3855     return false;
3856
3857   unsigned NumElems = VT.getVectorNumElements();
3858
3859   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3860       (VT.getSizeInBits() == 256 && NumElems != 8))
3861     return false;
3862
3863   // "i" is the value the indexed mask element must have
3864   for (unsigned i = 0; i != NumElems; i += 2)
3865     if (!isUndefOrEqual(Mask[i], i) ||
3866         !isUndefOrEqual(Mask[i+1], i))
3867       return false;
3868
3869   return true;
3870 }
3871
3872 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3873 /// specifies a shuffle of elements that is suitable for input to 256-bit
3874 /// version of MOVDDUP.
3875 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3876   if (!HasAVX || !VT.is256BitVector())
3877     return false;
3878
3879   unsigned NumElts = VT.getVectorNumElements();
3880   if (NumElts != 4)
3881     return false;
3882
3883   for (unsigned i = 0; i != NumElts/2; ++i)
3884     if (!isUndefOrEqual(Mask[i], 0))
3885       return false;
3886   for (unsigned i = NumElts/2; i != NumElts; ++i)
3887     if (!isUndefOrEqual(Mask[i], NumElts/2))
3888       return false;
3889   return true;
3890 }
3891
3892 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3893 /// specifies a shuffle of elements that is suitable for input to 128-bit
3894 /// version of MOVDDUP.
3895 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3896   if (!VT.is128BitVector())
3897     return false;
3898
3899   unsigned e = VT.getVectorNumElements() / 2;
3900   for (unsigned i = 0; i != e; ++i)
3901     if (!isUndefOrEqual(Mask[i], i))
3902       return false;
3903   for (unsigned i = 0; i != e; ++i)
3904     if (!isUndefOrEqual(Mask[e+i], i))
3905       return false;
3906   return true;
3907 }
3908
3909 /// isVEXTRACTF128Index - Return true if the specified
3910 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3911 /// suitable for input to VEXTRACTF128.
3912 bool X86::isVEXTRACTF128Index(SDNode *N) {
3913   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3914     return false;
3915
3916   // The index should be aligned on a 128-bit boundary.
3917   uint64_t Index =
3918     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3919
3920   unsigned VL = N->getValueType(0).getVectorNumElements();
3921   unsigned VBits = N->getValueType(0).getSizeInBits();
3922   unsigned ElSize = VBits / VL;
3923   bool Result = (Index * ElSize) % 128 == 0;
3924
3925   return Result;
3926 }
3927
3928 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3929 /// operand specifies a subvector insert that is suitable for input to
3930 /// VINSERTF128.
3931 bool X86::isVINSERTF128Index(SDNode *N) {
3932   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3933     return false;
3934
3935   // The index should be aligned on a 128-bit boundary.
3936   uint64_t Index =
3937     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3938
3939   unsigned VL = N->getValueType(0).getVectorNumElements();
3940   unsigned VBits = N->getValueType(0).getSizeInBits();
3941   unsigned ElSize = VBits / VL;
3942   bool Result = (Index * ElSize) % 128 == 0;
3943
3944   return Result;
3945 }
3946
3947 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3948 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3949 /// Handles 128-bit and 256-bit.
3950 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3951   EVT VT = N->getValueType(0);
3952
3953   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3954          "Unsupported vector type for PSHUF/SHUFP");
3955
3956   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3957   // independently on 128-bit lanes.
3958   unsigned NumElts = VT.getVectorNumElements();
3959   unsigned NumLanes = VT.getSizeInBits()/128;
3960   unsigned NumLaneElts = NumElts/NumLanes;
3961
3962   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3963          "Only supports 2 or 4 elements per lane");
3964
3965   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3966   unsigned Mask = 0;
3967   for (unsigned i = 0; i != NumElts; ++i) {
3968     int Elt = N->getMaskElt(i);
3969     if (Elt < 0) continue;
3970     Elt &= NumLaneElts - 1;
3971     unsigned ShAmt = (i << Shift) % 8;
3972     Mask |= Elt << ShAmt;
3973   }
3974
3975   return Mask;
3976 }
3977
3978 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3979 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3980 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3981   EVT VT = N->getValueType(0);
3982
3983   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3984          "Unsupported vector type for PSHUFHW");
3985
3986   unsigned NumElts = VT.getVectorNumElements();
3987
3988   unsigned Mask = 0;
3989   for (unsigned l = 0; l != NumElts; l += 8) {
3990     // 8 nodes per lane, but we only care about the last 4.
3991     for (unsigned i = 0; i < 4; ++i) {
3992       int Elt = N->getMaskElt(l+i+4);
3993       if (Elt < 0) continue;
3994       Elt &= 0x3; // only 2-bits.
3995       Mask |= Elt << (i * 2);
3996     }
3997   }
3998
3999   return Mask;
4000 }
4001
4002 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4003 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4004 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4005   EVT VT = N->getValueType(0);
4006
4007   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4008          "Unsupported vector type for PSHUFHW");
4009
4010   unsigned NumElts = VT.getVectorNumElements();
4011
4012   unsigned Mask = 0;
4013   for (unsigned l = 0; l != NumElts; l += 8) {
4014     // 8 nodes per lane, but we only care about the first 4.
4015     for (unsigned i = 0; i < 4; ++i) {
4016       int Elt = N->getMaskElt(l+i);
4017       if (Elt < 0) continue;
4018       Elt &= 0x3; // only 2-bits
4019       Mask |= Elt << (i * 2);
4020     }
4021   }
4022
4023   return Mask;
4024 }
4025
4026 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4027 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4028 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4029   EVT VT = SVOp->getValueType(0);
4030   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4031
4032   unsigned NumElts = VT.getVectorNumElements();
4033   unsigned NumLanes = VT.getSizeInBits()/128;
4034   unsigned NumLaneElts = NumElts/NumLanes;
4035
4036   int Val = 0;
4037   unsigned i;
4038   for (i = 0; i != NumElts; ++i) {
4039     Val = SVOp->getMaskElt(i);
4040     if (Val >= 0)
4041       break;
4042   }
4043   if (Val >= (int)NumElts)
4044     Val -= NumElts - NumLaneElts;
4045
4046   assert(Val - i > 0 && "PALIGNR imm should be positive");
4047   return (Val - i) * EltSize;
4048 }
4049
4050 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4051 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4052 /// instructions.
4053 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4054   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4055     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4056
4057   uint64_t Index =
4058     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4059
4060   EVT VecVT = N->getOperand(0).getValueType();
4061   EVT ElVT = VecVT.getVectorElementType();
4062
4063   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4064   return Index / NumElemsPerChunk;
4065 }
4066
4067 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4068 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4069 /// instructions.
4070 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4071   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4072     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4073
4074   uint64_t Index =
4075     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4076
4077   EVT VecVT = N->getValueType(0);
4078   EVT ElVT = VecVT.getVectorElementType();
4079
4080   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4081   return Index / NumElemsPerChunk;
4082 }
4083
4084 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4085 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4086 /// Handles 256-bit.
4087 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4088   EVT VT = N->getValueType(0);
4089
4090   unsigned NumElts = VT.getVectorNumElements();
4091
4092   assert((VT.is256BitVector() && NumElts == 4) &&
4093          "Unsupported vector type for VPERMQ/VPERMPD");
4094
4095   unsigned Mask = 0;
4096   for (unsigned i = 0; i != NumElts; ++i) {
4097     int Elt = N->getMaskElt(i);
4098     if (Elt < 0)
4099       continue;
4100     Mask |= Elt << (i*2);
4101   }
4102
4103   return Mask;
4104 }
4105 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4106 /// constant +0.0.
4107 bool X86::isZeroNode(SDValue Elt) {
4108   return ((isa<ConstantSDNode>(Elt) &&
4109            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4110           (isa<ConstantFPSDNode>(Elt) &&
4111            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4112 }
4113
4114 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4115 /// their permute mask.
4116 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4117                                     SelectionDAG &DAG) {
4118   EVT VT = SVOp->getValueType(0);
4119   unsigned NumElems = VT.getVectorNumElements();
4120   SmallVector<int, 8> MaskVec;
4121
4122   for (unsigned i = 0; i != NumElems; ++i) {
4123     int Idx = SVOp->getMaskElt(i);
4124     if (Idx >= 0) {
4125       if (Idx < (int)NumElems)
4126         Idx += NumElems;
4127       else
4128         Idx -= NumElems;
4129     }
4130     MaskVec.push_back(Idx);
4131   }
4132   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4133                               SVOp->getOperand(0), &MaskVec[0]);
4134 }
4135
4136 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4137 /// match movhlps. The lower half elements should come from upper half of
4138 /// V1 (and in order), and the upper half elements should come from the upper
4139 /// half of V2 (and in order).
4140 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4141   if (!VT.is128BitVector())
4142     return false;
4143   if (VT.getVectorNumElements() != 4)
4144     return false;
4145   for (unsigned i = 0, e = 2; i != e; ++i)
4146     if (!isUndefOrEqual(Mask[i], i+2))
4147       return false;
4148   for (unsigned i = 2; i != 4; ++i)
4149     if (!isUndefOrEqual(Mask[i], i+4))
4150       return false;
4151   return true;
4152 }
4153
4154 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4155 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4156 /// required.
4157 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4158   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4159     return false;
4160   N = N->getOperand(0).getNode();
4161   if (!ISD::isNON_EXTLoad(N))
4162     return false;
4163   if (LD)
4164     *LD = cast<LoadSDNode>(N);
4165   return true;
4166 }
4167
4168 // Test whether the given value is a vector value which will be legalized
4169 // into a load.
4170 static bool WillBeConstantPoolLoad(SDNode *N) {
4171   if (N->getOpcode() != ISD::BUILD_VECTOR)
4172     return false;
4173
4174   // Check for any non-constant elements.
4175   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4176     switch (N->getOperand(i).getNode()->getOpcode()) {
4177     case ISD::UNDEF:
4178     case ISD::ConstantFP:
4179     case ISD::Constant:
4180       break;
4181     default:
4182       return false;
4183     }
4184
4185   // Vectors of all-zeros and all-ones are materialized with special
4186   // instructions rather than being loaded.
4187   return !ISD::isBuildVectorAllZeros(N) &&
4188          !ISD::isBuildVectorAllOnes(N);
4189 }
4190
4191 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4192 /// match movlp{s|d}. The lower half elements should come from lower half of
4193 /// V1 (and in order), and the upper half elements should come from the upper
4194 /// half of V2 (and in order). And since V1 will become the source of the
4195 /// MOVLP, it must be either a vector load or a scalar load to vector.
4196 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4197                                ArrayRef<int> Mask, EVT VT) {
4198   if (!VT.is128BitVector())
4199     return false;
4200
4201   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4202     return false;
4203   // Is V2 is a vector load, don't do this transformation. We will try to use
4204   // load folding shufps op.
4205   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4206     return false;
4207
4208   unsigned NumElems = VT.getVectorNumElements();
4209
4210   if (NumElems != 2 && NumElems != 4)
4211     return false;
4212   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4213     if (!isUndefOrEqual(Mask[i], i))
4214       return false;
4215   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4216     if (!isUndefOrEqual(Mask[i], i+NumElems))
4217       return false;
4218   return true;
4219 }
4220
4221 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4222 /// all the same.
4223 static bool isSplatVector(SDNode *N) {
4224   if (N->getOpcode() != ISD::BUILD_VECTOR)
4225     return false;
4226
4227   SDValue SplatValue = N->getOperand(0);
4228   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4229     if (N->getOperand(i) != SplatValue)
4230       return false;
4231   return true;
4232 }
4233
4234 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4235 /// to an zero vector.
4236 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4237 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4238   SDValue V1 = N->getOperand(0);
4239   SDValue V2 = N->getOperand(1);
4240   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4241   for (unsigned i = 0; i != NumElems; ++i) {
4242     int Idx = N->getMaskElt(i);
4243     if (Idx >= (int)NumElems) {
4244       unsigned Opc = V2.getOpcode();
4245       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4246         continue;
4247       if (Opc != ISD::BUILD_VECTOR ||
4248           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4249         return false;
4250     } else if (Idx >= 0) {
4251       unsigned Opc = V1.getOpcode();
4252       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4253         continue;
4254       if (Opc != ISD::BUILD_VECTOR ||
4255           !X86::isZeroNode(V1.getOperand(Idx)))
4256         return false;
4257     }
4258   }
4259   return true;
4260 }
4261
4262 /// getZeroVector - Returns a vector of specified type with all zero elements.
4263 ///
4264 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4265                              SelectionDAG &DAG, DebugLoc dl) {
4266   assert(VT.isVector() && "Expected a vector type");
4267   unsigned Size = VT.getSizeInBits();
4268
4269   // Always build SSE zero vectors as <4 x i32> bitcasted
4270   // to their dest type. This ensures they get CSE'd.
4271   SDValue Vec;
4272   if (Size == 128) {  // SSE
4273     if (Subtarget->hasSSE2()) {  // SSE2
4274       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4275       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4276     } else { // SSE1
4277       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4278       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4279     }
4280   } else if (Size == 256) { // AVX
4281     if (Subtarget->hasAVX2()) { // AVX2
4282       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4283       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4284       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4285     } else {
4286       // 256-bit logic and arithmetic instructions in AVX are all
4287       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4288       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4289       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4290       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4291     }
4292   } else
4293     llvm_unreachable("Unexpected vector type");
4294
4295   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4296 }
4297
4298 /// getOnesVector - Returns a vector of specified type with all bits set.
4299 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4300 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4301 /// Then bitcast to their original type, ensuring they get CSE'd.
4302 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4303                              DebugLoc dl) {
4304   assert(VT.isVector() && "Expected a vector type");
4305   unsigned Size = VT.getSizeInBits();
4306
4307   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4308   SDValue Vec;
4309   if (Size == 256) {
4310     if (HasAVX2) { // AVX2
4311       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4312       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4313     } else { // AVX
4314       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4315       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4316     }
4317   } else if (Size == 128) {
4318     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4319   } else
4320     llvm_unreachable("Unexpected vector type");
4321
4322   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4323 }
4324
4325 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4326 /// that point to V2 points to its first element.
4327 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4328   for (unsigned i = 0; i != NumElems; ++i) {
4329     if (Mask[i] > (int)NumElems) {
4330       Mask[i] = NumElems;
4331     }
4332   }
4333 }
4334
4335 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4336 /// operation of specified width.
4337 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4338                        SDValue V2) {
4339   unsigned NumElems = VT.getVectorNumElements();
4340   SmallVector<int, 8> Mask;
4341   Mask.push_back(NumElems);
4342   for (unsigned i = 1; i != NumElems; ++i)
4343     Mask.push_back(i);
4344   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4345 }
4346
4347 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4348 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4349                           SDValue V2) {
4350   unsigned NumElems = VT.getVectorNumElements();
4351   SmallVector<int, 8> Mask;
4352   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4353     Mask.push_back(i);
4354     Mask.push_back(i + NumElems);
4355   }
4356   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4357 }
4358
4359 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4360 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4361                           SDValue V2) {
4362   unsigned NumElems = VT.getVectorNumElements();
4363   SmallVector<int, 8> Mask;
4364   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4365     Mask.push_back(i + Half);
4366     Mask.push_back(i + NumElems + Half);
4367   }
4368   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4369 }
4370
4371 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4372 // a generic shuffle instruction because the target has no such instructions.
4373 // Generate shuffles which repeat i16 and i8 several times until they can be
4374 // represented by v4f32 and then be manipulated by target suported shuffles.
4375 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4376   EVT VT = V.getValueType();
4377   int NumElems = VT.getVectorNumElements();
4378   DebugLoc dl = V.getDebugLoc();
4379
4380   while (NumElems > 4) {
4381     if (EltNo < NumElems/2) {
4382       V = getUnpackl(DAG, dl, VT, V, V);
4383     } else {
4384       V = getUnpackh(DAG, dl, VT, V, V);
4385       EltNo -= NumElems/2;
4386     }
4387     NumElems >>= 1;
4388   }
4389   return V;
4390 }
4391
4392 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4393 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4394   EVT VT = V.getValueType();
4395   DebugLoc dl = V.getDebugLoc();
4396   unsigned Size = VT.getSizeInBits();
4397
4398   if (Size == 128) {
4399     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4400     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4401     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4402                              &SplatMask[0]);
4403   } else if (Size == 256) {
4404     // To use VPERMILPS to splat scalars, the second half of indicies must
4405     // refer to the higher part, which is a duplication of the lower one,
4406     // because VPERMILPS can only handle in-lane permutations.
4407     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4408                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4409
4410     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4411     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4412                              &SplatMask[0]);
4413   } else
4414     llvm_unreachable("Vector size not supported");
4415
4416   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4417 }
4418
4419 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4420 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4421   EVT SrcVT = SV->getValueType(0);
4422   SDValue V1 = SV->getOperand(0);
4423   DebugLoc dl = SV->getDebugLoc();
4424
4425   int EltNo = SV->getSplatIndex();
4426   int NumElems = SrcVT.getVectorNumElements();
4427   unsigned Size = SrcVT.getSizeInBits();
4428
4429   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4430           "Unknown how to promote splat for type");
4431
4432   // Extract the 128-bit part containing the splat element and update
4433   // the splat element index when it refers to the higher register.
4434   if (Size == 256) {
4435     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4436     if (EltNo >= NumElems/2)
4437       EltNo -= NumElems/2;
4438   }
4439
4440   // All i16 and i8 vector types can't be used directly by a generic shuffle
4441   // instruction because the target has no such instruction. Generate shuffles
4442   // which repeat i16 and i8 several times until they fit in i32, and then can
4443   // be manipulated by target suported shuffles.
4444   EVT EltVT = SrcVT.getVectorElementType();
4445   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4446     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4447
4448   // Recreate the 256-bit vector and place the same 128-bit vector
4449   // into the low and high part. This is necessary because we want
4450   // to use VPERM* to shuffle the vectors
4451   if (Size == 256) {
4452     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4453   }
4454
4455   return getLegalSplat(DAG, V1, EltNo);
4456 }
4457
4458 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4459 /// vector of zero or undef vector.  This produces a shuffle where the low
4460 /// element of V2 is swizzled into the zero/undef vector, landing at element
4461 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4462 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4463                                            bool IsZero,
4464                                            const X86Subtarget *Subtarget,
4465                                            SelectionDAG &DAG) {
4466   EVT VT = V2.getValueType();
4467   SDValue V1 = IsZero
4468     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4469   unsigned NumElems = VT.getVectorNumElements();
4470   SmallVector<int, 16> MaskVec;
4471   for (unsigned i = 0; i != NumElems; ++i)
4472     // If this is the insertion idx, put the low elt of V2 here.
4473     MaskVec.push_back(i == Idx ? NumElems : i);
4474   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4475 }
4476
4477 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4478 /// target specific opcode. Returns true if the Mask could be calculated.
4479 /// Sets IsUnary to true if only uses one source.
4480 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4481                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4482   unsigned NumElems = VT.getVectorNumElements();
4483   SDValue ImmN;
4484
4485   IsUnary = false;
4486   switch(N->getOpcode()) {
4487   case X86ISD::SHUFP:
4488     ImmN = N->getOperand(N->getNumOperands()-1);
4489     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4490     break;
4491   case X86ISD::UNPCKH:
4492     DecodeUNPCKHMask(VT, Mask);
4493     break;
4494   case X86ISD::UNPCKL:
4495     DecodeUNPCKLMask(VT, Mask);
4496     break;
4497   case X86ISD::MOVHLPS:
4498     DecodeMOVHLPSMask(NumElems, Mask);
4499     break;
4500   case X86ISD::MOVLHPS:
4501     DecodeMOVLHPSMask(NumElems, Mask);
4502     break;
4503   case X86ISD::PSHUFD:
4504   case X86ISD::VPERMILP:
4505     ImmN = N->getOperand(N->getNumOperands()-1);
4506     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4507     IsUnary = true;
4508     break;
4509   case X86ISD::PSHUFHW:
4510     ImmN = N->getOperand(N->getNumOperands()-1);
4511     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4512     IsUnary = true;
4513     break;
4514   case X86ISD::PSHUFLW:
4515     ImmN = N->getOperand(N->getNumOperands()-1);
4516     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4517     IsUnary = true;
4518     break;
4519   case X86ISD::VPERMI:
4520     ImmN = N->getOperand(N->getNumOperands()-1);
4521     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4522     IsUnary = true;
4523     break;
4524   case X86ISD::MOVSS:
4525   case X86ISD::MOVSD: {
4526     // The index 0 always comes from the first element of the second source,
4527     // this is why MOVSS and MOVSD are used in the first place. The other
4528     // elements come from the other positions of the first source vector
4529     Mask.push_back(NumElems);
4530     for (unsigned i = 1; i != NumElems; ++i) {
4531       Mask.push_back(i);
4532     }
4533     break;
4534   }
4535   case X86ISD::VPERM2X128:
4536     ImmN = N->getOperand(N->getNumOperands()-1);
4537     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4538     if (Mask.empty()) return false;
4539     break;
4540   case X86ISD::MOVDDUP:
4541   case X86ISD::MOVLHPD:
4542   case X86ISD::MOVLPD:
4543   case X86ISD::MOVLPS:
4544   case X86ISD::MOVSHDUP:
4545   case X86ISD::MOVSLDUP:
4546   case X86ISD::PALIGN:
4547     // Not yet implemented
4548     return false;
4549   default: llvm_unreachable("unknown target shuffle node");
4550   }
4551
4552   return true;
4553 }
4554
4555 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4556 /// element of the result of the vector shuffle.
4557 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4558                                    unsigned Depth) {
4559   if (Depth == 6)
4560     return SDValue();  // Limit search depth.
4561
4562   SDValue V = SDValue(N, 0);
4563   EVT VT = V.getValueType();
4564   unsigned Opcode = V.getOpcode();
4565
4566   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4567   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4568     int Elt = SV->getMaskElt(Index);
4569
4570     if (Elt < 0)
4571       return DAG.getUNDEF(VT.getVectorElementType());
4572
4573     unsigned NumElems = VT.getVectorNumElements();
4574     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4575                                          : SV->getOperand(1);
4576     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4577   }
4578
4579   // Recurse into target specific vector shuffles to find scalars.
4580   if (isTargetShuffle(Opcode)) {
4581     MVT ShufVT = V.getValueType().getSimpleVT();
4582     unsigned NumElems = ShufVT.getVectorNumElements();
4583     SmallVector<int, 16> ShuffleMask;
4584     SDValue ImmN;
4585     bool IsUnary;
4586
4587     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4588       return SDValue();
4589
4590     int Elt = ShuffleMask[Index];
4591     if (Elt < 0)
4592       return DAG.getUNDEF(ShufVT.getVectorElementType());
4593
4594     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4595                                          : N->getOperand(1);
4596     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4597                                Depth+1);
4598   }
4599
4600   // Actual nodes that may contain scalar elements
4601   if (Opcode == ISD::BITCAST) {
4602     V = V.getOperand(0);
4603     EVT SrcVT = V.getValueType();
4604     unsigned NumElems = VT.getVectorNumElements();
4605
4606     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4607       return SDValue();
4608   }
4609
4610   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4611     return (Index == 0) ? V.getOperand(0)
4612                         : DAG.getUNDEF(VT.getVectorElementType());
4613
4614   if (V.getOpcode() == ISD::BUILD_VECTOR)
4615     return V.getOperand(Index);
4616
4617   return SDValue();
4618 }
4619
4620 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4621 /// shuffle operation which come from a consecutively from a zero. The
4622 /// search can start in two different directions, from left or right.
4623 static
4624 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4625                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4626   unsigned i;
4627   for (i = 0; i != NumElems; ++i) {
4628     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4629     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4630     if (!(Elt.getNode() &&
4631          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4632       break;
4633   }
4634
4635   return i;
4636 }
4637
4638 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4639 /// correspond consecutively to elements from one of the vector operands,
4640 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4641 static
4642 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4643                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4644                               unsigned NumElems, unsigned &OpNum) {
4645   bool SeenV1 = false;
4646   bool SeenV2 = false;
4647
4648   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4649     int Idx = SVOp->getMaskElt(i);
4650     // Ignore undef indicies
4651     if (Idx < 0)
4652       continue;
4653
4654     if (Idx < (int)NumElems)
4655       SeenV1 = true;
4656     else
4657       SeenV2 = true;
4658
4659     // Only accept consecutive elements from the same vector
4660     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4661       return false;
4662   }
4663
4664   OpNum = SeenV1 ? 0 : 1;
4665   return true;
4666 }
4667
4668 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4669 /// logical left shift of a vector.
4670 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4671                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4672   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4673   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4674               false /* check zeros from right */, DAG);
4675   unsigned OpSrc;
4676
4677   if (!NumZeros)
4678     return false;
4679
4680   // Considering the elements in the mask that are not consecutive zeros,
4681   // check if they consecutively come from only one of the source vectors.
4682   //
4683   //               V1 = {X, A, B, C}     0
4684   //                         \  \  \    /
4685   //   vector_shuffle V1, V2 <1, 2, 3, X>
4686   //
4687   if (!isShuffleMaskConsecutive(SVOp,
4688             0,                   // Mask Start Index
4689             NumElems-NumZeros,   // Mask End Index(exclusive)
4690             NumZeros,            // Where to start looking in the src vector
4691             NumElems,            // Number of elements in vector
4692             OpSrc))              // Which source operand ?
4693     return false;
4694
4695   isLeft = false;
4696   ShAmt = NumZeros;
4697   ShVal = SVOp->getOperand(OpSrc);
4698   return true;
4699 }
4700
4701 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4702 /// logical left shift of a vector.
4703 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4704                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4705   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4706   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4707               true /* check zeros from left */, DAG);
4708   unsigned OpSrc;
4709
4710   if (!NumZeros)
4711     return false;
4712
4713   // Considering the elements in the mask that are not consecutive zeros,
4714   // check if they consecutively come from only one of the source vectors.
4715   //
4716   //                           0    { A, B, X, X } = V2
4717   //                          / \    /  /
4718   //   vector_shuffle V1, V2 <X, X, 4, 5>
4719   //
4720   if (!isShuffleMaskConsecutive(SVOp,
4721             NumZeros,     // Mask Start Index
4722             NumElems,     // Mask End Index(exclusive)
4723             0,            // Where to start looking in the src vector
4724             NumElems,     // Number of elements in vector
4725             OpSrc))       // Which source operand ?
4726     return false;
4727
4728   isLeft = true;
4729   ShAmt = NumZeros;
4730   ShVal = SVOp->getOperand(OpSrc);
4731   return true;
4732 }
4733
4734 /// isVectorShift - Returns true if the shuffle can be implemented as a
4735 /// logical left or right shift of a vector.
4736 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4737                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4738   // Although the logic below support any bitwidth size, there are no
4739   // shift instructions which handle more than 128-bit vectors.
4740   if (!SVOp->getValueType(0).is128BitVector())
4741     return false;
4742
4743   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4744       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4745     return true;
4746
4747   return false;
4748 }
4749
4750 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4751 ///
4752 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4753                                        unsigned NumNonZero, unsigned NumZero,
4754                                        SelectionDAG &DAG,
4755                                        const X86Subtarget* Subtarget,
4756                                        const TargetLowering &TLI) {
4757   if (NumNonZero > 8)
4758     return SDValue();
4759
4760   DebugLoc dl = Op.getDebugLoc();
4761   SDValue V(0, 0);
4762   bool First = true;
4763   for (unsigned i = 0; i < 16; ++i) {
4764     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4765     if (ThisIsNonZero && First) {
4766       if (NumZero)
4767         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4768       else
4769         V = DAG.getUNDEF(MVT::v8i16);
4770       First = false;
4771     }
4772
4773     if ((i & 1) != 0) {
4774       SDValue ThisElt(0, 0), LastElt(0, 0);
4775       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4776       if (LastIsNonZero) {
4777         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4778                               MVT::i16, Op.getOperand(i-1));
4779       }
4780       if (ThisIsNonZero) {
4781         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4782         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4783                               ThisElt, DAG.getConstant(8, MVT::i8));
4784         if (LastIsNonZero)
4785           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4786       } else
4787         ThisElt = LastElt;
4788
4789       if (ThisElt.getNode())
4790         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4791                         DAG.getIntPtrConstant(i/2));
4792     }
4793   }
4794
4795   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4796 }
4797
4798 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4799 ///
4800 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4801                                      unsigned NumNonZero, unsigned NumZero,
4802                                      SelectionDAG &DAG,
4803                                      const X86Subtarget* Subtarget,
4804                                      const TargetLowering &TLI) {
4805   if (NumNonZero > 4)
4806     return SDValue();
4807
4808   DebugLoc dl = Op.getDebugLoc();
4809   SDValue V(0, 0);
4810   bool First = true;
4811   for (unsigned i = 0; i < 8; ++i) {
4812     bool isNonZero = (NonZeros & (1 << i)) != 0;
4813     if (isNonZero) {
4814       if (First) {
4815         if (NumZero)
4816           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4817         else
4818           V = DAG.getUNDEF(MVT::v8i16);
4819         First = false;
4820       }
4821       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4822                       MVT::v8i16, V, Op.getOperand(i),
4823                       DAG.getIntPtrConstant(i));
4824     }
4825   }
4826
4827   return V;
4828 }
4829
4830 /// getVShift - Return a vector logical shift node.
4831 ///
4832 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4833                          unsigned NumBits, SelectionDAG &DAG,
4834                          const TargetLowering &TLI, DebugLoc dl) {
4835   assert(VT.is128BitVector() && "Unknown type for VShift");
4836   EVT ShVT = MVT::v2i64;
4837   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4838   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4839   return DAG.getNode(ISD::BITCAST, dl, VT,
4840                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4841                              DAG.getConstant(NumBits,
4842                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4843 }
4844
4845 SDValue
4846 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4847                                           SelectionDAG &DAG) const {
4848
4849   // Check if the scalar load can be widened into a vector load. And if
4850   // the address is "base + cst" see if the cst can be "absorbed" into
4851   // the shuffle mask.
4852   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4853     SDValue Ptr = LD->getBasePtr();
4854     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4855       return SDValue();
4856     EVT PVT = LD->getValueType(0);
4857     if (PVT != MVT::i32 && PVT != MVT::f32)
4858       return SDValue();
4859
4860     int FI = -1;
4861     int64_t Offset = 0;
4862     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4863       FI = FINode->getIndex();
4864       Offset = 0;
4865     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4866                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4867       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4868       Offset = Ptr.getConstantOperandVal(1);
4869       Ptr = Ptr.getOperand(0);
4870     } else {
4871       return SDValue();
4872     }
4873
4874     // FIXME: 256-bit vector instructions don't require a strict alignment,
4875     // improve this code to support it better.
4876     unsigned RequiredAlign = VT.getSizeInBits()/8;
4877     SDValue Chain = LD->getChain();
4878     // Make sure the stack object alignment is at least 16 or 32.
4879     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4880     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4881       if (MFI->isFixedObjectIndex(FI)) {
4882         // Can't change the alignment. FIXME: It's possible to compute
4883         // the exact stack offset and reference FI + adjust offset instead.
4884         // If someone *really* cares about this. That's the way to implement it.
4885         return SDValue();
4886       } else {
4887         MFI->setObjectAlignment(FI, RequiredAlign);
4888       }
4889     }
4890
4891     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4892     // Ptr + (Offset & ~15).
4893     if (Offset < 0)
4894       return SDValue();
4895     if ((Offset % RequiredAlign) & 3)
4896       return SDValue();
4897     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4898     if (StartOffset)
4899       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4900                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4901
4902     int EltNo = (Offset - StartOffset) >> 2;
4903     unsigned NumElems = VT.getVectorNumElements();
4904
4905     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4906     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4907                              LD->getPointerInfo().getWithOffset(StartOffset),
4908                              false, false, false, 0);
4909
4910     SmallVector<int, 8> Mask;
4911     for (unsigned i = 0; i != NumElems; ++i)
4912       Mask.push_back(EltNo);
4913
4914     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4915   }
4916
4917   return SDValue();
4918 }
4919
4920 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4921 /// vector of type 'VT', see if the elements can be replaced by a single large
4922 /// load which has the same value as a build_vector whose operands are 'elts'.
4923 ///
4924 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4925 ///
4926 /// FIXME: we'd also like to handle the case where the last elements are zero
4927 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4928 /// There's even a handy isZeroNode for that purpose.
4929 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4930                                         DebugLoc &DL, SelectionDAG &DAG) {
4931   EVT EltVT = VT.getVectorElementType();
4932   unsigned NumElems = Elts.size();
4933
4934   LoadSDNode *LDBase = NULL;
4935   unsigned LastLoadedElt = -1U;
4936
4937   // For each element in the initializer, see if we've found a load or an undef.
4938   // If we don't find an initial load element, or later load elements are
4939   // non-consecutive, bail out.
4940   for (unsigned i = 0; i < NumElems; ++i) {
4941     SDValue Elt = Elts[i];
4942
4943     if (!Elt.getNode() ||
4944         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4945       return SDValue();
4946     if (!LDBase) {
4947       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4948         return SDValue();
4949       LDBase = cast<LoadSDNode>(Elt.getNode());
4950       LastLoadedElt = i;
4951       continue;
4952     }
4953     if (Elt.getOpcode() == ISD::UNDEF)
4954       continue;
4955
4956     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4957     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4958       return SDValue();
4959     LastLoadedElt = i;
4960   }
4961
4962   // If we have found an entire vector of loads and undefs, then return a large
4963   // load of the entire vector width starting at the base pointer.  If we found
4964   // consecutive loads for the low half, generate a vzext_load node.
4965   if (LastLoadedElt == NumElems - 1) {
4966     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4967       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4968                          LDBase->getPointerInfo(),
4969                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4970                          LDBase->isInvariant(), 0);
4971     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4972                        LDBase->getPointerInfo(),
4973                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4974                        LDBase->isInvariant(), LDBase->getAlignment());
4975   }
4976   if (NumElems == 4 && LastLoadedElt == 1 &&
4977       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4978     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4979     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4980     SDValue ResNode =
4981         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4982                                 LDBase->getPointerInfo(),
4983                                 LDBase->getAlignment(),
4984                                 false/*isVolatile*/, true/*ReadMem*/,
4985                                 false/*WriteMem*/);
4986     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4987   }
4988   return SDValue();
4989 }
4990
4991 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4992 /// to generate a splat value for the following cases:
4993 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4994 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4995 /// a scalar load, or a constant.
4996 /// The VBROADCAST node is returned when a pattern is found,
4997 /// or SDValue() otherwise.
4998 SDValue
4999 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5000   if (!Subtarget->hasAVX())
5001     return SDValue();
5002
5003   EVT VT = Op.getValueType();
5004   DebugLoc dl = Op.getDebugLoc();
5005
5006   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5007          "Unsupported vector type for broadcast.");
5008
5009   SDValue Ld;
5010   bool ConstSplatVal;
5011
5012   switch (Op.getOpcode()) {
5013     default:
5014       // Unknown pattern found.
5015       return SDValue();
5016
5017     case ISD::BUILD_VECTOR: {
5018       // The BUILD_VECTOR node must be a splat.
5019       if (!isSplatVector(Op.getNode()))
5020         return SDValue();
5021
5022       Ld = Op.getOperand(0);
5023       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5024                      Ld.getOpcode() == ISD::ConstantFP);
5025
5026       // The suspected load node has several users. Make sure that all
5027       // of its users are from the BUILD_VECTOR node.
5028       // Constants may have multiple users.
5029       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5030         return SDValue();
5031       break;
5032     }
5033
5034     case ISD::VECTOR_SHUFFLE: {
5035       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5036
5037       // Shuffles must have a splat mask where the first element is
5038       // broadcasted.
5039       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5040         return SDValue();
5041
5042       SDValue Sc = Op.getOperand(0);
5043       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5044           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5045
5046         if (!Subtarget->hasAVX2())
5047           return SDValue();
5048
5049         // Use the register form of the broadcast instruction available on AVX2.
5050         if (VT.is256BitVector())
5051           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5052         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5053       }
5054
5055       Ld = Sc.getOperand(0);
5056       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5057                        Ld.getOpcode() == ISD::ConstantFP);
5058
5059       // The scalar_to_vector node and the suspected
5060       // load node must have exactly one user.
5061       // Constants may have multiple users.
5062       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5063         return SDValue();
5064       break;
5065     }
5066   }
5067
5068   bool Is256 = VT.is256BitVector();
5069
5070   // Handle the broadcasting a single constant scalar from the constant pool
5071   // into a vector. On Sandybridge it is still better to load a constant vector
5072   // from the constant pool and not to broadcast it from a scalar.
5073   if (ConstSplatVal && Subtarget->hasAVX2()) {
5074     EVT CVT = Ld.getValueType();
5075     assert(!CVT.isVector() && "Must not broadcast a vector type");
5076     unsigned ScalarSize = CVT.getSizeInBits();
5077
5078     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5079       const Constant *C = 0;
5080       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5081         C = CI->getConstantIntValue();
5082       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5083         C = CF->getConstantFPValue();
5084
5085       assert(C && "Invalid constant type");
5086
5087       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5088       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5089       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5090                        MachinePointerInfo::getConstantPool(),
5091                        false, false, false, Alignment);
5092
5093       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5094     }
5095   }
5096
5097   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5098   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5099
5100   // Handle AVX2 in-register broadcasts.
5101   if (!IsLoad && Subtarget->hasAVX2() &&
5102       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5103     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5104
5105   // The scalar source must be a normal load.
5106   if (!IsLoad)
5107     return SDValue();
5108
5109   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5110     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5111
5112   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5113   // double since there is no vbroadcastsd xmm
5114   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5115     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5116       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5117   }
5118
5119   // Unsupported broadcast.
5120   return SDValue();
5121 }
5122
5123 SDValue
5124 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5125   DebugLoc dl = Op.getDebugLoc();
5126
5127   EVT VT = Op.getValueType();
5128   EVT ExtVT = VT.getVectorElementType();
5129   unsigned NumElems = Op.getNumOperands();
5130
5131   // Vectors containing all zeros can be matched by pxor and xorps later
5132   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5133     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5134     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5135     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5136       return Op;
5137
5138     return getZeroVector(VT, Subtarget, DAG, dl);
5139   }
5140
5141   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5142   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5143   // vpcmpeqd on 256-bit vectors.
5144   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5145     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5146       return Op;
5147
5148     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5149   }
5150
5151   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5152   if (Broadcast.getNode())
5153     return Broadcast;
5154
5155   unsigned EVTBits = ExtVT.getSizeInBits();
5156
5157   unsigned NumZero  = 0;
5158   unsigned NumNonZero = 0;
5159   unsigned NonZeros = 0;
5160   bool IsAllConstants = true;
5161   SmallSet<SDValue, 8> Values;
5162   for (unsigned i = 0; i < NumElems; ++i) {
5163     SDValue Elt = Op.getOperand(i);
5164     if (Elt.getOpcode() == ISD::UNDEF)
5165       continue;
5166     Values.insert(Elt);
5167     if (Elt.getOpcode() != ISD::Constant &&
5168         Elt.getOpcode() != ISD::ConstantFP)
5169       IsAllConstants = false;
5170     if (X86::isZeroNode(Elt))
5171       NumZero++;
5172     else {
5173       NonZeros |= (1 << i);
5174       NumNonZero++;
5175     }
5176   }
5177
5178   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5179   if (NumNonZero == 0)
5180     return DAG.getUNDEF(VT);
5181
5182   // Special case for single non-zero, non-undef, element.
5183   if (NumNonZero == 1) {
5184     unsigned Idx = CountTrailingZeros_32(NonZeros);
5185     SDValue Item = Op.getOperand(Idx);
5186
5187     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5188     // the value are obviously zero, truncate the value to i32 and do the
5189     // insertion that way.  Only do this if the value is non-constant or if the
5190     // value is a constant being inserted into element 0.  It is cheaper to do
5191     // a constant pool load than it is to do a movd + shuffle.
5192     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5193         (!IsAllConstants || Idx == 0)) {
5194       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5195         // Handle SSE only.
5196         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5197         EVT VecVT = MVT::v4i32;
5198         unsigned VecElts = 4;
5199
5200         // Truncate the value (which may itself be a constant) to i32, and
5201         // convert it to a vector with movd (S2V+shuffle to zero extend).
5202         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5203         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5204         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5205
5206         // Now we have our 32-bit value zero extended in the low element of
5207         // a vector.  If Idx != 0, swizzle it into place.
5208         if (Idx != 0) {
5209           SmallVector<int, 4> Mask;
5210           Mask.push_back(Idx);
5211           for (unsigned i = 1; i != VecElts; ++i)
5212             Mask.push_back(i);
5213           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5214                                       &Mask[0]);
5215         }
5216         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5217       }
5218     }
5219
5220     // If we have a constant or non-constant insertion into the low element of
5221     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5222     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5223     // depending on what the source datatype is.
5224     if (Idx == 0) {
5225       if (NumZero == 0)
5226         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5227
5228       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5229           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5230         if (VT.is256BitVector()) {
5231           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5232           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5233                              Item, DAG.getIntPtrConstant(0));
5234         }
5235         assert(VT.is128BitVector() && "Expected an SSE value type!");
5236         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5237         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5238         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5239       }
5240
5241       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5242         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5243         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5244         if (VT.is256BitVector()) {
5245           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5246           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5247         } else {
5248           assert(VT.is128BitVector() && "Expected an SSE value type!");
5249           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5250         }
5251         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5252       }
5253     }
5254
5255     // Is it a vector logical left shift?
5256     if (NumElems == 2 && Idx == 1 &&
5257         X86::isZeroNode(Op.getOperand(0)) &&
5258         !X86::isZeroNode(Op.getOperand(1))) {
5259       unsigned NumBits = VT.getSizeInBits();
5260       return getVShift(true, VT,
5261                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5262                                    VT, Op.getOperand(1)),
5263                        NumBits/2, DAG, *this, dl);
5264     }
5265
5266     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5267       return SDValue();
5268
5269     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5270     // is a non-constant being inserted into an element other than the low one,
5271     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5272     // movd/movss) to move this into the low element, then shuffle it into
5273     // place.
5274     if (EVTBits == 32) {
5275       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5276
5277       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5278       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5279       SmallVector<int, 8> MaskVec;
5280       for (unsigned i = 0; i != NumElems; ++i)
5281         MaskVec.push_back(i == Idx ? 0 : 1);
5282       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5283     }
5284   }
5285
5286   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5287   if (Values.size() == 1) {
5288     if (EVTBits == 32) {
5289       // Instead of a shuffle like this:
5290       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5291       // Check if it's possible to issue this instead.
5292       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5293       unsigned Idx = CountTrailingZeros_32(NonZeros);
5294       SDValue Item = Op.getOperand(Idx);
5295       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5296         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5297     }
5298     return SDValue();
5299   }
5300
5301   // A vector full of immediates; various special cases are already
5302   // handled, so this is best done with a single constant-pool load.
5303   if (IsAllConstants)
5304     return SDValue();
5305
5306   // For AVX-length vectors, build the individual 128-bit pieces and use
5307   // shuffles to put them in place.
5308   if (VT.is256BitVector()) {
5309     SmallVector<SDValue, 32> V;
5310     for (unsigned i = 0; i != NumElems; ++i)
5311       V.push_back(Op.getOperand(i));
5312
5313     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5314
5315     // Build both the lower and upper subvector.
5316     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5317     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5318                                 NumElems/2);
5319
5320     // Recreate the wider vector with the lower and upper part.
5321     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5322   }
5323
5324   // Let legalizer expand 2-wide build_vectors.
5325   if (EVTBits == 64) {
5326     if (NumNonZero == 1) {
5327       // One half is zero or undef.
5328       unsigned Idx = CountTrailingZeros_32(NonZeros);
5329       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5330                                  Op.getOperand(Idx));
5331       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5332     }
5333     return SDValue();
5334   }
5335
5336   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5337   if (EVTBits == 8 && NumElems == 16) {
5338     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5339                                         Subtarget, *this);
5340     if (V.getNode()) return V;
5341   }
5342
5343   if (EVTBits == 16 && NumElems == 8) {
5344     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5345                                       Subtarget, *this);
5346     if (V.getNode()) return V;
5347   }
5348
5349   // If element VT is == 32 bits, turn it into a number of shuffles.
5350   SmallVector<SDValue, 8> V(NumElems);
5351   if (NumElems == 4 && NumZero > 0) {
5352     for (unsigned i = 0; i < 4; ++i) {
5353       bool isZero = !(NonZeros & (1 << i));
5354       if (isZero)
5355         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5356       else
5357         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5358     }
5359
5360     for (unsigned i = 0; i < 2; ++i) {
5361       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5362         default: break;
5363         case 0:
5364           V[i] = V[i*2];  // Must be a zero vector.
5365           break;
5366         case 1:
5367           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5368           break;
5369         case 2:
5370           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5371           break;
5372         case 3:
5373           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5374           break;
5375       }
5376     }
5377
5378     bool Reverse1 = (NonZeros & 0x3) == 2;
5379     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5380     int MaskVec[] = {
5381       Reverse1 ? 1 : 0,
5382       Reverse1 ? 0 : 1,
5383       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5384       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5385     };
5386     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5387   }
5388
5389   if (Values.size() > 1 && VT.is128BitVector()) {
5390     // Check for a build vector of consecutive loads.
5391     for (unsigned i = 0; i < NumElems; ++i)
5392       V[i] = Op.getOperand(i);
5393
5394     // Check for elements which are consecutive loads.
5395     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5396     if (LD.getNode())
5397       return LD;
5398
5399     // For SSE 4.1, use insertps to put the high elements into the low element.
5400     if (getSubtarget()->hasSSE41()) {
5401       SDValue Result;
5402       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5403         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5404       else
5405         Result = DAG.getUNDEF(VT);
5406
5407       for (unsigned i = 1; i < NumElems; ++i) {
5408         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5409         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5410                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5411       }
5412       return Result;
5413     }
5414
5415     // Otherwise, expand into a number of unpckl*, start by extending each of
5416     // our (non-undef) elements to the full vector width with the element in the
5417     // bottom slot of the vector (which generates no code for SSE).
5418     for (unsigned i = 0; i < NumElems; ++i) {
5419       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5420         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5421       else
5422         V[i] = DAG.getUNDEF(VT);
5423     }
5424
5425     // Next, we iteratively mix elements, e.g. for v4f32:
5426     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5427     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5428     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5429     unsigned EltStride = NumElems >> 1;
5430     while (EltStride != 0) {
5431       for (unsigned i = 0; i < EltStride; ++i) {
5432         // If V[i+EltStride] is undef and this is the first round of mixing,
5433         // then it is safe to just drop this shuffle: V[i] is already in the
5434         // right place, the one element (since it's the first round) being
5435         // inserted as undef can be dropped.  This isn't safe for successive
5436         // rounds because they will permute elements within both vectors.
5437         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5438             EltStride == NumElems/2)
5439           continue;
5440
5441         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5442       }
5443       EltStride >>= 1;
5444     }
5445     return V[0];
5446   }
5447   return SDValue();
5448 }
5449
5450 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5451 // them in a MMX register.  This is better than doing a stack convert.
5452 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5453   DebugLoc dl = Op.getDebugLoc();
5454   EVT ResVT = Op.getValueType();
5455
5456   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5457          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5458   int Mask[2];
5459   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5460   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5461   InVec = Op.getOperand(1);
5462   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5463     unsigned NumElts = ResVT.getVectorNumElements();
5464     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5465     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5466                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5467   } else {
5468     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5469     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5470     Mask[0] = 0; Mask[1] = 2;
5471     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5472   }
5473   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5474 }
5475
5476 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5477 // to create 256-bit vectors from two other 128-bit ones.
5478 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5479   DebugLoc dl = Op.getDebugLoc();
5480   EVT ResVT = Op.getValueType();
5481
5482   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5483
5484   SDValue V1 = Op.getOperand(0);
5485   SDValue V2 = Op.getOperand(1);
5486   unsigned NumElems = ResVT.getVectorNumElements();
5487
5488   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5489 }
5490
5491 SDValue
5492 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5493   EVT ResVT = Op.getValueType();
5494
5495   assert(Op.getNumOperands() == 2);
5496   assert((ResVT.is128BitVector() || ResVT.is256BitVector()) &&
5497          "Unsupported CONCAT_VECTORS for value type");
5498
5499   // We support concatenate two MMX registers and place them in a MMX register.
5500   // This is better than doing a stack convert.
5501   if (ResVT.is128BitVector())
5502     return LowerMMXCONCAT_VECTORS(Op, DAG);
5503
5504   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5505   // from two other 128-bit ones.
5506   return LowerAVXCONCAT_VECTORS(Op, DAG);
5507 }
5508
5509 // Try to lower a shuffle node into a simple blend instruction.
5510 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5511                                           const X86Subtarget *Subtarget,
5512                                           SelectionDAG &DAG) {
5513   SDValue V1 = SVOp->getOperand(0);
5514   SDValue V2 = SVOp->getOperand(1);
5515   DebugLoc dl = SVOp->getDebugLoc();
5516   MVT VT = SVOp->getValueType(0).getSimpleVT();
5517   unsigned NumElems = VT.getVectorNumElements();
5518
5519   if (!Subtarget->hasSSE41())
5520     return SDValue();
5521
5522   unsigned ISDNo = 0;
5523   MVT OpTy;
5524
5525   switch (VT.SimpleTy) {
5526   default: return SDValue();
5527   case MVT::v8i16:
5528     ISDNo = X86ISD::BLENDPW;
5529     OpTy = MVT::v8i16;
5530     break;
5531   case MVT::v4i32:
5532   case MVT::v4f32:
5533     ISDNo = X86ISD::BLENDPS;
5534     OpTy = MVT::v4f32;
5535     break;
5536   case MVT::v2i64:
5537   case MVT::v2f64:
5538     ISDNo = X86ISD::BLENDPD;
5539     OpTy = MVT::v2f64;
5540     break;
5541   case MVT::v8i32:
5542   case MVT::v8f32:
5543     if (!Subtarget->hasAVX())
5544       return SDValue();
5545     ISDNo = X86ISD::BLENDPS;
5546     OpTy = MVT::v8f32;
5547     break;
5548   case MVT::v4i64:
5549   case MVT::v4f64:
5550     if (!Subtarget->hasAVX())
5551       return SDValue();
5552     ISDNo = X86ISD::BLENDPD;
5553     OpTy = MVT::v4f64;
5554     break;
5555   }
5556   assert(ISDNo && "Invalid Op Number");
5557
5558   unsigned MaskVals = 0;
5559
5560   for (unsigned i = 0; i != NumElems; ++i) {
5561     int EltIdx = SVOp->getMaskElt(i);
5562     if (EltIdx == (int)i || EltIdx < 0)
5563       MaskVals |= (1<<i);
5564     else if (EltIdx == (int)(i + NumElems))
5565       continue; // Bit is set to zero;
5566     else
5567       return SDValue();
5568   }
5569
5570   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5571   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5572   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5573                              DAG.getConstant(MaskVals, MVT::i32));
5574   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5575 }
5576
5577 // v8i16 shuffles - Prefer shuffles in the following order:
5578 // 1. [all]   pshuflw, pshufhw, optional move
5579 // 2. [ssse3] 1 x pshufb
5580 // 3. [ssse3] 2 x pshufb + 1 x por
5581 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5582 SDValue
5583 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5584                                             SelectionDAG &DAG) const {
5585   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5586   SDValue V1 = SVOp->getOperand(0);
5587   SDValue V2 = SVOp->getOperand(1);
5588   DebugLoc dl = SVOp->getDebugLoc();
5589   SmallVector<int, 8> MaskVals;
5590
5591   // Determine if more than 1 of the words in each of the low and high quadwords
5592   // of the result come from the same quadword of one of the two inputs.  Undef
5593   // mask values count as coming from any quadword, for better codegen.
5594   unsigned LoQuad[] = { 0, 0, 0, 0 };
5595   unsigned HiQuad[] = { 0, 0, 0, 0 };
5596   std::bitset<4> InputQuads;
5597   for (unsigned i = 0; i < 8; ++i) {
5598     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5599     int EltIdx = SVOp->getMaskElt(i);
5600     MaskVals.push_back(EltIdx);
5601     if (EltIdx < 0) {
5602       ++Quad[0];
5603       ++Quad[1];
5604       ++Quad[2];
5605       ++Quad[3];
5606       continue;
5607     }
5608     ++Quad[EltIdx / 4];
5609     InputQuads.set(EltIdx / 4);
5610   }
5611
5612   int BestLoQuad = -1;
5613   unsigned MaxQuad = 1;
5614   for (unsigned i = 0; i < 4; ++i) {
5615     if (LoQuad[i] > MaxQuad) {
5616       BestLoQuad = i;
5617       MaxQuad = LoQuad[i];
5618     }
5619   }
5620
5621   int BestHiQuad = -1;
5622   MaxQuad = 1;
5623   for (unsigned i = 0; i < 4; ++i) {
5624     if (HiQuad[i] > MaxQuad) {
5625       BestHiQuad = i;
5626       MaxQuad = HiQuad[i];
5627     }
5628   }
5629
5630   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5631   // of the two input vectors, shuffle them into one input vector so only a
5632   // single pshufb instruction is necessary. If There are more than 2 input
5633   // quads, disable the next transformation since it does not help SSSE3.
5634   bool V1Used = InputQuads[0] || InputQuads[1];
5635   bool V2Used = InputQuads[2] || InputQuads[3];
5636   if (Subtarget->hasSSSE3()) {
5637     if (InputQuads.count() == 2 && V1Used && V2Used) {
5638       BestLoQuad = InputQuads[0] ? 0 : 1;
5639       BestHiQuad = InputQuads[2] ? 2 : 3;
5640     }
5641     if (InputQuads.count() > 2) {
5642       BestLoQuad = -1;
5643       BestHiQuad = -1;
5644     }
5645   }
5646
5647   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5648   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5649   // words from all 4 input quadwords.
5650   SDValue NewV;
5651   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5652     int MaskV[] = {
5653       BestLoQuad < 0 ? 0 : BestLoQuad,
5654       BestHiQuad < 0 ? 1 : BestHiQuad
5655     };
5656     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5657                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5658                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5659     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5660
5661     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5662     // source words for the shuffle, to aid later transformations.
5663     bool AllWordsInNewV = true;
5664     bool InOrder[2] = { true, true };
5665     for (unsigned i = 0; i != 8; ++i) {
5666       int idx = MaskVals[i];
5667       if (idx != (int)i)
5668         InOrder[i/4] = false;
5669       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5670         continue;
5671       AllWordsInNewV = false;
5672       break;
5673     }
5674
5675     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5676     if (AllWordsInNewV) {
5677       for (int i = 0; i != 8; ++i) {
5678         int idx = MaskVals[i];
5679         if (idx < 0)
5680           continue;
5681         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5682         if ((idx != i) && idx < 4)
5683           pshufhw = false;
5684         if ((idx != i) && idx > 3)
5685           pshuflw = false;
5686       }
5687       V1 = NewV;
5688       V2Used = false;
5689       BestLoQuad = 0;
5690       BestHiQuad = 1;
5691     }
5692
5693     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5694     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5695     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5696       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5697       unsigned TargetMask = 0;
5698       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5699                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5700       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5701       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5702                              getShufflePSHUFLWImmediate(SVOp);
5703       V1 = NewV.getOperand(0);
5704       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5705     }
5706   }
5707
5708   // If we have SSSE3, and all words of the result are from 1 input vector,
5709   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5710   // is present, fall back to case 4.
5711   if (Subtarget->hasSSSE3()) {
5712     SmallVector<SDValue,16> pshufbMask;
5713
5714     // If we have elements from both input vectors, set the high bit of the
5715     // shuffle mask element to zero out elements that come from V2 in the V1
5716     // mask, and elements that come from V1 in the V2 mask, so that the two
5717     // results can be OR'd together.
5718     bool TwoInputs = V1Used && V2Used;
5719     for (unsigned i = 0; i != 8; ++i) {
5720       int EltIdx = MaskVals[i] * 2;
5721       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5722       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5723       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5724       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5725     }
5726     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5727     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5728                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5729                                  MVT::v16i8, &pshufbMask[0], 16));
5730     if (!TwoInputs)
5731       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5732
5733     // Calculate the shuffle mask for the second input, shuffle it, and
5734     // OR it with the first shuffled input.
5735     pshufbMask.clear();
5736     for (unsigned i = 0; i != 8; ++i) {
5737       int EltIdx = MaskVals[i] * 2;
5738       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5739       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5740       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5741       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5742     }
5743     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5744     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5745                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5746                                  MVT::v16i8, &pshufbMask[0], 16));
5747     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5748     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5749   }
5750
5751   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5752   // and update MaskVals with new element order.
5753   std::bitset<8> InOrder;
5754   if (BestLoQuad >= 0) {
5755     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5756     for (int i = 0; i != 4; ++i) {
5757       int idx = MaskVals[i];
5758       if (idx < 0) {
5759         InOrder.set(i);
5760       } else if ((idx / 4) == BestLoQuad) {
5761         MaskV[i] = idx & 3;
5762         InOrder.set(i);
5763       }
5764     }
5765     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5766                                 &MaskV[0]);
5767
5768     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5769       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5770       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5771                                   NewV.getOperand(0),
5772                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5773     }
5774   }
5775
5776   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5777   // and update MaskVals with the new element order.
5778   if (BestHiQuad >= 0) {
5779     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5780     for (unsigned i = 4; i != 8; ++i) {
5781       int idx = MaskVals[i];
5782       if (idx < 0) {
5783         InOrder.set(i);
5784       } else if ((idx / 4) == BestHiQuad) {
5785         MaskV[i] = (idx & 3) + 4;
5786         InOrder.set(i);
5787       }
5788     }
5789     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5790                                 &MaskV[0]);
5791
5792     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5793       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5794       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5795                                   NewV.getOperand(0),
5796                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5797     }
5798   }
5799
5800   // In case BestHi & BestLo were both -1, which means each quadword has a word
5801   // from each of the four input quadwords, calculate the InOrder bitvector now
5802   // before falling through to the insert/extract cleanup.
5803   if (BestLoQuad == -1 && BestHiQuad == -1) {
5804     NewV = V1;
5805     for (int i = 0; i != 8; ++i)
5806       if (MaskVals[i] < 0 || MaskVals[i] == i)
5807         InOrder.set(i);
5808   }
5809
5810   // The other elements are put in the right place using pextrw and pinsrw.
5811   for (unsigned i = 0; i != 8; ++i) {
5812     if (InOrder[i])
5813       continue;
5814     int EltIdx = MaskVals[i];
5815     if (EltIdx < 0)
5816       continue;
5817     SDValue ExtOp = (EltIdx < 8) ?
5818       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5819                   DAG.getIntPtrConstant(EltIdx)) :
5820       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5821                   DAG.getIntPtrConstant(EltIdx - 8));
5822     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5823                        DAG.getIntPtrConstant(i));
5824   }
5825   return NewV;
5826 }
5827
5828 // v16i8 shuffles - Prefer shuffles in the following order:
5829 // 1. [ssse3] 1 x pshufb
5830 // 2. [ssse3] 2 x pshufb + 1 x por
5831 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5832 static
5833 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5834                                  SelectionDAG &DAG,
5835                                  const X86TargetLowering &TLI) {
5836   SDValue V1 = SVOp->getOperand(0);
5837   SDValue V2 = SVOp->getOperand(1);
5838   DebugLoc dl = SVOp->getDebugLoc();
5839   ArrayRef<int> MaskVals = SVOp->getMask();
5840
5841   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5842
5843   // If we have SSSE3, case 1 is generated when all result bytes come from
5844   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5845   // present, fall back to case 3.
5846
5847   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5848   if (TLI.getSubtarget()->hasSSSE3()) {
5849     SmallVector<SDValue,16> pshufbMask;
5850
5851     // If all result elements are from one input vector, then only translate
5852     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5853     //
5854     // Otherwise, we have elements from both input vectors, and must zero out
5855     // elements that come from V2 in the first mask, and V1 in the second mask
5856     // so that we can OR them together.
5857     for (unsigned i = 0; i != 16; ++i) {
5858       int EltIdx = MaskVals[i];
5859       if (EltIdx < 0 || EltIdx >= 16)
5860         EltIdx = 0x80;
5861       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5862     }
5863     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5864                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5865                                  MVT::v16i8, &pshufbMask[0], 16));
5866     if (V2IsUndef)
5867       return V1;
5868
5869     // Calculate the shuffle mask for the second input, shuffle it, and
5870     // OR it with the first shuffled input.
5871     pshufbMask.clear();
5872     for (unsigned i = 0; i != 16; ++i) {
5873       int EltIdx = MaskVals[i];
5874       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5875       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5876     }
5877     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5878                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5879                                  MVT::v16i8, &pshufbMask[0], 16));
5880     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5881   }
5882
5883   // No SSSE3 - Calculate in place words and then fix all out of place words
5884   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5885   // the 16 different words that comprise the two doublequadword input vectors.
5886   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5887   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5888   SDValue NewV = V1;
5889   for (int i = 0; i != 8; ++i) {
5890     int Elt0 = MaskVals[i*2];
5891     int Elt1 = MaskVals[i*2+1];
5892
5893     // This word of the result is all undef, skip it.
5894     if (Elt0 < 0 && Elt1 < 0)
5895       continue;
5896
5897     // This word of the result is already in the correct place, skip it.
5898     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5899       continue;
5900
5901     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5902     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5903     SDValue InsElt;
5904
5905     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5906     // using a single extract together, load it and store it.
5907     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5908       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5909                            DAG.getIntPtrConstant(Elt1 / 2));
5910       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5911                         DAG.getIntPtrConstant(i));
5912       continue;
5913     }
5914
5915     // If Elt1 is defined, extract it from the appropriate source.  If the
5916     // source byte is not also odd, shift the extracted word left 8 bits
5917     // otherwise clear the bottom 8 bits if we need to do an or.
5918     if (Elt1 >= 0) {
5919       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5920                            DAG.getIntPtrConstant(Elt1 / 2));
5921       if ((Elt1 & 1) == 0)
5922         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5923                              DAG.getConstant(8,
5924                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5925       else if (Elt0 >= 0)
5926         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5927                              DAG.getConstant(0xFF00, MVT::i16));
5928     }
5929     // If Elt0 is defined, extract it from the appropriate source.  If the
5930     // source byte is not also even, shift the extracted word right 8 bits. If
5931     // Elt1 was also defined, OR the extracted values together before
5932     // inserting them in the result.
5933     if (Elt0 >= 0) {
5934       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5935                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5936       if ((Elt0 & 1) != 0)
5937         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5938                               DAG.getConstant(8,
5939                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5940       else if (Elt1 >= 0)
5941         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5942                              DAG.getConstant(0x00FF, MVT::i16));
5943       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5944                          : InsElt0;
5945     }
5946     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5947                        DAG.getIntPtrConstant(i));
5948   }
5949   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5950 }
5951
5952 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5953 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5954 /// done when every pair / quad of shuffle mask elements point to elements in
5955 /// the right sequence. e.g.
5956 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5957 static
5958 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5959                                  SelectionDAG &DAG, DebugLoc dl) {
5960   MVT VT = SVOp->getValueType(0).getSimpleVT();
5961   unsigned NumElems = VT.getVectorNumElements();
5962   MVT NewVT;
5963   unsigned Scale;
5964   switch (VT.SimpleTy) {
5965   default: llvm_unreachable("Unexpected!");
5966   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
5967   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
5968   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
5969   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
5970   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5971   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
5972   }
5973
5974   SmallVector<int, 8> MaskVec;
5975   for (unsigned i = 0; i != NumElems; i += Scale) {
5976     int StartIdx = -1;
5977     for (unsigned j = 0; j != Scale; ++j) {
5978       int EltIdx = SVOp->getMaskElt(i+j);
5979       if (EltIdx < 0)
5980         continue;
5981       if (StartIdx < 0)
5982         StartIdx = (EltIdx / Scale);
5983       if (EltIdx != (int)(StartIdx*Scale + j))
5984         return SDValue();
5985     }
5986     MaskVec.push_back(StartIdx);
5987   }
5988
5989   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
5990   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
5991   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5992 }
5993
5994 /// getVZextMovL - Return a zero-extending vector move low node.
5995 ///
5996 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5997                             SDValue SrcOp, SelectionDAG &DAG,
5998                             const X86Subtarget *Subtarget, DebugLoc dl) {
5999   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6000     LoadSDNode *LD = NULL;
6001     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6002       LD = dyn_cast<LoadSDNode>(SrcOp);
6003     if (!LD) {
6004       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6005       // instead.
6006       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6007       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6008           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6009           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6010           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6011         // PR2108
6012         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6013         return DAG.getNode(ISD::BITCAST, dl, VT,
6014                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6015                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6016                                                    OpVT,
6017                                                    SrcOp.getOperand(0)
6018                                                           .getOperand(0))));
6019       }
6020     }
6021   }
6022
6023   return DAG.getNode(ISD::BITCAST, dl, VT,
6024                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6025                                  DAG.getNode(ISD::BITCAST, dl,
6026                                              OpVT, SrcOp)));
6027 }
6028
6029 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6030 /// which could not be matched by any known target speficic shuffle
6031 static SDValue
6032 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6033
6034   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6035   if (NewOp.getNode())
6036     return NewOp;
6037
6038   EVT VT = SVOp->getValueType(0);
6039
6040   unsigned NumElems = VT.getVectorNumElements();
6041   unsigned NumLaneElems = NumElems / 2;
6042
6043   DebugLoc dl = SVOp->getDebugLoc();
6044   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6045   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6046   SDValue Output[2];
6047
6048   SmallVector<int, 16> Mask;
6049   for (unsigned l = 0; l < 2; ++l) {
6050     // Build a shuffle mask for the output, discovering on the fly which
6051     // input vectors to use as shuffle operands (recorded in InputUsed).
6052     // If building a suitable shuffle vector proves too hard, then bail
6053     // out with UseBuildVector set.
6054     bool UseBuildVector = false;
6055     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6056     unsigned LaneStart = l * NumLaneElems;
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         // the mask element does not index into any input vector.
6062         Mask.push_back(-1);
6063         continue;
6064       }
6065
6066       // The input vector this mask element indexes into.
6067       int Input = Idx / NumLaneElems;
6068
6069       // Turn the index into an offset from the start of the input vector.
6070       Idx -= Input * NumLaneElems;
6071
6072       // Find or create a shuffle vector operand to hold this input.
6073       unsigned OpNo;
6074       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6075         if (InputUsed[OpNo] == Input)
6076           // This input vector is already an operand.
6077           break;
6078         if (InputUsed[OpNo] < 0) {
6079           // Create a new operand for this input vector.
6080           InputUsed[OpNo] = Input;
6081           break;
6082         }
6083       }
6084
6085       if (OpNo >= array_lengthof(InputUsed)) {
6086         // More than two input vectors used!  Give up on trying to create a
6087         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6088         UseBuildVector = true;
6089         break;
6090       }
6091
6092       // Add the mask index for the new shuffle vector.
6093       Mask.push_back(Idx + OpNo * NumLaneElems);
6094     }
6095
6096     if (UseBuildVector) {
6097       SmallVector<SDValue, 16> SVOps;
6098       for (unsigned i = 0; i != NumLaneElems; ++i) {
6099         // The mask element.  This indexes into the input.
6100         int Idx = SVOp->getMaskElt(i+LaneStart);
6101         if (Idx < 0) {
6102           SVOps.push_back(DAG.getUNDEF(EltVT));
6103           continue;
6104         }
6105
6106         // The input vector this mask element indexes into.
6107         int Input = Idx / NumElems;
6108
6109         // Turn the index into an offset from the start of the input vector.
6110         Idx -= Input * NumElems;
6111
6112         // Extract the vector element by hand.
6113         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6114                                     SVOp->getOperand(Input),
6115                                     DAG.getIntPtrConstant(Idx)));
6116       }
6117
6118       // Construct the output using a BUILD_VECTOR.
6119       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6120                               SVOps.size());
6121     } else if (InputUsed[0] < 0) {
6122       // No input vectors were used! The result is undefined.
6123       Output[l] = DAG.getUNDEF(NVT);
6124     } else {
6125       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6126                                         (InputUsed[0] % 2) * NumLaneElems,
6127                                         DAG, dl);
6128       // If only one input was used, use an undefined vector for the other.
6129       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6130         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6131                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6132       // At least one input vector was used. Create a new shuffle vector.
6133       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6134     }
6135
6136     Mask.clear();
6137   }
6138
6139   // Concatenate the result back
6140   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6141 }
6142
6143 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6144 /// 4 elements, and match them with several different shuffle types.
6145 static SDValue
6146 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6147   SDValue V1 = SVOp->getOperand(0);
6148   SDValue V2 = SVOp->getOperand(1);
6149   DebugLoc dl = SVOp->getDebugLoc();
6150   EVT VT = SVOp->getValueType(0);
6151
6152   assert(VT.is128BitVector() && "Unsupported vector size");
6153
6154   std::pair<int, int> Locs[4];
6155   int Mask1[] = { -1, -1, -1, -1 };
6156   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6157
6158   unsigned NumHi = 0;
6159   unsigned NumLo = 0;
6160   for (unsigned i = 0; i != 4; ++i) {
6161     int Idx = PermMask[i];
6162     if (Idx < 0) {
6163       Locs[i] = std::make_pair(-1, -1);
6164     } else {
6165       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6166       if (Idx < 4) {
6167         Locs[i] = std::make_pair(0, NumLo);
6168         Mask1[NumLo] = Idx;
6169         NumLo++;
6170       } else {
6171         Locs[i] = std::make_pair(1, NumHi);
6172         if (2+NumHi < 4)
6173           Mask1[2+NumHi] = Idx;
6174         NumHi++;
6175       }
6176     }
6177   }
6178
6179   if (NumLo <= 2 && NumHi <= 2) {
6180     // If no more than two elements come from either vector. This can be
6181     // implemented with two shuffles. First shuffle gather the elements.
6182     // The second shuffle, which takes the first shuffle as both of its
6183     // vector operands, put the elements into the right order.
6184     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6185
6186     int Mask2[] = { -1, -1, -1, -1 };
6187
6188     for (unsigned i = 0; i != 4; ++i)
6189       if (Locs[i].first != -1) {
6190         unsigned Idx = (i < 2) ? 0 : 4;
6191         Idx += Locs[i].first * 2 + Locs[i].second;
6192         Mask2[i] = Idx;
6193       }
6194
6195     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6196   }
6197
6198   if (NumLo == 3 || NumHi == 3) {
6199     // Otherwise, we must have three elements from one vector, call it X, and
6200     // one element from the other, call it Y.  First, use a shufps to build an
6201     // intermediate vector with the one element from Y and the element from X
6202     // that will be in the same half in the final destination (the indexes don't
6203     // matter). Then, use a shufps to build the final vector, taking the half
6204     // containing the element from Y from the intermediate, and the other half
6205     // from X.
6206     if (NumHi == 3) {
6207       // Normalize it so the 3 elements come from V1.
6208       CommuteVectorShuffleMask(PermMask, 4);
6209       std::swap(V1, V2);
6210     }
6211
6212     // Find the element from V2.
6213     unsigned HiIndex;
6214     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6215       int Val = PermMask[HiIndex];
6216       if (Val < 0)
6217         continue;
6218       if (Val >= 4)
6219         break;
6220     }
6221
6222     Mask1[0] = PermMask[HiIndex];
6223     Mask1[1] = -1;
6224     Mask1[2] = PermMask[HiIndex^1];
6225     Mask1[3] = -1;
6226     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6227
6228     if (HiIndex >= 2) {
6229       Mask1[0] = PermMask[0];
6230       Mask1[1] = PermMask[1];
6231       Mask1[2] = HiIndex & 1 ? 6 : 4;
6232       Mask1[3] = HiIndex & 1 ? 4 : 6;
6233       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6234     }
6235
6236     Mask1[0] = HiIndex & 1 ? 2 : 0;
6237     Mask1[1] = HiIndex & 1 ? 0 : 2;
6238     Mask1[2] = PermMask[2];
6239     Mask1[3] = PermMask[3];
6240     if (Mask1[2] >= 0)
6241       Mask1[2] += 4;
6242     if (Mask1[3] >= 0)
6243       Mask1[3] += 4;
6244     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6245   }
6246
6247   // Break it into (shuffle shuffle_hi, shuffle_lo).
6248   int LoMask[] = { -1, -1, -1, -1 };
6249   int HiMask[] = { -1, -1, -1, -1 };
6250
6251   int *MaskPtr = LoMask;
6252   unsigned MaskIdx = 0;
6253   unsigned LoIdx = 0;
6254   unsigned HiIdx = 2;
6255   for (unsigned i = 0; i != 4; ++i) {
6256     if (i == 2) {
6257       MaskPtr = HiMask;
6258       MaskIdx = 1;
6259       LoIdx = 0;
6260       HiIdx = 2;
6261     }
6262     int Idx = PermMask[i];
6263     if (Idx < 0) {
6264       Locs[i] = std::make_pair(-1, -1);
6265     } else if (Idx < 4) {
6266       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6267       MaskPtr[LoIdx] = Idx;
6268       LoIdx++;
6269     } else {
6270       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6271       MaskPtr[HiIdx] = Idx;
6272       HiIdx++;
6273     }
6274   }
6275
6276   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6277   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6278   int MaskOps[] = { -1, -1, -1, -1 };
6279   for (unsigned i = 0; i != 4; ++i)
6280     if (Locs[i].first != -1)
6281       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6282   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6283 }
6284
6285 static bool MayFoldVectorLoad(SDValue V) {
6286   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6287     V = V.getOperand(0);
6288   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6289     V = V.getOperand(0);
6290   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6291       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6292     // BUILD_VECTOR (load), undef
6293     V = V.getOperand(0);
6294   if (MayFoldLoad(V))
6295     return true;
6296   return false;
6297 }
6298
6299 // FIXME: the version above should always be used. Since there's
6300 // a bug where several vector shuffles can't be folded because the
6301 // DAG is not updated during lowering and a node claims to have two
6302 // uses while it only has one, use this version, and let isel match
6303 // another instruction if the load really happens to have more than
6304 // one use. Remove this version after this bug get fixed.
6305 // rdar://8434668, PR8156
6306 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6307   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6308     V = V.getOperand(0);
6309   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6310     V = V.getOperand(0);
6311   if (ISD::isNormalLoad(V.getNode()))
6312     return true;
6313   return false;
6314 }
6315
6316 static
6317 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6318   EVT VT = Op.getValueType();
6319
6320   // Canonizalize to v2f64.
6321   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6322   return DAG.getNode(ISD::BITCAST, dl, VT,
6323                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6324                                           V1, DAG));
6325 }
6326
6327 static
6328 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6329                         bool HasSSE2) {
6330   SDValue V1 = Op.getOperand(0);
6331   SDValue V2 = Op.getOperand(1);
6332   EVT VT = Op.getValueType();
6333
6334   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6335
6336   if (HasSSE2 && VT == MVT::v2f64)
6337     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6338
6339   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6340   return DAG.getNode(ISD::BITCAST, dl, VT,
6341                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6342                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6343                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6344 }
6345
6346 static
6347 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6348   SDValue V1 = Op.getOperand(0);
6349   SDValue V2 = Op.getOperand(1);
6350   EVT VT = Op.getValueType();
6351
6352   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6353          "unsupported shuffle type");
6354
6355   if (V2.getOpcode() == ISD::UNDEF)
6356     V2 = V1;
6357
6358   // v4i32 or v4f32
6359   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6360 }
6361
6362 static
6363 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6364   SDValue V1 = Op.getOperand(0);
6365   SDValue V2 = Op.getOperand(1);
6366   EVT VT = Op.getValueType();
6367   unsigned NumElems = VT.getVectorNumElements();
6368
6369   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6370   // operand of these instructions is only memory, so check if there's a
6371   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6372   // same masks.
6373   bool CanFoldLoad = false;
6374
6375   // Trivial case, when V2 comes from a load.
6376   if (MayFoldVectorLoad(V2))
6377     CanFoldLoad = true;
6378
6379   // When V1 is a load, it can be folded later into a store in isel, example:
6380   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6381   //    turns into:
6382   //  (MOVLPSmr addr:$src1, VR128:$src2)
6383   // So, recognize this potential and also use MOVLPS or MOVLPD
6384   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6385     CanFoldLoad = true;
6386
6387   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6388   if (CanFoldLoad) {
6389     if (HasSSE2 && NumElems == 2)
6390       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6391
6392     if (NumElems == 4)
6393       // If we don't care about the second element, proceed to use movss.
6394       if (SVOp->getMaskElt(1) != -1)
6395         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6396   }
6397
6398   // movl and movlp will both match v2i64, but v2i64 is never matched by
6399   // movl earlier because we make it strict to avoid messing with the movlp load
6400   // folding logic (see the code above getMOVLP call). Match it here then,
6401   // this is horrible, but will stay like this until we move all shuffle
6402   // matching to x86 specific nodes. Note that for the 1st condition all
6403   // types are matched with movsd.
6404   if (HasSSE2) {
6405     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6406     // as to remove this logic from here, as much as possible
6407     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6408       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6409     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6410   }
6411
6412   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6413
6414   // Invert the operand order and use SHUFPS to match it.
6415   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6416                               getShuffleSHUFImmediate(SVOp), DAG);
6417 }
6418
6419 SDValue
6420 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6421   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6422   EVT VT = Op.getValueType();
6423   DebugLoc dl = Op.getDebugLoc();
6424   SDValue V1 = Op.getOperand(0);
6425   SDValue V2 = Op.getOperand(1);
6426
6427   if (isZeroShuffle(SVOp))
6428     return getZeroVector(VT, Subtarget, DAG, dl);
6429
6430   // Handle splat operations
6431   if (SVOp->isSplat()) {
6432     unsigned NumElem = VT.getVectorNumElements();
6433     int Size = VT.getSizeInBits();
6434
6435     // Use vbroadcast whenever the splat comes from a foldable load
6436     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6437     if (Broadcast.getNode())
6438       return Broadcast;
6439
6440     // Handle splats by matching through known shuffle masks
6441     if ((Size == 128 && NumElem <= 4) ||
6442         (Size == 256 && NumElem < 8))
6443       return SDValue();
6444
6445     // All remaning splats are promoted to target supported vector shuffles.
6446     return PromoteSplat(SVOp, DAG);
6447   }
6448
6449   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6450   // do it!
6451   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6452       VT == MVT::v16i16 || VT == MVT::v32i8) {
6453     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6454     if (NewOp.getNode())
6455       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6456   } else if ((VT == MVT::v4i32 ||
6457              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6458     // FIXME: Figure out a cleaner way to do this.
6459     // Try to make use of movq to zero out the top part.
6460     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6461       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6462       if (NewOp.getNode()) {
6463         EVT NewVT = NewOp.getValueType();
6464         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6465                                NewVT, true, false))
6466           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6467                               DAG, Subtarget, dl);
6468       }
6469     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6470       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6471       if (NewOp.getNode()) {
6472         EVT NewVT = NewOp.getValueType();
6473         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6474           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6475                               DAG, Subtarget, dl);
6476       }
6477     }
6478   }
6479   return SDValue();
6480 }
6481
6482 SDValue
6483 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6484   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6485   SDValue V1 = Op.getOperand(0);
6486   SDValue V2 = Op.getOperand(1);
6487   EVT VT = Op.getValueType();
6488   DebugLoc dl = Op.getDebugLoc();
6489   unsigned NumElems = VT.getVectorNumElements();
6490   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6491   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6492   bool V1IsSplat = false;
6493   bool V2IsSplat = false;
6494   bool HasSSE2 = Subtarget->hasSSE2();
6495   bool HasAVX    = Subtarget->hasAVX();
6496   bool HasAVX2   = Subtarget->hasAVX2();
6497   MachineFunction &MF = DAG.getMachineFunction();
6498   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6499
6500   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6501
6502   if (V1IsUndef && V2IsUndef)
6503     return DAG.getUNDEF(VT);
6504
6505   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6506
6507   // Vector shuffle lowering takes 3 steps:
6508   //
6509   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6510   //    narrowing and commutation of operands should be handled.
6511   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6512   //    shuffle nodes.
6513   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6514   //    so the shuffle can be broken into other shuffles and the legalizer can
6515   //    try the lowering again.
6516   //
6517   // The general idea is that no vector_shuffle operation should be left to
6518   // be matched during isel, all of them must be converted to a target specific
6519   // node here.
6520
6521   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6522   // narrowing and commutation of operands should be handled. The actual code
6523   // doesn't include all of those, work in progress...
6524   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6525   if (NewOp.getNode())
6526     return NewOp;
6527
6528   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6529
6530   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6531   // unpckh_undef). Only use pshufd if speed is more important than size.
6532   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6533     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6534   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6535     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6536
6537   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6538       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6539     return getMOVDDup(Op, dl, V1, DAG);
6540
6541   if (isMOVHLPS_v_undef_Mask(M, VT))
6542     return getMOVHighToLow(Op, dl, DAG);
6543
6544   // Use to match splats
6545   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6546       (VT == MVT::v2f64 || VT == MVT::v2i64))
6547     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6548
6549   if (isPSHUFDMask(M, VT)) {
6550     // The actual implementation will match the mask in the if above and then
6551     // during isel it can match several different instructions, not only pshufd
6552     // as its name says, sad but true, emulate the behavior for now...
6553     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6554       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6555
6556     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6557
6558     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6559       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6560
6561     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6562       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6563
6564     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6565                                 TargetMask, DAG);
6566   }
6567
6568   // Check if this can be converted into a logical shift.
6569   bool isLeft = false;
6570   unsigned ShAmt = 0;
6571   SDValue ShVal;
6572   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6573   if (isShift && ShVal.hasOneUse()) {
6574     // If the shifted value has multiple uses, it may be cheaper to use
6575     // v_set0 + movlhps or movhlps, etc.
6576     EVT EltVT = VT.getVectorElementType();
6577     ShAmt *= EltVT.getSizeInBits();
6578     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6579   }
6580
6581   if (isMOVLMask(M, VT)) {
6582     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6583       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6584     if (!isMOVLPMask(M, VT)) {
6585       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6586         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6587
6588       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6589         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6590     }
6591   }
6592
6593   // FIXME: fold these into legal mask.
6594   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6595     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6596
6597   if (isMOVHLPSMask(M, VT))
6598     return getMOVHighToLow(Op, dl, DAG);
6599
6600   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6601     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6602
6603   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6604     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6605
6606   if (isMOVLPMask(M, VT))
6607     return getMOVLP(Op, dl, DAG, HasSSE2);
6608
6609   if (ShouldXformToMOVHLPS(M, VT) ||
6610       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6611     return CommuteVectorShuffle(SVOp, DAG);
6612
6613   if (isShift) {
6614     // No better options. Use a vshldq / vsrldq.
6615     EVT EltVT = VT.getVectorElementType();
6616     ShAmt *= EltVT.getSizeInBits();
6617     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6618   }
6619
6620   bool Commuted = false;
6621   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6622   // 1,1,1,1 -> v8i16 though.
6623   V1IsSplat = isSplatVector(V1.getNode());
6624   V2IsSplat = isSplatVector(V2.getNode());
6625
6626   // Canonicalize the splat or undef, if present, to be on the RHS.
6627   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6628     CommuteVectorShuffleMask(M, NumElems);
6629     std::swap(V1, V2);
6630     std::swap(V1IsSplat, V2IsSplat);
6631     Commuted = true;
6632   }
6633
6634   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6635     // Shuffling low element of v1 into undef, just return v1.
6636     if (V2IsUndef)
6637       return V1;
6638     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6639     // the instruction selector will not match, so get a canonical MOVL with
6640     // swapped operands to undo the commute.
6641     return getMOVL(DAG, dl, VT, V2, V1);
6642   }
6643
6644   if (isUNPCKLMask(M, VT, HasAVX2))
6645     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6646
6647   if (isUNPCKHMask(M, VT, HasAVX2))
6648     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6649
6650   if (V2IsSplat) {
6651     // Normalize mask so all entries that point to V2 points to its first
6652     // element then try to match unpck{h|l} again. If match, return a
6653     // new vector_shuffle with the corrected mask.p
6654     SmallVector<int, 8> NewMask(M.begin(), M.end());
6655     NormalizeMask(NewMask, NumElems);
6656     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6657       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6658     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6659       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6660   }
6661
6662   if (Commuted) {
6663     // Commute is back and try unpck* again.
6664     // FIXME: this seems wrong.
6665     CommuteVectorShuffleMask(M, NumElems);
6666     std::swap(V1, V2);
6667     std::swap(V1IsSplat, V2IsSplat);
6668     Commuted = false;
6669
6670     if (isUNPCKLMask(M, VT, HasAVX2))
6671       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6672
6673     if (isUNPCKHMask(M, VT, HasAVX2))
6674       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6675   }
6676
6677   // Normalize the node to match x86 shuffle ops if needed
6678   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6679     return CommuteVectorShuffle(SVOp, DAG);
6680
6681   // The checks below are all present in isShuffleMaskLegal, but they are
6682   // inlined here right now to enable us to directly emit target specific
6683   // nodes, and remove one by one until they don't return Op anymore.
6684
6685   if (isPALIGNRMask(M, VT, Subtarget))
6686     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6687                                 getShufflePALIGNRImmediate(SVOp),
6688                                 DAG);
6689
6690   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6691       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6692     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6693       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6694   }
6695
6696   if (isPSHUFHWMask(M, VT, HasAVX2))
6697     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6698                                 getShufflePSHUFHWImmediate(SVOp),
6699                                 DAG);
6700
6701   if (isPSHUFLWMask(M, VT, HasAVX2))
6702     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6703                                 getShufflePSHUFLWImmediate(SVOp),
6704                                 DAG);
6705
6706   if (isSHUFPMask(M, VT, HasAVX))
6707     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6708                                 getShuffleSHUFImmediate(SVOp), DAG);
6709
6710   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6711     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6712   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6713     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6714
6715   //===--------------------------------------------------------------------===//
6716   // Generate target specific nodes for 128 or 256-bit shuffles only
6717   // supported in the AVX instruction set.
6718   //
6719
6720   // Handle VMOVDDUPY permutations
6721   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6722     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6723
6724   // Handle VPERMILPS/D* permutations
6725   if (isVPERMILPMask(M, VT, HasAVX)) {
6726     if (HasAVX2 && VT == MVT::v8i32)
6727       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6728                                   getShuffleSHUFImmediate(SVOp), DAG);
6729     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6730                                 getShuffleSHUFImmediate(SVOp), DAG);
6731   }
6732
6733   // Handle VPERM2F128/VPERM2I128 permutations
6734   if (isVPERM2X128Mask(M, VT, HasAVX))
6735     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6736                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6737
6738   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6739   if (BlendOp.getNode())
6740     return BlendOp;
6741
6742   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6743     SmallVector<SDValue, 8> permclMask;
6744     for (unsigned i = 0; i != 8; ++i) {
6745       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6746     }
6747     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6748                                &permclMask[0], 8);
6749     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6750     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6751                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6752   }
6753
6754   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6755     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6756                                 getShuffleCLImmediate(SVOp), DAG);
6757
6758
6759   //===--------------------------------------------------------------------===//
6760   // Since no target specific shuffle was selected for this generic one,
6761   // lower it into other known shuffles. FIXME: this isn't true yet, but
6762   // this is the plan.
6763   //
6764
6765   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6766   if (VT == MVT::v8i16) {
6767     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6768     if (NewOp.getNode())
6769       return NewOp;
6770   }
6771
6772   if (VT == MVT::v16i8) {
6773     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6774     if (NewOp.getNode())
6775       return NewOp;
6776   }
6777
6778   // Handle all 128-bit wide vectors with 4 elements, and match them with
6779   // several different shuffle types.
6780   if (NumElems == 4 && VT.is128BitVector())
6781     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6782
6783   // Handle general 256-bit shuffles
6784   if (VT.is256BitVector())
6785     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6786
6787   return SDValue();
6788 }
6789
6790 SDValue
6791 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6792                                                 SelectionDAG &DAG) const {
6793   EVT VT = Op.getValueType();
6794   DebugLoc dl = Op.getDebugLoc();
6795
6796   if (!Op.getOperand(0).getValueType().is128BitVector())
6797     return SDValue();
6798
6799   if (VT.getSizeInBits() == 8) {
6800     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6801                                     Op.getOperand(0), Op.getOperand(1));
6802     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6803                                     DAG.getValueType(VT));
6804     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6805   }
6806
6807   if (VT.getSizeInBits() == 16) {
6808     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6809     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6810     if (Idx == 0)
6811       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6812                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6813                                      DAG.getNode(ISD::BITCAST, dl,
6814                                                  MVT::v4i32,
6815                                                  Op.getOperand(0)),
6816                                      Op.getOperand(1)));
6817     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6818                                     Op.getOperand(0), Op.getOperand(1));
6819     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6820                                     DAG.getValueType(VT));
6821     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6822   }
6823
6824   if (VT == MVT::f32) {
6825     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6826     // the result back to FR32 register. It's only worth matching if the
6827     // result has a single use which is a store or a bitcast to i32.  And in
6828     // the case of a store, it's not worth it if the index is a constant 0,
6829     // because a MOVSSmr can be used instead, which is smaller and faster.
6830     if (!Op.hasOneUse())
6831       return SDValue();
6832     SDNode *User = *Op.getNode()->use_begin();
6833     if ((User->getOpcode() != ISD::STORE ||
6834          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6835           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6836         (User->getOpcode() != ISD::BITCAST ||
6837          User->getValueType(0) != MVT::i32))
6838       return SDValue();
6839     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6840                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6841                                               Op.getOperand(0)),
6842                                               Op.getOperand(1));
6843     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6844   }
6845
6846   if (VT == MVT::i32 || VT == MVT::i64) {
6847     // ExtractPS/pextrq works with constant index.
6848     if (isa<ConstantSDNode>(Op.getOperand(1)))
6849       return Op;
6850   }
6851   return SDValue();
6852 }
6853
6854
6855 SDValue
6856 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6857                                            SelectionDAG &DAG) const {
6858   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6859     return SDValue();
6860
6861   SDValue Vec = Op.getOperand(0);
6862   EVT VecVT = Vec.getValueType();
6863
6864   // If this is a 256-bit vector result, first extract the 128-bit vector and
6865   // then extract the element from the 128-bit vector.
6866   if (VecVT.is256BitVector()) {
6867     DebugLoc dl = Op.getNode()->getDebugLoc();
6868     unsigned NumElems = VecVT.getVectorNumElements();
6869     SDValue Idx = Op.getOperand(1);
6870     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6871
6872     // Get the 128-bit vector.
6873     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6874
6875     if (IdxVal >= NumElems/2)
6876       IdxVal -= NumElems/2;
6877     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6878                        DAG.getConstant(IdxVal, MVT::i32));
6879   }
6880
6881   assert(VecVT.is128BitVector() && "Unexpected vector length");
6882
6883   if (Subtarget->hasSSE41()) {
6884     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6885     if (Res.getNode())
6886       return Res;
6887   }
6888
6889   EVT VT = Op.getValueType();
6890   DebugLoc dl = Op.getDebugLoc();
6891   // TODO: handle v16i8.
6892   if (VT.getSizeInBits() == 16) {
6893     SDValue Vec = Op.getOperand(0);
6894     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6895     if (Idx == 0)
6896       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6897                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6898                                      DAG.getNode(ISD::BITCAST, dl,
6899                                                  MVT::v4i32, Vec),
6900                                      Op.getOperand(1)));
6901     // Transform it so it match pextrw which produces a 32-bit result.
6902     EVT EltVT = MVT::i32;
6903     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6904                                     Op.getOperand(0), Op.getOperand(1));
6905     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6906                                     DAG.getValueType(VT));
6907     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6908   }
6909
6910   if (VT.getSizeInBits() == 32) {
6911     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6912     if (Idx == 0)
6913       return Op;
6914
6915     // SHUFPS the element to the lowest double word, then movss.
6916     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6917     EVT VVT = Op.getOperand(0).getValueType();
6918     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6919                                        DAG.getUNDEF(VVT), Mask);
6920     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6921                        DAG.getIntPtrConstant(0));
6922   }
6923
6924   if (VT.getSizeInBits() == 64) {
6925     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6926     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6927     //        to match extract_elt for f64.
6928     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6929     if (Idx == 0)
6930       return Op;
6931
6932     // UNPCKHPD the element to the lowest double word, then movsd.
6933     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6934     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6935     int Mask[2] = { 1, -1 };
6936     EVT VVT = Op.getOperand(0).getValueType();
6937     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6938                                        DAG.getUNDEF(VVT), Mask);
6939     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6940                        DAG.getIntPtrConstant(0));
6941   }
6942
6943   return SDValue();
6944 }
6945
6946 SDValue
6947 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6948                                                SelectionDAG &DAG) const {
6949   EVT VT = Op.getValueType();
6950   EVT EltVT = VT.getVectorElementType();
6951   DebugLoc dl = Op.getDebugLoc();
6952
6953   SDValue N0 = Op.getOperand(0);
6954   SDValue N1 = Op.getOperand(1);
6955   SDValue N2 = Op.getOperand(2);
6956
6957   if (!VT.is128BitVector())
6958     return SDValue();
6959
6960   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6961       isa<ConstantSDNode>(N2)) {
6962     unsigned Opc;
6963     if (VT == MVT::v8i16)
6964       Opc = X86ISD::PINSRW;
6965     else if (VT == MVT::v16i8)
6966       Opc = X86ISD::PINSRB;
6967     else
6968       Opc = X86ISD::PINSRB;
6969
6970     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6971     // argument.
6972     if (N1.getValueType() != MVT::i32)
6973       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6974     if (N2.getValueType() != MVT::i32)
6975       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6976     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6977   }
6978
6979   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6980     // Bits [7:6] of the constant are the source select.  This will always be
6981     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6982     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6983     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6984     // Bits [5:4] of the constant are the destination select.  This is the
6985     //  value of the incoming immediate.
6986     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6987     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6988     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6989     // Create this as a scalar to vector..
6990     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6991     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6992   }
6993
6994   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
6995     // PINSR* works with constant index.
6996     return Op;
6997   }
6998   return SDValue();
6999 }
7000
7001 SDValue
7002 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7003   EVT VT = Op.getValueType();
7004   EVT EltVT = VT.getVectorElementType();
7005
7006   DebugLoc dl = Op.getDebugLoc();
7007   SDValue N0 = Op.getOperand(0);
7008   SDValue N1 = Op.getOperand(1);
7009   SDValue N2 = Op.getOperand(2);
7010
7011   // If this is a 256-bit vector result, first extract the 128-bit vector,
7012   // insert the element into the extracted half and then place it back.
7013   if (VT.is256BitVector()) {
7014     if (!isa<ConstantSDNode>(N2))
7015       return SDValue();
7016
7017     // Get the desired 128-bit vector half.
7018     unsigned NumElems = VT.getVectorNumElements();
7019     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7020     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7021
7022     // Insert the element into the desired half.
7023     bool Upper = IdxVal >= NumElems/2;
7024     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7025                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7026
7027     // Insert the changed part back to the 256-bit vector
7028     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7029   }
7030
7031   if (Subtarget->hasSSE41())
7032     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7033
7034   if (EltVT == MVT::i8)
7035     return SDValue();
7036
7037   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7038     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7039     // as its second argument.
7040     if (N1.getValueType() != MVT::i32)
7041       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7042     if (N2.getValueType() != MVT::i32)
7043       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7044     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7045   }
7046   return SDValue();
7047 }
7048
7049 SDValue
7050 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7051   LLVMContext *Context = DAG.getContext();
7052   DebugLoc dl = Op.getDebugLoc();
7053   EVT OpVT = Op.getValueType();
7054
7055   // If this is a 256-bit vector result, first insert into a 128-bit
7056   // vector and then insert into the 256-bit vector.
7057   if (!OpVT.is128BitVector()) {
7058     // Insert into a 128-bit vector.
7059     EVT VT128 = EVT::getVectorVT(*Context,
7060                                  OpVT.getVectorElementType(),
7061                                  OpVT.getVectorNumElements() / 2);
7062
7063     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7064
7065     // Insert the 128-bit vector.
7066     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7067   }
7068
7069   if (OpVT == MVT::v1i64 &&
7070       Op.getOperand(0).getValueType() == MVT::i64)
7071     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7072
7073   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7074   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7075   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7076                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7077 }
7078
7079 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7080 // a simple subregister reference or explicit instructions to grab
7081 // upper bits of a vector.
7082 SDValue
7083 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7084   if (Subtarget->hasAVX()) {
7085     DebugLoc dl = Op.getNode()->getDebugLoc();
7086     SDValue Vec = Op.getNode()->getOperand(0);
7087     SDValue Idx = Op.getNode()->getOperand(1);
7088
7089     if (Op.getNode()->getValueType(0).is128BitVector() &&
7090         Vec.getNode()->getValueType(0).is256BitVector() &&
7091         isa<ConstantSDNode>(Idx)) {
7092       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7093       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7094     }
7095   }
7096   return SDValue();
7097 }
7098
7099 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7100 // simple superregister reference or explicit instructions to insert
7101 // the upper bits of a vector.
7102 SDValue
7103 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7104   if (Subtarget->hasAVX()) {
7105     DebugLoc dl = Op.getNode()->getDebugLoc();
7106     SDValue Vec = Op.getNode()->getOperand(0);
7107     SDValue SubVec = Op.getNode()->getOperand(1);
7108     SDValue Idx = Op.getNode()->getOperand(2);
7109
7110     if (Op.getNode()->getValueType(0).is256BitVector() &&
7111         SubVec.getNode()->getValueType(0).is128BitVector() &&
7112         isa<ConstantSDNode>(Idx)) {
7113       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7114       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7115     }
7116   }
7117   return SDValue();
7118 }
7119
7120 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7121 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7122 // one of the above mentioned nodes. It has to be wrapped because otherwise
7123 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7124 // be used to form addressing mode. These wrapped nodes will be selected
7125 // into MOV32ri.
7126 SDValue
7127 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7128   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7129
7130   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7131   // global base reg.
7132   unsigned char OpFlag = 0;
7133   unsigned WrapperKind = X86ISD::Wrapper;
7134   CodeModel::Model M = getTargetMachine().getCodeModel();
7135
7136   if (Subtarget->isPICStyleRIPRel() &&
7137       (M == CodeModel::Small || M == CodeModel::Kernel))
7138     WrapperKind = X86ISD::WrapperRIP;
7139   else if (Subtarget->isPICStyleGOT())
7140     OpFlag = X86II::MO_GOTOFF;
7141   else if (Subtarget->isPICStyleStubPIC())
7142     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7143
7144   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7145                                              CP->getAlignment(),
7146                                              CP->getOffset(), OpFlag);
7147   DebugLoc DL = CP->getDebugLoc();
7148   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7149   // With PIC, the address is actually $g + Offset.
7150   if (OpFlag) {
7151     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7152                          DAG.getNode(X86ISD::GlobalBaseReg,
7153                                      DebugLoc(), getPointerTy()),
7154                          Result);
7155   }
7156
7157   return Result;
7158 }
7159
7160 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7161   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7162
7163   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7164   // global base reg.
7165   unsigned char OpFlag = 0;
7166   unsigned WrapperKind = X86ISD::Wrapper;
7167   CodeModel::Model M = getTargetMachine().getCodeModel();
7168
7169   if (Subtarget->isPICStyleRIPRel() &&
7170       (M == CodeModel::Small || M == CodeModel::Kernel))
7171     WrapperKind = X86ISD::WrapperRIP;
7172   else if (Subtarget->isPICStyleGOT())
7173     OpFlag = X86II::MO_GOTOFF;
7174   else if (Subtarget->isPICStyleStubPIC())
7175     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7176
7177   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7178                                           OpFlag);
7179   DebugLoc DL = JT->getDebugLoc();
7180   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7181
7182   // With PIC, the address is actually $g + Offset.
7183   if (OpFlag)
7184     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7185                          DAG.getNode(X86ISD::GlobalBaseReg,
7186                                      DebugLoc(), getPointerTy()),
7187                          Result);
7188
7189   return Result;
7190 }
7191
7192 SDValue
7193 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7194   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7195
7196   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7197   // global base reg.
7198   unsigned char OpFlag = 0;
7199   unsigned WrapperKind = X86ISD::Wrapper;
7200   CodeModel::Model M = getTargetMachine().getCodeModel();
7201
7202   if (Subtarget->isPICStyleRIPRel() &&
7203       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7204     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7205       OpFlag = X86II::MO_GOTPCREL;
7206     WrapperKind = X86ISD::WrapperRIP;
7207   } else if (Subtarget->isPICStyleGOT()) {
7208     OpFlag = X86II::MO_GOT;
7209   } else if (Subtarget->isPICStyleStubPIC()) {
7210     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7211   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7212     OpFlag = X86II::MO_DARWIN_NONLAZY;
7213   }
7214
7215   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7216
7217   DebugLoc DL = Op.getDebugLoc();
7218   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7219
7220
7221   // With PIC, the address is actually $g + Offset.
7222   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7223       !Subtarget->is64Bit()) {
7224     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7225                          DAG.getNode(X86ISD::GlobalBaseReg,
7226                                      DebugLoc(), getPointerTy()),
7227                          Result);
7228   }
7229
7230   // For symbols that require a load from a stub to get the address, emit the
7231   // load.
7232   if (isGlobalStubReference(OpFlag))
7233     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7234                          MachinePointerInfo::getGOT(), false, false, false, 0);
7235
7236   return Result;
7237 }
7238
7239 SDValue
7240 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7241   // Create the TargetBlockAddressAddress node.
7242   unsigned char OpFlags =
7243     Subtarget->ClassifyBlockAddressReference();
7244   CodeModel::Model M = getTargetMachine().getCodeModel();
7245   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7246   DebugLoc dl = Op.getDebugLoc();
7247   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7248                                        /*isTarget=*/true, OpFlags);
7249
7250   if (Subtarget->isPICStyleRIPRel() &&
7251       (M == CodeModel::Small || M == CodeModel::Kernel))
7252     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7253   else
7254     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7255
7256   // With PIC, the address is actually $g + Offset.
7257   if (isGlobalRelativeToPICBase(OpFlags)) {
7258     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7259                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7260                          Result);
7261   }
7262
7263   return Result;
7264 }
7265
7266 SDValue
7267 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7268                                       int64_t Offset,
7269                                       SelectionDAG &DAG) const {
7270   // Create the TargetGlobalAddress node, folding in the constant
7271   // offset if it is legal.
7272   unsigned char OpFlags =
7273     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7274   CodeModel::Model M = getTargetMachine().getCodeModel();
7275   SDValue Result;
7276   if (OpFlags == X86II::MO_NO_FLAG &&
7277       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7278     // A direct static reference to a global.
7279     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7280     Offset = 0;
7281   } else {
7282     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7283   }
7284
7285   if (Subtarget->isPICStyleRIPRel() &&
7286       (M == CodeModel::Small || M == CodeModel::Kernel))
7287     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7288   else
7289     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7290
7291   // With PIC, the address is actually $g + Offset.
7292   if (isGlobalRelativeToPICBase(OpFlags)) {
7293     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7294                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7295                          Result);
7296   }
7297
7298   // For globals that require a load from a stub to get the address, emit the
7299   // load.
7300   if (isGlobalStubReference(OpFlags))
7301     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7302                          MachinePointerInfo::getGOT(), false, false, false, 0);
7303
7304   // If there was a non-zero offset that we didn't fold, create an explicit
7305   // addition for it.
7306   if (Offset != 0)
7307     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7308                          DAG.getConstant(Offset, getPointerTy()));
7309
7310   return Result;
7311 }
7312
7313 SDValue
7314 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7315   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7316   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7317   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7318 }
7319
7320 static SDValue
7321 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7322            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7323            unsigned char OperandFlags, bool LocalDynamic = false) {
7324   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7325   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7326   DebugLoc dl = GA->getDebugLoc();
7327   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7328                                            GA->getValueType(0),
7329                                            GA->getOffset(),
7330                                            OperandFlags);
7331
7332   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7333                                            : X86ISD::TLSADDR;
7334
7335   if (InFlag) {
7336     SDValue Ops[] = { Chain,  TGA, *InFlag };
7337     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7338   } else {
7339     SDValue Ops[]  = { Chain, TGA };
7340     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7341   }
7342
7343   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7344   MFI->setAdjustsStack(true);
7345
7346   SDValue Flag = Chain.getValue(1);
7347   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7348 }
7349
7350 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7351 static SDValue
7352 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7353                                 const EVT PtrVT) {
7354   SDValue InFlag;
7355   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7356   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7357                                      DAG.getNode(X86ISD::GlobalBaseReg,
7358                                                  DebugLoc(), PtrVT), InFlag);
7359   InFlag = Chain.getValue(1);
7360
7361   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7362 }
7363
7364 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7365 static SDValue
7366 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7367                                 const EVT PtrVT) {
7368   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7369                     X86::RAX, X86II::MO_TLSGD);
7370 }
7371
7372 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7373                                            SelectionDAG &DAG,
7374                                            const EVT PtrVT,
7375                                            bool is64Bit) {
7376   DebugLoc dl = GA->getDebugLoc();
7377
7378   // Get the start address of the TLS block for this module.
7379   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7380       .getInfo<X86MachineFunctionInfo>();
7381   MFI->incNumLocalDynamicTLSAccesses();
7382
7383   SDValue Base;
7384   if (is64Bit) {
7385     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7386                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7387   } else {
7388     SDValue InFlag;
7389     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7390         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7391     InFlag = Chain.getValue(1);
7392     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7393                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7394   }
7395
7396   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7397   // of Base.
7398
7399   // Build x@dtpoff.
7400   unsigned char OperandFlags = X86II::MO_DTPOFF;
7401   unsigned WrapperKind = X86ISD::Wrapper;
7402   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7403                                            GA->getValueType(0),
7404                                            GA->getOffset(), OperandFlags);
7405   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7406
7407   // Add x@dtpoff with the base.
7408   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7409 }
7410
7411 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7412 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7413                                    const EVT PtrVT, TLSModel::Model model,
7414                                    bool is64Bit, bool isPIC) {
7415   DebugLoc dl = GA->getDebugLoc();
7416
7417   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7418   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7419                                                          is64Bit ? 257 : 256));
7420
7421   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7422                                       DAG.getIntPtrConstant(0),
7423                                       MachinePointerInfo(Ptr),
7424                                       false, false, false, 0);
7425
7426   unsigned char OperandFlags = 0;
7427   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7428   // initialexec.
7429   unsigned WrapperKind = X86ISD::Wrapper;
7430   if (model == TLSModel::LocalExec) {
7431     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7432   } else if (model == TLSModel::InitialExec) {
7433     if (is64Bit) {
7434       OperandFlags = X86II::MO_GOTTPOFF;
7435       WrapperKind = X86ISD::WrapperRIP;
7436     } else {
7437       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7438     }
7439   } else {
7440     llvm_unreachable("Unexpected model");
7441   }
7442
7443   // emit "addl x@ntpoff,%eax" (local exec)
7444   // or "addl x@indntpoff,%eax" (initial exec)
7445   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7446   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7447                                            GA->getValueType(0),
7448                                            GA->getOffset(), OperandFlags);
7449   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7450
7451   if (model == TLSModel::InitialExec) {
7452     if (isPIC && !is64Bit) {
7453       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7454                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7455                            Offset);
7456     }
7457
7458     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7459                          MachinePointerInfo::getGOT(), false, false, false,
7460                          0);
7461   }
7462
7463   // The address of the thread local variable is the add of the thread
7464   // pointer with the offset of the variable.
7465   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7466 }
7467
7468 SDValue
7469 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7470
7471   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7472   const GlobalValue *GV = GA->getGlobal();
7473
7474   if (Subtarget->isTargetELF()) {
7475     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7476
7477     switch (model) {
7478       case TLSModel::GeneralDynamic:
7479         if (Subtarget->is64Bit())
7480           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7481         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7482       case TLSModel::LocalDynamic:
7483         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7484                                            Subtarget->is64Bit());
7485       case TLSModel::InitialExec:
7486       case TLSModel::LocalExec:
7487         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7488                                    Subtarget->is64Bit(),
7489                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7490     }
7491     llvm_unreachable("Unknown TLS model.");
7492   }
7493
7494   if (Subtarget->isTargetDarwin()) {
7495     // Darwin only has one model of TLS.  Lower to that.
7496     unsigned char OpFlag = 0;
7497     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7498                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7499
7500     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7501     // global base reg.
7502     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7503                   !Subtarget->is64Bit();
7504     if (PIC32)
7505       OpFlag = X86II::MO_TLVP_PIC_BASE;
7506     else
7507       OpFlag = X86II::MO_TLVP;
7508     DebugLoc DL = Op.getDebugLoc();
7509     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7510                                                 GA->getValueType(0),
7511                                                 GA->getOffset(), OpFlag);
7512     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7513
7514     // With PIC32, the address is actually $g + Offset.
7515     if (PIC32)
7516       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7517                            DAG.getNode(X86ISD::GlobalBaseReg,
7518                                        DebugLoc(), getPointerTy()),
7519                            Offset);
7520
7521     // Lowering the machine isd will make sure everything is in the right
7522     // location.
7523     SDValue Chain = DAG.getEntryNode();
7524     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7525     SDValue Args[] = { Chain, Offset };
7526     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7527
7528     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7529     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7530     MFI->setAdjustsStack(true);
7531
7532     // And our return value (tls address) is in the standard call return value
7533     // location.
7534     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7535     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7536                               Chain.getValue(1));
7537   }
7538
7539   if (Subtarget->isTargetWindows()) {
7540     // Just use the implicit TLS architecture
7541     // Need to generate someting similar to:
7542     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7543     //                                  ; from TEB
7544     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7545     //   mov     rcx, qword [rdx+rcx*8]
7546     //   mov     eax, .tls$:tlsvar
7547     //   [rax+rcx] contains the address
7548     // Windows 64bit: gs:0x58
7549     // Windows 32bit: fs:__tls_array
7550
7551     // If GV is an alias then use the aliasee for determining
7552     // thread-localness.
7553     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7554       GV = GA->resolveAliasedGlobal(false);
7555     DebugLoc dl = GA->getDebugLoc();
7556     SDValue Chain = DAG.getEntryNode();
7557
7558     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7559     // %gs:0x58 (64-bit).
7560     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7561                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7562                                                              256)
7563                                         : Type::getInt32PtrTy(*DAG.getContext(),
7564                                                               257));
7565
7566     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7567                                         Subtarget->is64Bit()
7568                                         ? DAG.getIntPtrConstant(0x58)
7569                                         : DAG.getExternalSymbol("_tls_array",
7570                                                                 getPointerTy()),
7571                                         MachinePointerInfo(Ptr),
7572                                         false, false, false, 0);
7573
7574     // Load the _tls_index variable
7575     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7576     if (Subtarget->is64Bit())
7577       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7578                            IDX, MachinePointerInfo(), MVT::i32,
7579                            false, false, 0);
7580     else
7581       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7582                         false, false, false, 0);
7583
7584     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7585                                     getPointerTy());
7586     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7587
7588     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7589     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7590                       false, false, false, 0);
7591
7592     // Get the offset of start of .tls section
7593     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7594                                              GA->getValueType(0),
7595                                              GA->getOffset(), X86II::MO_SECREL);
7596     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7597
7598     // The address of the thread local variable is the add of the thread
7599     // pointer with the offset of the variable.
7600     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7601   }
7602
7603   llvm_unreachable("TLS not implemented for this target.");
7604 }
7605
7606
7607 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7608 /// and take a 2 x i32 value to shift plus a shift amount.
7609 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7610   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7611   EVT VT = Op.getValueType();
7612   unsigned VTBits = VT.getSizeInBits();
7613   DebugLoc dl = Op.getDebugLoc();
7614   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7615   SDValue ShOpLo = Op.getOperand(0);
7616   SDValue ShOpHi = Op.getOperand(1);
7617   SDValue ShAmt  = Op.getOperand(2);
7618   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7619                                      DAG.getConstant(VTBits - 1, MVT::i8))
7620                        : DAG.getConstant(0, VT);
7621
7622   SDValue Tmp2, Tmp3;
7623   if (Op.getOpcode() == ISD::SHL_PARTS) {
7624     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7625     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7626   } else {
7627     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7628     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7629   }
7630
7631   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7632                                 DAG.getConstant(VTBits, MVT::i8));
7633   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7634                              AndNode, DAG.getConstant(0, MVT::i8));
7635
7636   SDValue Hi, Lo;
7637   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7638   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7639   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7640
7641   if (Op.getOpcode() == ISD::SHL_PARTS) {
7642     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7643     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7644   } else {
7645     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7646     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7647   }
7648
7649   SDValue Ops[2] = { Lo, Hi };
7650   return DAG.getMergeValues(Ops, 2, dl);
7651 }
7652
7653 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7654                                            SelectionDAG &DAG) const {
7655   EVT SrcVT = Op.getOperand(0).getValueType();
7656
7657   if (SrcVT.isVector())
7658     return SDValue();
7659
7660   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7661          "Unknown SINT_TO_FP to lower!");
7662
7663   // These are really Legal; return the operand so the caller accepts it as
7664   // Legal.
7665   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7666     return Op;
7667   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7668       Subtarget->is64Bit()) {
7669     return Op;
7670   }
7671
7672   DebugLoc dl = Op.getDebugLoc();
7673   unsigned Size = SrcVT.getSizeInBits()/8;
7674   MachineFunction &MF = DAG.getMachineFunction();
7675   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7676   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7677   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7678                                StackSlot,
7679                                MachinePointerInfo::getFixedStack(SSFI),
7680                                false, false, 0);
7681   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7682 }
7683
7684 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7685                                      SDValue StackSlot,
7686                                      SelectionDAG &DAG) const {
7687   // Build the FILD
7688   DebugLoc DL = Op.getDebugLoc();
7689   SDVTList Tys;
7690   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7691   if (useSSE)
7692     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7693   else
7694     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7695
7696   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7697
7698   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7699   MachineMemOperand *MMO;
7700   if (FI) {
7701     int SSFI = FI->getIndex();
7702     MMO =
7703       DAG.getMachineFunction()
7704       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7705                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7706   } else {
7707     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7708     StackSlot = StackSlot.getOperand(1);
7709   }
7710   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7711   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7712                                            X86ISD::FILD, DL,
7713                                            Tys, Ops, array_lengthof(Ops),
7714                                            SrcVT, MMO);
7715
7716   if (useSSE) {
7717     Chain = Result.getValue(1);
7718     SDValue InFlag = Result.getValue(2);
7719
7720     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7721     // shouldn't be necessary except that RFP cannot be live across
7722     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7723     MachineFunction &MF = DAG.getMachineFunction();
7724     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7725     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7726     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7727     Tys = DAG.getVTList(MVT::Other);
7728     SDValue Ops[] = {
7729       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7730     };
7731     MachineMemOperand *MMO =
7732       DAG.getMachineFunction()
7733       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7734                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7735
7736     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7737                                     Ops, array_lengthof(Ops),
7738                                     Op.getValueType(), MMO);
7739     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7740                          MachinePointerInfo::getFixedStack(SSFI),
7741                          false, false, false, 0);
7742   }
7743
7744   return Result;
7745 }
7746
7747 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7748 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7749                                                SelectionDAG &DAG) const {
7750   // This algorithm is not obvious. Here it is what we're trying to output:
7751   /*
7752      movq       %rax,  %xmm0
7753      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7754      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7755      #ifdef __SSE3__
7756        haddpd   %xmm0, %xmm0
7757      #else
7758        pshufd   $0x4e, %xmm0, %xmm1
7759        addpd    %xmm1, %xmm0
7760      #endif
7761   */
7762
7763   DebugLoc dl = Op.getDebugLoc();
7764   LLVMContext *Context = DAG.getContext();
7765
7766   // Build some magic constants.
7767   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7768   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7769   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7770
7771   SmallVector<Constant*,2> CV1;
7772   CV1.push_back(
7773         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7774   CV1.push_back(
7775         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7776   Constant *C1 = ConstantVector::get(CV1);
7777   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7778
7779   // Load the 64-bit value into an XMM register.
7780   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7781                             Op.getOperand(0));
7782   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7783                               MachinePointerInfo::getConstantPool(),
7784                               false, false, false, 16);
7785   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7786                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7787                               CLod0);
7788
7789   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7790                               MachinePointerInfo::getConstantPool(),
7791                               false, false, false, 16);
7792   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7793   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7794   SDValue Result;
7795
7796   if (Subtarget->hasSSE3()) {
7797     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7798     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7799   } else {
7800     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7801     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7802                                            S2F, 0x4E, DAG);
7803     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7804                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7805                          Sub);
7806   }
7807
7808   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7809                      DAG.getIntPtrConstant(0));
7810 }
7811
7812 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7813 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7814                                                SelectionDAG &DAG) const {
7815   DebugLoc dl = Op.getDebugLoc();
7816   // FP constant to bias correct the final result.
7817   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7818                                    MVT::f64);
7819
7820   // Load the 32-bit value into an XMM register.
7821   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7822                              Op.getOperand(0));
7823
7824   // Zero out the upper parts of the register.
7825   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7826
7827   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7828                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7829                      DAG.getIntPtrConstant(0));
7830
7831   // Or the load with the bias.
7832   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7833                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7834                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7835                                                    MVT::v2f64, Load)),
7836                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7837                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7838                                                    MVT::v2f64, Bias)));
7839   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7840                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7841                    DAG.getIntPtrConstant(0));
7842
7843   // Subtract the bias.
7844   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7845
7846   // Handle final rounding.
7847   EVT DestVT = Op.getValueType();
7848
7849   if (DestVT.bitsLT(MVT::f64))
7850     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7851                        DAG.getIntPtrConstant(0));
7852   if (DestVT.bitsGT(MVT::f64))
7853     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7854
7855   // Handle final rounding.
7856   return Sub;
7857 }
7858
7859 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7860                                            SelectionDAG &DAG) const {
7861   SDValue N0 = Op.getOperand(0);
7862   DebugLoc dl = Op.getDebugLoc();
7863
7864   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7865   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7866   // the optimization here.
7867   if (DAG.SignBitIsZero(N0))
7868     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7869
7870   EVT SrcVT = N0.getValueType();
7871   EVT DstVT = Op.getValueType();
7872   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7873     return LowerUINT_TO_FP_i64(Op, DAG);
7874   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7875     return LowerUINT_TO_FP_i32(Op, DAG);
7876   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7877     return SDValue();
7878
7879   // Make a 64-bit buffer, and use it to build an FILD.
7880   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7881   if (SrcVT == MVT::i32) {
7882     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7883     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7884                                      getPointerTy(), StackSlot, WordOff);
7885     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7886                                   StackSlot, MachinePointerInfo(),
7887                                   false, false, 0);
7888     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7889                                   OffsetSlot, MachinePointerInfo(),
7890                                   false, false, 0);
7891     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7892     return Fild;
7893   }
7894
7895   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7896   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7897                                StackSlot, MachinePointerInfo(),
7898                                false, false, 0);
7899   // For i64 source, we need to add the appropriate power of 2 if the input
7900   // was negative.  This is the same as the optimization in
7901   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7902   // we must be careful to do the computation in x87 extended precision, not
7903   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7904   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7905   MachineMemOperand *MMO =
7906     DAG.getMachineFunction()
7907     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7908                           MachineMemOperand::MOLoad, 8, 8);
7909
7910   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7911   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7912   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7913                                          MVT::i64, MMO);
7914
7915   APInt FF(32, 0x5F800000ULL);
7916
7917   // Check whether the sign bit is set.
7918   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7919                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7920                                  ISD::SETLT);
7921
7922   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7923   SDValue FudgePtr = DAG.getConstantPool(
7924                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7925                                          getPointerTy());
7926
7927   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7928   SDValue Zero = DAG.getIntPtrConstant(0);
7929   SDValue Four = DAG.getIntPtrConstant(4);
7930   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7931                                Zero, Four);
7932   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7933
7934   // Load the value out, extending it from f32 to f80.
7935   // FIXME: Avoid the extend by constructing the right constant pool?
7936   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7937                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7938                                  MVT::f32, false, false, 4);
7939   // Extend everything to 80 bits to force it to be done on x87.
7940   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7941   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7942 }
7943
7944 std::pair<SDValue,SDValue> X86TargetLowering::
7945 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7946   DebugLoc DL = Op.getDebugLoc();
7947
7948   EVT DstTy = Op.getValueType();
7949
7950   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7951     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7952     DstTy = MVT::i64;
7953   }
7954
7955   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7956          DstTy.getSimpleVT() >= MVT::i16 &&
7957          "Unknown FP_TO_INT to lower!");
7958
7959   // These are really Legal.
7960   if (DstTy == MVT::i32 &&
7961       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7962     return std::make_pair(SDValue(), SDValue());
7963   if (Subtarget->is64Bit() &&
7964       DstTy == MVT::i64 &&
7965       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7966     return std::make_pair(SDValue(), SDValue());
7967
7968   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7969   // stack slot, or into the FTOL runtime function.
7970   MachineFunction &MF = DAG.getMachineFunction();
7971   unsigned MemSize = DstTy.getSizeInBits()/8;
7972   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7973   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7974
7975   unsigned Opc;
7976   if (!IsSigned && isIntegerTypeFTOL(DstTy))
7977     Opc = X86ISD::WIN_FTOL;
7978   else
7979     switch (DstTy.getSimpleVT().SimpleTy) {
7980     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7981     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7982     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7983     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7984     }
7985
7986   SDValue Chain = DAG.getEntryNode();
7987   SDValue Value = Op.getOperand(0);
7988   EVT TheVT = Op.getOperand(0).getValueType();
7989   // FIXME This causes a redundant load/store if the SSE-class value is already
7990   // in memory, such as if it is on the callstack.
7991   if (isScalarFPTypeInSSEReg(TheVT)) {
7992     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7993     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7994                          MachinePointerInfo::getFixedStack(SSFI),
7995                          false, false, 0);
7996     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7997     SDValue Ops[] = {
7998       Chain, StackSlot, DAG.getValueType(TheVT)
7999     };
8000
8001     MachineMemOperand *MMO =
8002       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8003                               MachineMemOperand::MOLoad, MemSize, MemSize);
8004     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8005                                     DstTy, MMO);
8006     Chain = Value.getValue(1);
8007     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8008     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8009   }
8010
8011   MachineMemOperand *MMO =
8012     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8013                             MachineMemOperand::MOStore, MemSize, MemSize);
8014
8015   if (Opc != X86ISD::WIN_FTOL) {
8016     // Build the FP_TO_INT*_IN_MEM
8017     SDValue Ops[] = { Chain, Value, StackSlot };
8018     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8019                                            Ops, 3, DstTy, MMO);
8020     return std::make_pair(FIST, StackSlot);
8021   } else {
8022     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8023       DAG.getVTList(MVT::Other, MVT::Glue),
8024       Chain, Value);
8025     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8026       MVT::i32, ftol.getValue(1));
8027     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8028       MVT::i32, eax.getValue(2));
8029     SDValue Ops[] = { eax, edx };
8030     SDValue pair = IsReplace
8031       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8032       : DAG.getMergeValues(Ops, 2, DL);
8033     return std::make_pair(pair, SDValue());
8034   }
8035 }
8036
8037 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8038                                            SelectionDAG &DAG) const {
8039   if (Op.getValueType().isVector())
8040     return SDValue();
8041
8042   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8043     /*IsSigned=*/ true, /*IsReplace=*/ false);
8044   SDValue FIST = Vals.first, StackSlot = Vals.second;
8045   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8046   if (FIST.getNode() == 0) return Op;
8047
8048   if (StackSlot.getNode())
8049     // Load the result.
8050     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8051                        FIST, StackSlot, MachinePointerInfo(),
8052                        false, false, false, 0);
8053
8054   // The node is the result.
8055   return FIST;
8056 }
8057
8058 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8059                                            SelectionDAG &DAG) const {
8060   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8061     /*IsSigned=*/ false, /*IsReplace=*/ false);
8062   SDValue FIST = Vals.first, StackSlot = Vals.second;
8063   assert(FIST.getNode() && "Unexpected failure");
8064
8065   if (StackSlot.getNode())
8066     // Load the result.
8067     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8068                        FIST, StackSlot, MachinePointerInfo(),
8069                        false, false, false, 0);
8070
8071   // The node is the result.
8072   return FIST;
8073 }
8074
8075 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8076                                      SelectionDAG &DAG) const {
8077   LLVMContext *Context = DAG.getContext();
8078   DebugLoc dl = Op.getDebugLoc();
8079   EVT VT = Op.getValueType();
8080   EVT EltVT = VT;
8081   if (VT.isVector())
8082     EltVT = VT.getVectorElementType();
8083   Constant *C;
8084   if (EltVT == MVT::f64) {
8085     C = ConstantVector::getSplat(2,
8086                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8087   } else {
8088     C = ConstantVector::getSplat(4,
8089                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8090   }
8091   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8092   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8093                              MachinePointerInfo::getConstantPool(),
8094                              false, false, false, 16);
8095   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8096 }
8097
8098 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8099   LLVMContext *Context = DAG.getContext();
8100   DebugLoc dl = Op.getDebugLoc();
8101   EVT VT = Op.getValueType();
8102   EVT EltVT = VT;
8103   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8104   if (VT.isVector()) {
8105     EltVT = VT.getVectorElementType();
8106     NumElts = VT.getVectorNumElements();
8107   }
8108   Constant *C;
8109   if (EltVT == MVT::f64)
8110     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8111   else
8112     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8113   C = ConstantVector::getSplat(NumElts, C);
8114   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8115   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8116                              MachinePointerInfo::getConstantPool(),
8117                              false, false, false, 16);
8118   if (VT.isVector()) {
8119     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8120     return DAG.getNode(ISD::BITCAST, dl, VT,
8121                        DAG.getNode(ISD::XOR, dl, XORVT,
8122                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8123                                                Op.getOperand(0)),
8124                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8125   }
8126
8127   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8128 }
8129
8130 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8131   LLVMContext *Context = DAG.getContext();
8132   SDValue Op0 = Op.getOperand(0);
8133   SDValue Op1 = Op.getOperand(1);
8134   DebugLoc dl = Op.getDebugLoc();
8135   EVT VT = Op.getValueType();
8136   EVT SrcVT = Op1.getValueType();
8137
8138   // If second operand is smaller, extend it first.
8139   if (SrcVT.bitsLT(VT)) {
8140     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8141     SrcVT = VT;
8142   }
8143   // And if it is bigger, shrink it first.
8144   if (SrcVT.bitsGT(VT)) {
8145     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8146     SrcVT = VT;
8147   }
8148
8149   // At this point the operands and the result should have the same
8150   // type, and that won't be f80 since that is not custom lowered.
8151
8152   // First get the sign bit of second operand.
8153   SmallVector<Constant*,4> CV;
8154   if (SrcVT == MVT::f64) {
8155     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8156     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8157   } else {
8158     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8159     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8160     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8161     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8162   }
8163   Constant *C = ConstantVector::get(CV);
8164   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8165   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8166                               MachinePointerInfo::getConstantPool(),
8167                               false, false, false, 16);
8168   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8169
8170   // Shift sign bit right or left if the two operands have different types.
8171   if (SrcVT.bitsGT(VT)) {
8172     // Op0 is MVT::f32, Op1 is MVT::f64.
8173     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8174     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8175                           DAG.getConstant(32, MVT::i32));
8176     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8177     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8178                           DAG.getIntPtrConstant(0));
8179   }
8180
8181   // Clear first operand sign bit.
8182   CV.clear();
8183   if (VT == MVT::f64) {
8184     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8185     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8186   } else {
8187     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8188     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8189     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8190     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8191   }
8192   C = ConstantVector::get(CV);
8193   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8194   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8195                               MachinePointerInfo::getConstantPool(),
8196                               false, false, false, 16);
8197   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8198
8199   // Or the value with the sign bit.
8200   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8201 }
8202
8203 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8204   SDValue N0 = Op.getOperand(0);
8205   DebugLoc dl = Op.getDebugLoc();
8206   EVT VT = Op.getValueType();
8207
8208   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8209   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8210                                   DAG.getConstant(1, VT));
8211   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8212 }
8213
8214 /// Emit nodes that will be selected as "test Op0,Op0", or something
8215 /// equivalent.
8216 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8217                                     SelectionDAG &DAG) const {
8218   DebugLoc dl = Op.getDebugLoc();
8219
8220   // CF and OF aren't always set the way we want. Determine which
8221   // of these we need.
8222   bool NeedCF = false;
8223   bool NeedOF = false;
8224   switch (X86CC) {
8225   default: break;
8226   case X86::COND_A: case X86::COND_AE:
8227   case X86::COND_B: case X86::COND_BE:
8228     NeedCF = true;
8229     break;
8230   case X86::COND_G: case X86::COND_GE:
8231   case X86::COND_L: case X86::COND_LE:
8232   case X86::COND_O: case X86::COND_NO:
8233     NeedOF = true;
8234     break;
8235   }
8236
8237   // See if we can use the EFLAGS value from the operand instead of
8238   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8239   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8240   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8241     // Emit a CMP with 0, which is the TEST pattern.
8242     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8243                        DAG.getConstant(0, Op.getValueType()));
8244
8245   unsigned Opcode = 0;
8246   unsigned NumOperands = 0;
8247   switch (Op.getNode()->getOpcode()) {
8248   case ISD::ADD:
8249     // Due to an isel shortcoming, be conservative if this add is likely to be
8250     // selected as part of a load-modify-store instruction. When the root node
8251     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8252     // uses of other nodes in the match, such as the ADD in this case. This
8253     // leads to the ADD being left around and reselected, with the result being
8254     // two adds in the output.  Alas, even if none our users are stores, that
8255     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8256     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8257     // climbing the DAG back to the root, and it doesn't seem to be worth the
8258     // effort.
8259     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8260          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8261       if (UI->getOpcode() != ISD::CopyToReg &&
8262           UI->getOpcode() != ISD::SETCC &&
8263           UI->getOpcode() != ISD::STORE)
8264         goto default_case;
8265
8266     if (ConstantSDNode *C =
8267         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8268       // An add of one will be selected as an INC.
8269       if (C->getAPIntValue() == 1) {
8270         Opcode = X86ISD::INC;
8271         NumOperands = 1;
8272         break;
8273       }
8274
8275       // An add of negative one (subtract of one) will be selected as a DEC.
8276       if (C->getAPIntValue().isAllOnesValue()) {
8277         Opcode = X86ISD::DEC;
8278         NumOperands = 1;
8279         break;
8280       }
8281     }
8282
8283     // Otherwise use a regular EFLAGS-setting add.
8284     Opcode = X86ISD::ADD;
8285     NumOperands = 2;
8286     break;
8287   case ISD::AND: {
8288     // If the primary and result isn't used, don't bother using X86ISD::AND,
8289     // because a TEST instruction will be better.
8290     bool NonFlagUse = false;
8291     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8292            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8293       SDNode *User = *UI;
8294       unsigned UOpNo = UI.getOperandNo();
8295       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8296         // Look pass truncate.
8297         UOpNo = User->use_begin().getOperandNo();
8298         User = *User->use_begin();
8299       }
8300
8301       if (User->getOpcode() != ISD::BRCOND &&
8302           User->getOpcode() != ISD::SETCC &&
8303           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8304         NonFlagUse = true;
8305         break;
8306       }
8307     }
8308
8309     if (!NonFlagUse)
8310       break;
8311   }
8312     // FALL THROUGH
8313   case ISD::SUB:
8314   case ISD::OR:
8315   case ISD::XOR:
8316     // Due to the ISEL shortcoming noted above, be conservative if this op is
8317     // likely to be selected as part of a load-modify-store instruction.
8318     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8319            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8320       if (UI->getOpcode() == ISD::STORE)
8321         goto default_case;
8322
8323     // Otherwise use a regular EFLAGS-setting instruction.
8324     switch (Op.getNode()->getOpcode()) {
8325     default: llvm_unreachable("unexpected operator!");
8326     case ISD::SUB:
8327       Opcode = X86ISD::SUB;
8328       break;
8329     case ISD::OR:  Opcode = X86ISD::OR;  break;
8330     case ISD::XOR: Opcode = X86ISD::XOR; break;
8331     case ISD::AND: Opcode = X86ISD::AND; break;
8332     }
8333
8334     NumOperands = 2;
8335     break;
8336   case X86ISD::ADD:
8337   case X86ISD::SUB:
8338   case X86ISD::INC:
8339   case X86ISD::DEC:
8340   case X86ISD::OR:
8341   case X86ISD::XOR:
8342   case X86ISD::AND:
8343     return SDValue(Op.getNode(), 1);
8344   default:
8345   default_case:
8346     break;
8347   }
8348
8349   if (Opcode == 0)
8350     // Emit a CMP with 0, which is the TEST pattern.
8351     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8352                        DAG.getConstant(0, Op.getValueType()));
8353
8354   if (Opcode == X86ISD::CMP) {
8355     SDValue New = DAG.getNode(Opcode, dl, MVT::i32, Op.getOperand(0),
8356                               Op.getOperand(1));
8357     // We can't replace usage of SUB with CMP.
8358     // The SUB node will be removed later because there is no use of it.
8359     return SDValue(New.getNode(), 0);
8360   }
8361
8362   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8363   SmallVector<SDValue, 4> Ops;
8364   for (unsigned i = 0; i != NumOperands; ++i)
8365     Ops.push_back(Op.getOperand(i));
8366
8367   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8368   DAG.ReplaceAllUsesWith(Op, New);
8369   return SDValue(New.getNode(), 1);
8370 }
8371
8372 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8373 /// equivalent.
8374 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8375                                    SelectionDAG &DAG) const {
8376   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8377     if (C->getAPIntValue() == 0)
8378       return EmitTest(Op0, X86CC, DAG);
8379
8380   DebugLoc dl = Op0.getDebugLoc();
8381   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8382        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8383     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8384     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8385     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8386                               Op0, Op1);
8387     return SDValue(Sub.getNode(), 1);
8388   }
8389   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8390 }
8391
8392 /// Convert a comparison if required by the subtarget.
8393 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8394                                                  SelectionDAG &DAG) const {
8395   // If the subtarget does not support the FUCOMI instruction, floating-point
8396   // comparisons have to be converted.
8397   if (Subtarget->hasCMov() ||
8398       Cmp.getOpcode() != X86ISD::CMP ||
8399       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8400       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8401     return Cmp;
8402
8403   // The instruction selector will select an FUCOM instruction instead of
8404   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8405   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8406   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8407   DebugLoc dl = Cmp.getDebugLoc();
8408   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8409   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8410   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8411                             DAG.getConstant(8, MVT::i8));
8412   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8413   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8414 }
8415
8416 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8417 /// if it's possible.
8418 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8419                                      DebugLoc dl, SelectionDAG &DAG) const {
8420   SDValue Op0 = And.getOperand(0);
8421   SDValue Op1 = And.getOperand(1);
8422   if (Op0.getOpcode() == ISD::TRUNCATE)
8423     Op0 = Op0.getOperand(0);
8424   if (Op1.getOpcode() == ISD::TRUNCATE)
8425     Op1 = Op1.getOperand(0);
8426
8427   SDValue LHS, RHS;
8428   if (Op1.getOpcode() == ISD::SHL)
8429     std::swap(Op0, Op1);
8430   if (Op0.getOpcode() == ISD::SHL) {
8431     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8432       if (And00C->getZExtValue() == 1) {
8433         // If we looked past a truncate, check that it's only truncating away
8434         // known zeros.
8435         unsigned BitWidth = Op0.getValueSizeInBits();
8436         unsigned AndBitWidth = And.getValueSizeInBits();
8437         if (BitWidth > AndBitWidth) {
8438           APInt Zeros, Ones;
8439           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8440           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8441             return SDValue();
8442         }
8443         LHS = Op1;
8444         RHS = Op0.getOperand(1);
8445       }
8446   } else if (Op1.getOpcode() == ISD::Constant) {
8447     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8448     uint64_t AndRHSVal = AndRHS->getZExtValue();
8449     SDValue AndLHS = Op0;
8450
8451     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8452       LHS = AndLHS.getOperand(0);
8453       RHS = AndLHS.getOperand(1);
8454     }
8455
8456     // Use BT if the immediate can't be encoded in a TEST instruction.
8457     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8458       LHS = AndLHS;
8459       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8460     }
8461   }
8462
8463   if (LHS.getNode()) {
8464     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8465     // instruction.  Since the shift amount is in-range-or-undefined, we know
8466     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8467     // the encoding for the i16 version is larger than the i32 version.
8468     // Also promote i16 to i32 for performance / code size reason.
8469     if (LHS.getValueType() == MVT::i8 ||
8470         LHS.getValueType() == MVT::i16)
8471       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8472
8473     // If the operand types disagree, extend the shift amount to match.  Since
8474     // BT ignores high bits (like shifts) we can use anyextend.
8475     if (LHS.getValueType() != RHS.getValueType())
8476       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8477
8478     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8479     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8480     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8481                        DAG.getConstant(Cond, MVT::i8), BT);
8482   }
8483
8484   return SDValue();
8485 }
8486
8487 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8488
8489   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8490
8491   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8492   SDValue Op0 = Op.getOperand(0);
8493   SDValue Op1 = Op.getOperand(1);
8494   DebugLoc dl = Op.getDebugLoc();
8495   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8496
8497   // Optimize to BT if possible.
8498   // Lower (X & (1 << N)) == 0 to BT(X, N).
8499   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8500   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8501   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8502       Op1.getOpcode() == ISD::Constant &&
8503       cast<ConstantSDNode>(Op1)->isNullValue() &&
8504       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8505     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8506     if (NewSetCC.getNode())
8507       return NewSetCC;
8508   }
8509
8510   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8511   // these.
8512   if (Op1.getOpcode() == ISD::Constant &&
8513       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8514        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8515       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8516
8517     // If the input is a setcc, then reuse the input setcc or use a new one with
8518     // the inverted condition.
8519     if (Op0.getOpcode() == X86ISD::SETCC) {
8520       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8521       bool Invert = (CC == ISD::SETNE) ^
8522         cast<ConstantSDNode>(Op1)->isNullValue();
8523       if (!Invert) return Op0;
8524
8525       CCode = X86::GetOppositeBranchCondition(CCode);
8526       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8527                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8528     }
8529   }
8530
8531   bool isFP = Op1.getValueType().isFloatingPoint();
8532   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8533   if (X86CC == X86::COND_INVALID)
8534     return SDValue();
8535
8536   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8537   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8538   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8539                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8540 }
8541
8542 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8543 // ones, and then concatenate the result back.
8544 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8545   EVT VT = Op.getValueType();
8546
8547   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8548          "Unsupported value type for operation");
8549
8550   unsigned NumElems = VT.getVectorNumElements();
8551   DebugLoc dl = Op.getDebugLoc();
8552   SDValue CC = Op.getOperand(2);
8553
8554   // Extract the LHS vectors
8555   SDValue LHS = Op.getOperand(0);
8556   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8557   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8558
8559   // Extract the RHS vectors
8560   SDValue RHS = Op.getOperand(1);
8561   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8562   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8563
8564   // Issue the operation on the smaller types and concatenate the result back
8565   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8566   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8567   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8568                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8569                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8570 }
8571
8572
8573 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8574   SDValue Cond;
8575   SDValue Op0 = Op.getOperand(0);
8576   SDValue Op1 = Op.getOperand(1);
8577   SDValue CC = Op.getOperand(2);
8578   EVT VT = Op.getValueType();
8579   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8580   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8581   DebugLoc dl = Op.getDebugLoc();
8582
8583   if (isFP) {
8584     unsigned SSECC = 8;
8585     EVT EltVT = Op0.getValueType().getVectorElementType();
8586     assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8587
8588     bool Swap = false;
8589
8590     // SSE Condition code mapping:
8591     //  0 - EQ
8592     //  1 - LT
8593     //  2 - LE
8594     //  3 - UNORD
8595     //  4 - NEQ
8596     //  5 - NLT
8597     //  6 - NLE
8598     //  7 - ORD
8599     switch (SetCCOpcode) {
8600     default: break;
8601     case ISD::SETOEQ:
8602     case ISD::SETEQ:  SSECC = 0; break;
8603     case ISD::SETOGT:
8604     case ISD::SETGT: Swap = true; // Fallthrough
8605     case ISD::SETLT:
8606     case ISD::SETOLT: SSECC = 1; break;
8607     case ISD::SETOGE:
8608     case ISD::SETGE: Swap = true; // Fallthrough
8609     case ISD::SETLE:
8610     case ISD::SETOLE: SSECC = 2; break;
8611     case ISD::SETUO:  SSECC = 3; break;
8612     case ISD::SETUNE:
8613     case ISD::SETNE:  SSECC = 4; break;
8614     case ISD::SETULE: Swap = true;
8615     case ISD::SETUGE: SSECC = 5; break;
8616     case ISD::SETULT: Swap = true;
8617     case ISD::SETUGT: SSECC = 6; break;
8618     case ISD::SETO:   SSECC = 7; break;
8619     }
8620     if (Swap)
8621       std::swap(Op0, Op1);
8622
8623     // In the two special cases we can't handle, emit two comparisons.
8624     if (SSECC == 8) {
8625       if (SetCCOpcode == ISD::SETUEQ) {
8626         SDValue UNORD, EQ;
8627         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8628                             DAG.getConstant(3, MVT::i8));
8629         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8630                          DAG.getConstant(0, MVT::i8));
8631         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8632       }
8633       if (SetCCOpcode == ISD::SETONE) {
8634         SDValue ORD, NEQ;
8635         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8636                           DAG.getConstant(7, MVT::i8));
8637         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8638                           DAG.getConstant(4, MVT::i8));
8639         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8640       }
8641       llvm_unreachable("Illegal FP comparison");
8642     }
8643     // Handle all other FP comparisons here.
8644     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8645                        DAG.getConstant(SSECC, MVT::i8));
8646   }
8647
8648   // Break 256-bit integer vector compare into smaller ones.
8649   if (VT.is256BitVector() && !Subtarget->hasAVX2())
8650     return Lower256IntVSETCC(Op, DAG);
8651
8652   // We are handling one of the integer comparisons here.  Since SSE only has
8653   // GT and EQ comparisons for integer, swapping operands and multiple
8654   // operations may be required for some comparisons.
8655   unsigned Opc = 0;
8656   bool Swap = false, Invert = false, FlipSigns = false;
8657
8658   switch (SetCCOpcode) {
8659   default: break;
8660   case ISD::SETNE:  Invert = true;
8661   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8662   case ISD::SETLT:  Swap = true;
8663   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8664   case ISD::SETGE:  Swap = true;
8665   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8666   case ISD::SETULT: Swap = true;
8667   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8668   case ISD::SETUGE: Swap = true;
8669   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8670   }
8671   if (Swap)
8672     std::swap(Op0, Op1);
8673
8674   // Check that the operation in question is available (most are plain SSE2,
8675   // but PCMPGTQ and PCMPEQQ have different requirements).
8676   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8677     return SDValue();
8678   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8679     return SDValue();
8680
8681   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8682   // bits of the inputs before performing those operations.
8683   if (FlipSigns) {
8684     EVT EltVT = VT.getVectorElementType();
8685     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8686                                       EltVT);
8687     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8688     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8689                                     SignBits.size());
8690     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8691     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8692   }
8693
8694   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8695
8696   // If the logical-not of the result is required, perform that now.
8697   if (Invert)
8698     Result = DAG.getNOT(dl, Result, VT);
8699
8700   return Result;
8701 }
8702
8703 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8704 static bool isX86LogicalCmp(SDValue Op) {
8705   unsigned Opc = Op.getNode()->getOpcode();
8706   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8707       Opc == X86ISD::SAHF)
8708     return true;
8709   if (Op.getResNo() == 1 &&
8710       (Opc == X86ISD::ADD ||
8711        Opc == X86ISD::SUB ||
8712        Opc == X86ISD::ADC ||
8713        Opc == X86ISD::SBB ||
8714        Opc == X86ISD::SMUL ||
8715        Opc == X86ISD::UMUL ||
8716        Opc == X86ISD::INC ||
8717        Opc == X86ISD::DEC ||
8718        Opc == X86ISD::OR ||
8719        Opc == X86ISD::XOR ||
8720        Opc == X86ISD::AND))
8721     return true;
8722
8723   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8724     return true;
8725
8726   return false;
8727 }
8728
8729 static bool isZero(SDValue V) {
8730   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8731   return C && C->isNullValue();
8732 }
8733
8734 static bool isAllOnes(SDValue V) {
8735   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8736   return C && C->isAllOnesValue();
8737 }
8738
8739 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8740   if (V.getOpcode() != ISD::TRUNCATE)
8741     return false;
8742
8743   SDValue VOp0 = V.getOperand(0);
8744   unsigned InBits = VOp0.getValueSizeInBits();
8745   unsigned Bits = V.getValueSizeInBits();
8746   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8747 }
8748
8749 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8750   bool addTest = true;
8751   SDValue Cond  = Op.getOperand(0);
8752   SDValue Op1 = Op.getOperand(1);
8753   SDValue Op2 = Op.getOperand(2);
8754   DebugLoc DL = Op.getDebugLoc();
8755   SDValue CC;
8756
8757   if (Cond.getOpcode() == ISD::SETCC) {
8758     SDValue NewCond = LowerSETCC(Cond, DAG);
8759     if (NewCond.getNode())
8760       Cond = NewCond;
8761   }
8762
8763   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8764   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8765   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8766   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8767   if (Cond.getOpcode() == X86ISD::SETCC &&
8768       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8769       isZero(Cond.getOperand(1).getOperand(1))) {
8770     SDValue Cmp = Cond.getOperand(1);
8771
8772     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8773
8774     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8775         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8776       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8777
8778       SDValue CmpOp0 = Cmp.getOperand(0);
8779       // Apply further optimizations for special cases
8780       // (select (x != 0), -1, 0) -> neg & sbb
8781       // (select (x == 0), 0, -1) -> neg & sbb
8782       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8783         if (YC->isNullValue() &&
8784             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8785           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8786           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8787                                     DAG.getConstant(0, CmpOp0.getValueType()),
8788                                     CmpOp0);
8789           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8790                                     DAG.getConstant(X86::COND_B, MVT::i8),
8791                                     SDValue(Neg.getNode(), 1));
8792           return Res;
8793         }
8794
8795       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8796                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8797       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8798
8799       SDValue Res =   // Res = 0 or -1.
8800         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8801                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8802
8803       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8804         Res = DAG.getNOT(DL, Res, Res.getValueType());
8805
8806       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8807       if (N2C == 0 || !N2C->isNullValue())
8808         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8809       return Res;
8810     }
8811   }
8812
8813   // Look past (and (setcc_carry (cmp ...)), 1).
8814   if (Cond.getOpcode() == ISD::AND &&
8815       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8816     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8817     if (C && C->getAPIntValue() == 1)
8818       Cond = Cond.getOperand(0);
8819   }
8820
8821   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8822   // setting operand in place of the X86ISD::SETCC.
8823   unsigned CondOpcode = Cond.getOpcode();
8824   if (CondOpcode == X86ISD::SETCC ||
8825       CondOpcode == X86ISD::SETCC_CARRY) {
8826     CC = Cond.getOperand(0);
8827
8828     SDValue Cmp = Cond.getOperand(1);
8829     unsigned Opc = Cmp.getOpcode();
8830     EVT VT = Op.getValueType();
8831
8832     bool IllegalFPCMov = false;
8833     if (VT.isFloatingPoint() && !VT.isVector() &&
8834         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8835       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8836
8837     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8838         Opc == X86ISD::BT) { // FIXME
8839       Cond = Cmp;
8840       addTest = false;
8841     }
8842   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8843              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8844              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8845               Cond.getOperand(0).getValueType() != MVT::i8)) {
8846     SDValue LHS = Cond.getOperand(0);
8847     SDValue RHS = Cond.getOperand(1);
8848     unsigned X86Opcode;
8849     unsigned X86Cond;
8850     SDVTList VTs;
8851     switch (CondOpcode) {
8852     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8853     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8854     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8855     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8856     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8857     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8858     default: llvm_unreachable("unexpected overflowing operator");
8859     }
8860     if (CondOpcode == ISD::UMULO)
8861       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8862                           MVT::i32);
8863     else
8864       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8865
8866     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8867
8868     if (CondOpcode == ISD::UMULO)
8869       Cond = X86Op.getValue(2);
8870     else
8871       Cond = X86Op.getValue(1);
8872
8873     CC = DAG.getConstant(X86Cond, MVT::i8);
8874     addTest = false;
8875   }
8876
8877   if (addTest) {
8878     // Look pass the truncate if the high bits are known zero.
8879     if (isTruncWithZeroHighBitsInput(Cond, DAG))
8880         Cond = Cond.getOperand(0);
8881
8882     // We know the result of AND is compared against zero. Try to match
8883     // it to BT.
8884     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8885       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8886       if (NewSetCC.getNode()) {
8887         CC = NewSetCC.getOperand(0);
8888         Cond = NewSetCC.getOperand(1);
8889         addTest = false;
8890       }
8891     }
8892   }
8893
8894   if (addTest) {
8895     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8896     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8897   }
8898
8899   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8900   // a <  b ?  0 : -1 -> RES = setcc_carry
8901   // a >= b ? -1 :  0 -> RES = setcc_carry
8902   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8903   if (Cond.getOpcode() == X86ISD::SUB) {
8904     Cond = ConvertCmpIfNecessary(Cond, DAG);
8905     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8906
8907     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8908         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8909       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8910                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8911       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8912         return DAG.getNOT(DL, Res, Res.getValueType());
8913       return Res;
8914     }
8915   }
8916
8917   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8918   // condition is true.
8919   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8920   SDValue Ops[] = { Op2, Op1, CC, Cond };
8921   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8922 }
8923
8924 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8925 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8926 // from the AND / OR.
8927 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8928   Opc = Op.getOpcode();
8929   if (Opc != ISD::OR && Opc != ISD::AND)
8930     return false;
8931   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8932           Op.getOperand(0).hasOneUse() &&
8933           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8934           Op.getOperand(1).hasOneUse());
8935 }
8936
8937 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8938 // 1 and that the SETCC node has a single use.
8939 static bool isXor1OfSetCC(SDValue Op) {
8940   if (Op.getOpcode() != ISD::XOR)
8941     return false;
8942   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8943   if (N1C && N1C->getAPIntValue() == 1) {
8944     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8945       Op.getOperand(0).hasOneUse();
8946   }
8947   return false;
8948 }
8949
8950 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8951   bool addTest = true;
8952   SDValue Chain = Op.getOperand(0);
8953   SDValue Cond  = Op.getOperand(1);
8954   SDValue Dest  = Op.getOperand(2);
8955   DebugLoc dl = Op.getDebugLoc();
8956   SDValue CC;
8957   bool Inverted = false;
8958
8959   if (Cond.getOpcode() == ISD::SETCC) {
8960     // Check for setcc([su]{add,sub,mul}o == 0).
8961     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8962         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8963         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8964         Cond.getOperand(0).getResNo() == 1 &&
8965         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8966          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8967          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8968          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8969          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8970          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8971       Inverted = true;
8972       Cond = Cond.getOperand(0);
8973     } else {
8974       SDValue NewCond = LowerSETCC(Cond, DAG);
8975       if (NewCond.getNode())
8976         Cond = NewCond;
8977     }
8978   }
8979 #if 0
8980   // FIXME: LowerXALUO doesn't handle these!!
8981   else if (Cond.getOpcode() == X86ISD::ADD  ||
8982            Cond.getOpcode() == X86ISD::SUB  ||
8983            Cond.getOpcode() == X86ISD::SMUL ||
8984            Cond.getOpcode() == X86ISD::UMUL)
8985     Cond = LowerXALUO(Cond, DAG);
8986 #endif
8987
8988   // Look pass (and (setcc_carry (cmp ...)), 1).
8989   if (Cond.getOpcode() == ISD::AND &&
8990       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8991     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8992     if (C && C->getAPIntValue() == 1)
8993       Cond = Cond.getOperand(0);
8994   }
8995
8996   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8997   // setting operand in place of the X86ISD::SETCC.
8998   unsigned CondOpcode = Cond.getOpcode();
8999   if (CondOpcode == X86ISD::SETCC ||
9000       CondOpcode == X86ISD::SETCC_CARRY) {
9001     CC = Cond.getOperand(0);
9002
9003     SDValue Cmp = Cond.getOperand(1);
9004     unsigned Opc = Cmp.getOpcode();
9005     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9006     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9007       Cond = Cmp;
9008       addTest = false;
9009     } else {
9010       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9011       default: break;
9012       case X86::COND_O:
9013       case X86::COND_B:
9014         // These can only come from an arithmetic instruction with overflow,
9015         // e.g. SADDO, UADDO.
9016         Cond = Cond.getNode()->getOperand(1);
9017         addTest = false;
9018         break;
9019       }
9020     }
9021   }
9022   CondOpcode = Cond.getOpcode();
9023   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9024       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9025       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9026        Cond.getOperand(0).getValueType() != MVT::i8)) {
9027     SDValue LHS = Cond.getOperand(0);
9028     SDValue RHS = Cond.getOperand(1);
9029     unsigned X86Opcode;
9030     unsigned X86Cond;
9031     SDVTList VTs;
9032     switch (CondOpcode) {
9033     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9034     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9035     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9036     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9037     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9038     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9039     default: llvm_unreachable("unexpected overflowing operator");
9040     }
9041     if (Inverted)
9042       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9043     if (CondOpcode == ISD::UMULO)
9044       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9045                           MVT::i32);
9046     else
9047       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9048
9049     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9050
9051     if (CondOpcode == ISD::UMULO)
9052       Cond = X86Op.getValue(2);
9053     else
9054       Cond = X86Op.getValue(1);
9055
9056     CC = DAG.getConstant(X86Cond, MVT::i8);
9057     addTest = false;
9058   } else {
9059     unsigned CondOpc;
9060     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9061       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9062       if (CondOpc == ISD::OR) {
9063         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9064         // two branches instead of an explicit OR instruction with a
9065         // separate test.
9066         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9067             isX86LogicalCmp(Cmp)) {
9068           CC = Cond.getOperand(0).getOperand(0);
9069           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9070                               Chain, Dest, CC, Cmp);
9071           CC = Cond.getOperand(1).getOperand(0);
9072           Cond = Cmp;
9073           addTest = false;
9074         }
9075       } else { // ISD::AND
9076         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9077         // two branches instead of an explicit AND instruction with a
9078         // separate test. However, we only do this if this block doesn't
9079         // have a fall-through edge, because this requires an explicit
9080         // jmp when the condition is false.
9081         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9082             isX86LogicalCmp(Cmp) &&
9083             Op.getNode()->hasOneUse()) {
9084           X86::CondCode CCode =
9085             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9086           CCode = X86::GetOppositeBranchCondition(CCode);
9087           CC = DAG.getConstant(CCode, MVT::i8);
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             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9101                                 Chain, Dest, CC, Cmp);
9102             X86::CondCode CCode =
9103               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9104             CCode = X86::GetOppositeBranchCondition(CCode);
9105             CC = DAG.getConstant(CCode, MVT::i8);
9106             Cond = Cmp;
9107             addTest = false;
9108           }
9109         }
9110       }
9111     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9112       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9113       // It should be transformed during dag combiner except when the condition
9114       // is set by a arithmetics with overflow node.
9115       X86::CondCode CCode =
9116         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9117       CCode = X86::GetOppositeBranchCondition(CCode);
9118       CC = DAG.getConstant(CCode, MVT::i8);
9119       Cond = Cond.getOperand(0).getOperand(1);
9120       addTest = false;
9121     } else if (Cond.getOpcode() == ISD::SETCC &&
9122                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9123       // For FCMP_OEQ, we can emit
9124       // two branches instead of an explicit AND instruction with a
9125       // separate test. However, we only do this if this block doesn't
9126       // have a fall-through edge, because this requires an explicit
9127       // jmp when the condition is false.
9128       if (Op.getNode()->hasOneUse()) {
9129         SDNode *User = *Op.getNode()->use_begin();
9130         // Look for an unconditional branch following this conditional branch.
9131         // We need this because we need to reverse the successors in order
9132         // to implement FCMP_OEQ.
9133         if (User->getOpcode() == ISD::BR) {
9134           SDValue FalseBB = User->getOperand(1);
9135           SDNode *NewBR =
9136             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9137           assert(NewBR == User);
9138           (void)NewBR;
9139           Dest = FalseBB;
9140
9141           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9142                                     Cond.getOperand(0), Cond.getOperand(1));
9143           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9144           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9145           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9146                               Chain, Dest, CC, Cmp);
9147           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9148           Cond = Cmp;
9149           addTest = false;
9150         }
9151       }
9152     } else if (Cond.getOpcode() == ISD::SETCC &&
9153                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9154       // For FCMP_UNE, we can emit
9155       // two branches instead of an explicit AND instruction with a
9156       // separate test. However, we only do this if this block doesn't
9157       // have a fall-through edge, because this requires an explicit
9158       // jmp when the condition is false.
9159       if (Op.getNode()->hasOneUse()) {
9160         SDNode *User = *Op.getNode()->use_begin();
9161         // Look for an unconditional branch following this conditional branch.
9162         // We need this because we need to reverse the successors in order
9163         // to implement FCMP_UNE.
9164         if (User->getOpcode() == ISD::BR) {
9165           SDValue FalseBB = User->getOperand(1);
9166           SDNode *NewBR =
9167             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9168           assert(NewBR == User);
9169           (void)NewBR;
9170
9171           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9172                                     Cond.getOperand(0), Cond.getOperand(1));
9173           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9174           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9175           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9176                               Chain, Dest, CC, Cmp);
9177           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9178           Cond = Cmp;
9179           addTest = false;
9180           Dest = FalseBB;
9181         }
9182       }
9183     }
9184   }
9185
9186   if (addTest) {
9187     // Look pass the truncate if the high bits are known zero.
9188     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9189         Cond = Cond.getOperand(0);
9190
9191     // We know the result of AND is compared against zero. Try to match
9192     // it to BT.
9193     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9194       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9195       if (NewSetCC.getNode()) {
9196         CC = NewSetCC.getOperand(0);
9197         Cond = NewSetCC.getOperand(1);
9198         addTest = false;
9199       }
9200     }
9201   }
9202
9203   if (addTest) {
9204     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9205     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9206   }
9207   Cond = ConvertCmpIfNecessary(Cond, DAG);
9208   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9209                      Chain, Dest, CC, Cond);
9210 }
9211
9212
9213 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9214 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9215 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9216 // that the guard pages used by the OS virtual memory manager are allocated in
9217 // correct sequence.
9218 SDValue
9219 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9220                                            SelectionDAG &DAG) const {
9221   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9222           getTargetMachine().Options.EnableSegmentedStacks) &&
9223          "This should be used only on Windows targets or when segmented stacks "
9224          "are being used");
9225   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9226   DebugLoc dl = Op.getDebugLoc();
9227
9228   // Get the inputs.
9229   SDValue Chain = Op.getOperand(0);
9230   SDValue Size  = Op.getOperand(1);
9231   // FIXME: Ensure alignment here
9232
9233   bool Is64Bit = Subtarget->is64Bit();
9234   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9235
9236   if (getTargetMachine().Options.EnableSegmentedStacks) {
9237     MachineFunction &MF = DAG.getMachineFunction();
9238     MachineRegisterInfo &MRI = MF.getRegInfo();
9239
9240     if (Is64Bit) {
9241       // The 64 bit implementation of segmented stacks needs to clobber both r10
9242       // r11. This makes it impossible to use it along with nested parameters.
9243       const Function *F = MF.getFunction();
9244
9245       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9246            I != E; ++I)
9247         if (I->hasNestAttr())
9248           report_fatal_error("Cannot use segmented stacks with functions that "
9249                              "have nested arguments.");
9250     }
9251
9252     const TargetRegisterClass *AddrRegClass =
9253       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9254     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9255     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9256     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9257                                 DAG.getRegister(Vreg, SPTy));
9258     SDValue Ops1[2] = { Value, Chain };
9259     return DAG.getMergeValues(Ops1, 2, dl);
9260   } else {
9261     SDValue Flag;
9262     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9263
9264     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9265     Flag = Chain.getValue(1);
9266     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9267
9268     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9269     Flag = Chain.getValue(1);
9270
9271     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9272
9273     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9274     return DAG.getMergeValues(Ops1, 2, dl);
9275   }
9276 }
9277
9278 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9279   MachineFunction &MF = DAG.getMachineFunction();
9280   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9281
9282   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9283   DebugLoc DL = Op.getDebugLoc();
9284
9285   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9286     // vastart just stores the address of the VarArgsFrameIndex slot into the
9287     // memory location argument.
9288     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9289                                    getPointerTy());
9290     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9291                         MachinePointerInfo(SV), false, false, 0);
9292   }
9293
9294   // __va_list_tag:
9295   //   gp_offset         (0 - 6 * 8)
9296   //   fp_offset         (48 - 48 + 8 * 16)
9297   //   overflow_arg_area (point to parameters coming in memory).
9298   //   reg_save_area
9299   SmallVector<SDValue, 8> MemOps;
9300   SDValue FIN = Op.getOperand(1);
9301   // Store gp_offset
9302   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9303                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9304                                                MVT::i32),
9305                                FIN, MachinePointerInfo(SV), false, false, 0);
9306   MemOps.push_back(Store);
9307
9308   // Store fp_offset
9309   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9310                     FIN, DAG.getIntPtrConstant(4));
9311   Store = DAG.getStore(Op.getOperand(0), DL,
9312                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9313                                        MVT::i32),
9314                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9315   MemOps.push_back(Store);
9316
9317   // Store ptr to overflow_arg_area
9318   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9319                     FIN, DAG.getIntPtrConstant(4));
9320   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9321                                     getPointerTy());
9322   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9323                        MachinePointerInfo(SV, 8),
9324                        false, false, 0);
9325   MemOps.push_back(Store);
9326
9327   // Store ptr to reg_save_area.
9328   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9329                     FIN, DAG.getIntPtrConstant(8));
9330   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9331                                     getPointerTy());
9332   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9333                        MachinePointerInfo(SV, 16), false, false, 0);
9334   MemOps.push_back(Store);
9335   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9336                      &MemOps[0], MemOps.size());
9337 }
9338
9339 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9340   assert(Subtarget->is64Bit() &&
9341          "LowerVAARG only handles 64-bit va_arg!");
9342   assert((Subtarget->isTargetLinux() ||
9343           Subtarget->isTargetDarwin()) &&
9344           "Unhandled target in LowerVAARG");
9345   assert(Op.getNode()->getNumOperands() == 4);
9346   SDValue Chain = Op.getOperand(0);
9347   SDValue SrcPtr = Op.getOperand(1);
9348   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9349   unsigned Align = Op.getConstantOperandVal(3);
9350   DebugLoc dl = Op.getDebugLoc();
9351
9352   EVT ArgVT = Op.getNode()->getValueType(0);
9353   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9354   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9355   uint8_t ArgMode;
9356
9357   // Decide which area this value should be read from.
9358   // TODO: Implement the AMD64 ABI in its entirety. This simple
9359   // selection mechanism works only for the basic types.
9360   if (ArgVT == MVT::f80) {
9361     llvm_unreachable("va_arg for f80 not yet implemented");
9362   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9363     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9364   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9365     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9366   } else {
9367     llvm_unreachable("Unhandled argument type in LowerVAARG");
9368   }
9369
9370   if (ArgMode == 2) {
9371     // Sanity Check: Make sure using fp_offset makes sense.
9372     assert(!getTargetMachine().Options.UseSoftFloat &&
9373            !(DAG.getMachineFunction()
9374                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9375            Subtarget->hasSSE1());
9376   }
9377
9378   // Insert VAARG_64 node into the DAG
9379   // VAARG_64 returns two values: Variable Argument Address, Chain
9380   SmallVector<SDValue, 11> InstOps;
9381   InstOps.push_back(Chain);
9382   InstOps.push_back(SrcPtr);
9383   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9384   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9385   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9386   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9387   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9388                                           VTs, &InstOps[0], InstOps.size(),
9389                                           MVT::i64,
9390                                           MachinePointerInfo(SV),
9391                                           /*Align=*/0,
9392                                           /*Volatile=*/false,
9393                                           /*ReadMem=*/true,
9394                                           /*WriteMem=*/true);
9395   Chain = VAARG.getValue(1);
9396
9397   // Load the next argument and return it
9398   return DAG.getLoad(ArgVT, dl,
9399                      Chain,
9400                      VAARG,
9401                      MachinePointerInfo(),
9402                      false, false, false, 0);
9403 }
9404
9405 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9406   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9407   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9408   SDValue Chain = Op.getOperand(0);
9409   SDValue DstPtr = Op.getOperand(1);
9410   SDValue SrcPtr = Op.getOperand(2);
9411   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9412   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9413   DebugLoc DL = Op.getDebugLoc();
9414
9415   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9416                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9417                        false,
9418                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9419 }
9420
9421 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9422 // may or may not be a constant. Takes immediate version of shift as input.
9423 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9424                                    SDValue SrcOp, SDValue ShAmt,
9425                                    SelectionDAG &DAG) {
9426   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9427
9428   if (isa<ConstantSDNode>(ShAmt)) {
9429     // Constant may be a TargetConstant. Use a regular constant.
9430     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9431     switch (Opc) {
9432       default: llvm_unreachable("Unknown target vector shift node");
9433       case X86ISD::VSHLI:
9434       case X86ISD::VSRLI:
9435       case X86ISD::VSRAI:
9436         return DAG.getNode(Opc, dl, VT, SrcOp,
9437                            DAG.getConstant(ShiftAmt, MVT::i32));
9438     }
9439   }
9440
9441   // Change opcode to non-immediate version
9442   switch (Opc) {
9443     default: llvm_unreachable("Unknown target vector shift node");
9444     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9445     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9446     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9447   }
9448
9449   // Need to build a vector containing shift amount
9450   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9451   SDValue ShOps[4];
9452   ShOps[0] = ShAmt;
9453   ShOps[1] = DAG.getConstant(0, MVT::i32);
9454   ShOps[2] = DAG.getUNDEF(MVT::i32);
9455   ShOps[3] = DAG.getUNDEF(MVT::i32);
9456   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9457
9458   // The return type has to be a 128-bit type with the same element
9459   // type as the input type.
9460   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9461   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9462
9463   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9464   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9465 }
9466
9467 SDValue
9468 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9469   DebugLoc dl = Op.getDebugLoc();
9470   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9471   switch (IntNo) {
9472   default: return SDValue();    // Don't custom lower most intrinsics.
9473   // Comparison intrinsics.
9474   case Intrinsic::x86_sse_comieq_ss:
9475   case Intrinsic::x86_sse_comilt_ss:
9476   case Intrinsic::x86_sse_comile_ss:
9477   case Intrinsic::x86_sse_comigt_ss:
9478   case Intrinsic::x86_sse_comige_ss:
9479   case Intrinsic::x86_sse_comineq_ss:
9480   case Intrinsic::x86_sse_ucomieq_ss:
9481   case Intrinsic::x86_sse_ucomilt_ss:
9482   case Intrinsic::x86_sse_ucomile_ss:
9483   case Intrinsic::x86_sse_ucomigt_ss:
9484   case Intrinsic::x86_sse_ucomige_ss:
9485   case Intrinsic::x86_sse_ucomineq_ss:
9486   case Intrinsic::x86_sse2_comieq_sd:
9487   case Intrinsic::x86_sse2_comilt_sd:
9488   case Intrinsic::x86_sse2_comile_sd:
9489   case Intrinsic::x86_sse2_comigt_sd:
9490   case Intrinsic::x86_sse2_comige_sd:
9491   case Intrinsic::x86_sse2_comineq_sd:
9492   case Intrinsic::x86_sse2_ucomieq_sd:
9493   case Intrinsic::x86_sse2_ucomilt_sd:
9494   case Intrinsic::x86_sse2_ucomile_sd:
9495   case Intrinsic::x86_sse2_ucomigt_sd:
9496   case Intrinsic::x86_sse2_ucomige_sd:
9497   case Intrinsic::x86_sse2_ucomineq_sd: {
9498     unsigned Opc = 0;
9499     ISD::CondCode CC = ISD::SETCC_INVALID;
9500     switch (IntNo) {
9501     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9502     case Intrinsic::x86_sse_comieq_ss:
9503     case Intrinsic::x86_sse2_comieq_sd:
9504       Opc = X86ISD::COMI;
9505       CC = ISD::SETEQ;
9506       break;
9507     case Intrinsic::x86_sse_comilt_ss:
9508     case Intrinsic::x86_sse2_comilt_sd:
9509       Opc = X86ISD::COMI;
9510       CC = ISD::SETLT;
9511       break;
9512     case Intrinsic::x86_sse_comile_ss:
9513     case Intrinsic::x86_sse2_comile_sd:
9514       Opc = X86ISD::COMI;
9515       CC = ISD::SETLE;
9516       break;
9517     case Intrinsic::x86_sse_comigt_ss:
9518     case Intrinsic::x86_sse2_comigt_sd:
9519       Opc = X86ISD::COMI;
9520       CC = ISD::SETGT;
9521       break;
9522     case Intrinsic::x86_sse_comige_ss:
9523     case Intrinsic::x86_sse2_comige_sd:
9524       Opc = X86ISD::COMI;
9525       CC = ISD::SETGE;
9526       break;
9527     case Intrinsic::x86_sse_comineq_ss:
9528     case Intrinsic::x86_sse2_comineq_sd:
9529       Opc = X86ISD::COMI;
9530       CC = ISD::SETNE;
9531       break;
9532     case Intrinsic::x86_sse_ucomieq_ss:
9533     case Intrinsic::x86_sse2_ucomieq_sd:
9534       Opc = X86ISD::UCOMI;
9535       CC = ISD::SETEQ;
9536       break;
9537     case Intrinsic::x86_sse_ucomilt_ss:
9538     case Intrinsic::x86_sse2_ucomilt_sd:
9539       Opc = X86ISD::UCOMI;
9540       CC = ISD::SETLT;
9541       break;
9542     case Intrinsic::x86_sse_ucomile_ss:
9543     case Intrinsic::x86_sse2_ucomile_sd:
9544       Opc = X86ISD::UCOMI;
9545       CC = ISD::SETLE;
9546       break;
9547     case Intrinsic::x86_sse_ucomigt_ss:
9548     case Intrinsic::x86_sse2_ucomigt_sd:
9549       Opc = X86ISD::UCOMI;
9550       CC = ISD::SETGT;
9551       break;
9552     case Intrinsic::x86_sse_ucomige_ss:
9553     case Intrinsic::x86_sse2_ucomige_sd:
9554       Opc = X86ISD::UCOMI;
9555       CC = ISD::SETGE;
9556       break;
9557     case Intrinsic::x86_sse_ucomineq_ss:
9558     case Intrinsic::x86_sse2_ucomineq_sd:
9559       Opc = X86ISD::UCOMI;
9560       CC = ISD::SETNE;
9561       break;
9562     }
9563
9564     SDValue LHS = Op.getOperand(1);
9565     SDValue RHS = Op.getOperand(2);
9566     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9567     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9568     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9569     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9570                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9571     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9572   }
9573   // Arithmetic intrinsics.
9574   case Intrinsic::x86_sse2_pmulu_dq:
9575   case Intrinsic::x86_avx2_pmulu_dq:
9576     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9577                        Op.getOperand(1), Op.getOperand(2));
9578   case Intrinsic::x86_sse3_hadd_ps:
9579   case Intrinsic::x86_sse3_hadd_pd:
9580   case Intrinsic::x86_avx_hadd_ps_256:
9581   case Intrinsic::x86_avx_hadd_pd_256:
9582     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9583                        Op.getOperand(1), Op.getOperand(2));
9584   case Intrinsic::x86_sse3_hsub_ps:
9585   case Intrinsic::x86_sse3_hsub_pd:
9586   case Intrinsic::x86_avx_hsub_ps_256:
9587   case Intrinsic::x86_avx_hsub_pd_256:
9588     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9589                        Op.getOperand(1), Op.getOperand(2));
9590   case Intrinsic::x86_ssse3_phadd_w_128:
9591   case Intrinsic::x86_ssse3_phadd_d_128:
9592   case Intrinsic::x86_avx2_phadd_w:
9593   case Intrinsic::x86_avx2_phadd_d:
9594     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9595                        Op.getOperand(1), Op.getOperand(2));
9596   case Intrinsic::x86_ssse3_phsub_w_128:
9597   case Intrinsic::x86_ssse3_phsub_d_128:
9598   case Intrinsic::x86_avx2_phsub_w:
9599   case Intrinsic::x86_avx2_phsub_d:
9600     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9601                        Op.getOperand(1), Op.getOperand(2));
9602   case Intrinsic::x86_avx2_psllv_d:
9603   case Intrinsic::x86_avx2_psllv_q:
9604   case Intrinsic::x86_avx2_psllv_d_256:
9605   case Intrinsic::x86_avx2_psllv_q_256:
9606     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9607                       Op.getOperand(1), Op.getOperand(2));
9608   case Intrinsic::x86_avx2_psrlv_d:
9609   case Intrinsic::x86_avx2_psrlv_q:
9610   case Intrinsic::x86_avx2_psrlv_d_256:
9611   case Intrinsic::x86_avx2_psrlv_q_256:
9612     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9613                       Op.getOperand(1), Op.getOperand(2));
9614   case Intrinsic::x86_avx2_psrav_d:
9615   case Intrinsic::x86_avx2_psrav_d_256:
9616     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9617                       Op.getOperand(1), Op.getOperand(2));
9618   case Intrinsic::x86_ssse3_pshuf_b_128:
9619   case Intrinsic::x86_avx2_pshuf_b:
9620     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9621                        Op.getOperand(1), Op.getOperand(2));
9622   case Intrinsic::x86_ssse3_psign_b_128:
9623   case Intrinsic::x86_ssse3_psign_w_128:
9624   case Intrinsic::x86_ssse3_psign_d_128:
9625   case Intrinsic::x86_avx2_psign_b:
9626   case Intrinsic::x86_avx2_psign_w:
9627   case Intrinsic::x86_avx2_psign_d:
9628     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9629                        Op.getOperand(1), Op.getOperand(2));
9630   case Intrinsic::x86_sse41_insertps:
9631     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9632                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9633   case Intrinsic::x86_avx_vperm2f128_ps_256:
9634   case Intrinsic::x86_avx_vperm2f128_pd_256:
9635   case Intrinsic::x86_avx_vperm2f128_si_256:
9636   case Intrinsic::x86_avx2_vperm2i128:
9637     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9638                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9639   case Intrinsic::x86_avx2_permd:
9640   case Intrinsic::x86_avx2_permps:
9641     // Operands intentionally swapped. Mask is last operand to intrinsic,
9642     // but second operand for node/intruction.
9643     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9644                        Op.getOperand(2), Op.getOperand(1));
9645
9646   // ptest and testp intrinsics. The intrinsic these come from are designed to
9647   // return an integer value, not just an instruction so lower it to the ptest
9648   // or testp pattern and a setcc for the result.
9649   case Intrinsic::x86_sse41_ptestz:
9650   case Intrinsic::x86_sse41_ptestc:
9651   case Intrinsic::x86_sse41_ptestnzc:
9652   case Intrinsic::x86_avx_ptestz_256:
9653   case Intrinsic::x86_avx_ptestc_256:
9654   case Intrinsic::x86_avx_ptestnzc_256:
9655   case Intrinsic::x86_avx_vtestz_ps:
9656   case Intrinsic::x86_avx_vtestc_ps:
9657   case Intrinsic::x86_avx_vtestnzc_ps:
9658   case Intrinsic::x86_avx_vtestz_pd:
9659   case Intrinsic::x86_avx_vtestc_pd:
9660   case Intrinsic::x86_avx_vtestnzc_pd:
9661   case Intrinsic::x86_avx_vtestz_ps_256:
9662   case Intrinsic::x86_avx_vtestc_ps_256:
9663   case Intrinsic::x86_avx_vtestnzc_ps_256:
9664   case Intrinsic::x86_avx_vtestz_pd_256:
9665   case Intrinsic::x86_avx_vtestc_pd_256:
9666   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9667     bool IsTestPacked = false;
9668     unsigned X86CC = 0;
9669     switch (IntNo) {
9670     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9671     case Intrinsic::x86_avx_vtestz_ps:
9672     case Intrinsic::x86_avx_vtestz_pd:
9673     case Intrinsic::x86_avx_vtestz_ps_256:
9674     case Intrinsic::x86_avx_vtestz_pd_256:
9675       IsTestPacked = true; // Fallthrough
9676     case Intrinsic::x86_sse41_ptestz:
9677     case Intrinsic::x86_avx_ptestz_256:
9678       // ZF = 1
9679       X86CC = X86::COND_E;
9680       break;
9681     case Intrinsic::x86_avx_vtestc_ps:
9682     case Intrinsic::x86_avx_vtestc_pd:
9683     case Intrinsic::x86_avx_vtestc_ps_256:
9684     case Intrinsic::x86_avx_vtestc_pd_256:
9685       IsTestPacked = true; // Fallthrough
9686     case Intrinsic::x86_sse41_ptestc:
9687     case Intrinsic::x86_avx_ptestc_256:
9688       // CF = 1
9689       X86CC = X86::COND_B;
9690       break;
9691     case Intrinsic::x86_avx_vtestnzc_ps:
9692     case Intrinsic::x86_avx_vtestnzc_pd:
9693     case Intrinsic::x86_avx_vtestnzc_ps_256:
9694     case Intrinsic::x86_avx_vtestnzc_pd_256:
9695       IsTestPacked = true; // Fallthrough
9696     case Intrinsic::x86_sse41_ptestnzc:
9697     case Intrinsic::x86_avx_ptestnzc_256:
9698       // ZF and CF = 0
9699       X86CC = X86::COND_A;
9700       break;
9701     }
9702
9703     SDValue LHS = Op.getOperand(1);
9704     SDValue RHS = Op.getOperand(2);
9705     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9706     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9707     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9708     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9709     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9710   }
9711
9712   // SSE/AVX shift intrinsics
9713   case Intrinsic::x86_sse2_psll_w:
9714   case Intrinsic::x86_sse2_psll_d:
9715   case Intrinsic::x86_sse2_psll_q:
9716   case Intrinsic::x86_avx2_psll_w:
9717   case Intrinsic::x86_avx2_psll_d:
9718   case Intrinsic::x86_avx2_psll_q:
9719     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9720                        Op.getOperand(1), Op.getOperand(2));
9721   case Intrinsic::x86_sse2_psrl_w:
9722   case Intrinsic::x86_sse2_psrl_d:
9723   case Intrinsic::x86_sse2_psrl_q:
9724   case Intrinsic::x86_avx2_psrl_w:
9725   case Intrinsic::x86_avx2_psrl_d:
9726   case Intrinsic::x86_avx2_psrl_q:
9727     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9728                        Op.getOperand(1), Op.getOperand(2));
9729   case Intrinsic::x86_sse2_psra_w:
9730   case Intrinsic::x86_sse2_psra_d:
9731   case Intrinsic::x86_avx2_psra_w:
9732   case Intrinsic::x86_avx2_psra_d:
9733     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9734                        Op.getOperand(1), Op.getOperand(2));
9735   case Intrinsic::x86_sse2_pslli_w:
9736   case Intrinsic::x86_sse2_pslli_d:
9737   case Intrinsic::x86_sse2_pslli_q:
9738   case Intrinsic::x86_avx2_pslli_w:
9739   case Intrinsic::x86_avx2_pslli_d:
9740   case Intrinsic::x86_avx2_pslli_q:
9741     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9742                                Op.getOperand(1), Op.getOperand(2), DAG);
9743   case Intrinsic::x86_sse2_psrli_w:
9744   case Intrinsic::x86_sse2_psrli_d:
9745   case Intrinsic::x86_sse2_psrli_q:
9746   case Intrinsic::x86_avx2_psrli_w:
9747   case Intrinsic::x86_avx2_psrli_d:
9748   case Intrinsic::x86_avx2_psrli_q:
9749     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9750                                Op.getOperand(1), Op.getOperand(2), DAG);
9751   case Intrinsic::x86_sse2_psrai_w:
9752   case Intrinsic::x86_sse2_psrai_d:
9753   case Intrinsic::x86_avx2_psrai_w:
9754   case Intrinsic::x86_avx2_psrai_d:
9755     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9756                                Op.getOperand(1), Op.getOperand(2), DAG);
9757   // Fix vector shift instructions where the last operand is a non-immediate
9758   // i32 value.
9759   case Intrinsic::x86_mmx_pslli_w:
9760   case Intrinsic::x86_mmx_pslli_d:
9761   case Intrinsic::x86_mmx_pslli_q:
9762   case Intrinsic::x86_mmx_psrli_w:
9763   case Intrinsic::x86_mmx_psrli_d:
9764   case Intrinsic::x86_mmx_psrli_q:
9765   case Intrinsic::x86_mmx_psrai_w:
9766   case Intrinsic::x86_mmx_psrai_d: {
9767     SDValue ShAmt = Op.getOperand(2);
9768     if (isa<ConstantSDNode>(ShAmt))
9769       return SDValue();
9770
9771     unsigned NewIntNo = 0;
9772     switch (IntNo) {
9773     case Intrinsic::x86_mmx_pslli_w:
9774       NewIntNo = Intrinsic::x86_mmx_psll_w;
9775       break;
9776     case Intrinsic::x86_mmx_pslli_d:
9777       NewIntNo = Intrinsic::x86_mmx_psll_d;
9778       break;
9779     case Intrinsic::x86_mmx_pslli_q:
9780       NewIntNo = Intrinsic::x86_mmx_psll_q;
9781       break;
9782     case Intrinsic::x86_mmx_psrli_w:
9783       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9784       break;
9785     case Intrinsic::x86_mmx_psrli_d:
9786       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9787       break;
9788     case Intrinsic::x86_mmx_psrli_q:
9789       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9790       break;
9791     case Intrinsic::x86_mmx_psrai_w:
9792       NewIntNo = Intrinsic::x86_mmx_psra_w;
9793       break;
9794     case Intrinsic::x86_mmx_psrai_d:
9795       NewIntNo = Intrinsic::x86_mmx_psra_d;
9796       break;
9797     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9798     }
9799
9800     // The vector shift intrinsics with scalars uses 32b shift amounts but
9801     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9802     // to be zero.
9803     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9804                          DAG.getConstant(0, MVT::i32));
9805 // FIXME this must be lowered to get rid of the invalid type.
9806
9807     EVT VT = Op.getValueType();
9808     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9809     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9810                        DAG.getConstant(NewIntNo, MVT::i32),
9811                        Op.getOperand(1), ShAmt);
9812   }
9813   case Intrinsic::x86_sse42_pcmpistria128:
9814   case Intrinsic::x86_sse42_pcmpestria128:
9815   case Intrinsic::x86_sse42_pcmpistric128:
9816   case Intrinsic::x86_sse42_pcmpestric128:
9817   case Intrinsic::x86_sse42_pcmpistrio128:
9818   case Intrinsic::x86_sse42_pcmpestrio128:
9819   case Intrinsic::x86_sse42_pcmpistris128:
9820   case Intrinsic::x86_sse42_pcmpestris128:
9821   case Intrinsic::x86_sse42_pcmpistriz128:
9822   case Intrinsic::x86_sse42_pcmpestriz128: {
9823     unsigned Opcode;
9824     unsigned X86CC;
9825     switch (IntNo) {
9826     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9827     case Intrinsic::x86_sse42_pcmpistria128:
9828       Opcode = X86ISD::PCMPISTRI;
9829       X86CC = X86::COND_A;
9830       break;
9831     case Intrinsic::x86_sse42_pcmpestria128:
9832       Opcode = X86ISD::PCMPESTRI;
9833       X86CC = X86::COND_A;
9834       break;
9835     case Intrinsic::x86_sse42_pcmpistric128:
9836       Opcode = X86ISD::PCMPISTRI;
9837       X86CC = X86::COND_B;
9838       break;
9839     case Intrinsic::x86_sse42_pcmpestric128:
9840       Opcode = X86ISD::PCMPESTRI;
9841       X86CC = X86::COND_B;
9842       break;
9843     case Intrinsic::x86_sse42_pcmpistrio128:
9844       Opcode = X86ISD::PCMPISTRI;
9845       X86CC = X86::COND_O;
9846       break;
9847     case Intrinsic::x86_sse42_pcmpestrio128:
9848       Opcode = X86ISD::PCMPESTRI;
9849       X86CC = X86::COND_O;
9850       break;
9851     case Intrinsic::x86_sse42_pcmpistris128:
9852       Opcode = X86ISD::PCMPISTRI;
9853       X86CC = X86::COND_S;
9854       break;
9855     case Intrinsic::x86_sse42_pcmpestris128:
9856       Opcode = X86ISD::PCMPESTRI;
9857       X86CC = X86::COND_S;
9858       break;
9859     case Intrinsic::x86_sse42_pcmpistriz128:
9860       Opcode = X86ISD::PCMPISTRI;
9861       X86CC = X86::COND_E;
9862       break;
9863     case Intrinsic::x86_sse42_pcmpestriz128:
9864       Opcode = X86ISD::PCMPESTRI;
9865       X86CC = X86::COND_E;
9866       break;
9867     }
9868     SmallVector<SDValue, 5> NewOps;
9869     NewOps.append(Op->op_begin()+1, Op->op_end());
9870     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9871     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
9872     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9873                                 DAG.getConstant(X86CC, MVT::i8),
9874                                 SDValue(PCMP.getNode(), 1));
9875     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9876   }
9877   case Intrinsic::x86_sse42_pcmpistri128:
9878   case Intrinsic::x86_sse42_pcmpestri128: {
9879     unsigned Opcode;
9880     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
9881       Opcode = X86ISD::PCMPISTRI;
9882     else
9883       Opcode = X86ISD::PCMPESTRI;
9884
9885     SmallVector<SDValue, 5> NewOps;
9886     NewOps.append(Op->op_begin()+1, Op->op_end());
9887     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9888     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
9889   }
9890   }
9891 }
9892
9893 SDValue
9894 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9895   DebugLoc dl = Op.getDebugLoc();
9896   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9897   switch (IntNo) {
9898   default: return SDValue();    // Don't custom lower most intrinsics.
9899
9900   // RDRAND intrinsics.
9901   case Intrinsic::x86_rdrand_16:
9902   case Intrinsic::x86_rdrand_32:
9903   case Intrinsic::x86_rdrand_64: {
9904     // Emit the node with the right value type.
9905     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
9906     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
9907
9908     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
9909     // return the value from Rand, which is always 0, casted to i32.
9910     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
9911                       DAG.getConstant(1, Op->getValueType(1)),
9912                       DAG.getConstant(X86::COND_B, MVT::i32),
9913                       SDValue(Result.getNode(), 1) };
9914     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
9915                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
9916                                   Ops, 4);
9917
9918     // Return { result, isValid, chain }.
9919     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
9920                        SDValue(Result.getNode(), 2));
9921   }
9922   }
9923 }
9924
9925 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9926                                            SelectionDAG &DAG) const {
9927   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9928   MFI->setReturnAddressIsTaken(true);
9929
9930   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9931   DebugLoc dl = Op.getDebugLoc();
9932
9933   if (Depth > 0) {
9934     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9935     SDValue Offset =
9936       DAG.getConstant(TD->getPointerSize(),
9937                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9938     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9939                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9940                                    FrameAddr, Offset),
9941                        MachinePointerInfo(), false, false, false, 0);
9942   }
9943
9944   // Just load the return address.
9945   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9946   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9947                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9948 }
9949
9950 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9951   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9952   MFI->setFrameAddressIsTaken(true);
9953
9954   EVT VT = Op.getValueType();
9955   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9956   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9957   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9958   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9959   while (Depth--)
9960     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9961                             MachinePointerInfo(),
9962                             false, false, false, 0);
9963   return FrameAddr;
9964 }
9965
9966 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9967                                                      SelectionDAG &DAG) const {
9968   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9969 }
9970
9971 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9972   SDValue Chain     = Op.getOperand(0);
9973   SDValue Offset    = Op.getOperand(1);
9974   SDValue Handler   = Op.getOperand(2);
9975   DebugLoc dl       = Op.getDebugLoc();
9976
9977   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9978                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9979                                      getPointerTy());
9980   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9981
9982   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9983                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9984   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9985   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9986                        false, false, 0);
9987   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9988
9989   return DAG.getNode(X86ISD::EH_RETURN, dl,
9990                      MVT::Other,
9991                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9992 }
9993
9994 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9995                                                   SelectionDAG &DAG) const {
9996   return Op.getOperand(0);
9997 }
9998
9999 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10000                                                 SelectionDAG &DAG) const {
10001   SDValue Root = Op.getOperand(0);
10002   SDValue Trmp = Op.getOperand(1); // trampoline
10003   SDValue FPtr = Op.getOperand(2); // nested function
10004   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10005   DebugLoc dl  = Op.getDebugLoc();
10006
10007   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10008
10009   if (Subtarget->is64Bit()) {
10010     SDValue OutChains[6];
10011
10012     // Large code-model.
10013     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10014     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10015
10016     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10017     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10018
10019     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10020
10021     // Load the pointer to the nested function into R11.
10022     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10023     SDValue Addr = Trmp;
10024     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10025                                 Addr, MachinePointerInfo(TrmpAddr),
10026                                 false, false, 0);
10027
10028     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10029                        DAG.getConstant(2, MVT::i64));
10030     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10031                                 MachinePointerInfo(TrmpAddr, 2),
10032                                 false, false, 2);
10033
10034     // Load the 'nest' parameter value into R10.
10035     // R10 is specified in X86CallingConv.td
10036     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10037     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10038                        DAG.getConstant(10, MVT::i64));
10039     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10040                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10041                                 false, false, 0);
10042
10043     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10044                        DAG.getConstant(12, MVT::i64));
10045     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10046                                 MachinePointerInfo(TrmpAddr, 12),
10047                                 false, false, 2);
10048
10049     // Jump to the nested function.
10050     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10051     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10052                        DAG.getConstant(20, MVT::i64));
10053     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10054                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10055                                 false, false, 0);
10056
10057     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10058     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10059                        DAG.getConstant(22, MVT::i64));
10060     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10061                                 MachinePointerInfo(TrmpAddr, 22),
10062                                 false, false, 0);
10063
10064     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10065   } else {
10066     const Function *Func =
10067       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10068     CallingConv::ID CC = Func->getCallingConv();
10069     unsigned NestReg;
10070
10071     switch (CC) {
10072     default:
10073       llvm_unreachable("Unsupported calling convention");
10074     case CallingConv::C:
10075     case CallingConv::X86_StdCall: {
10076       // Pass 'nest' parameter in ECX.
10077       // Must be kept in sync with X86CallingConv.td
10078       NestReg = X86::ECX;
10079
10080       // Check that ECX wasn't needed by an 'inreg' parameter.
10081       FunctionType *FTy = Func->getFunctionType();
10082       const AttrListPtr &Attrs = Func->getAttributes();
10083
10084       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10085         unsigned InRegCount = 0;
10086         unsigned Idx = 1;
10087
10088         for (FunctionType::param_iterator I = FTy->param_begin(),
10089              E = FTy->param_end(); I != E; ++I, ++Idx)
10090           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10091             // FIXME: should only count parameters that are lowered to integers.
10092             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10093
10094         if (InRegCount > 2) {
10095           report_fatal_error("Nest register in use - reduce number of inreg"
10096                              " parameters!");
10097         }
10098       }
10099       break;
10100     }
10101     case CallingConv::X86_FastCall:
10102     case CallingConv::X86_ThisCall:
10103     case CallingConv::Fast:
10104       // Pass 'nest' parameter in EAX.
10105       // Must be kept in sync with X86CallingConv.td
10106       NestReg = X86::EAX;
10107       break;
10108     }
10109
10110     SDValue OutChains[4];
10111     SDValue Addr, Disp;
10112
10113     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10114                        DAG.getConstant(10, MVT::i32));
10115     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10116
10117     // This is storing the opcode for MOV32ri.
10118     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10119     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10120     OutChains[0] = DAG.getStore(Root, dl,
10121                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10122                                 Trmp, MachinePointerInfo(TrmpAddr),
10123                                 false, false, 0);
10124
10125     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10126                        DAG.getConstant(1, MVT::i32));
10127     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10128                                 MachinePointerInfo(TrmpAddr, 1),
10129                                 false, false, 1);
10130
10131     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10132     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10133                        DAG.getConstant(5, MVT::i32));
10134     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10135                                 MachinePointerInfo(TrmpAddr, 5),
10136                                 false, false, 1);
10137
10138     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10139                        DAG.getConstant(6, MVT::i32));
10140     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10141                                 MachinePointerInfo(TrmpAddr, 6),
10142                                 false, false, 1);
10143
10144     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10145   }
10146 }
10147
10148 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10149                                             SelectionDAG &DAG) const {
10150   /*
10151    The rounding mode is in bits 11:10 of FPSR, and has the following
10152    settings:
10153      00 Round to nearest
10154      01 Round to -inf
10155      10 Round to +inf
10156      11 Round to 0
10157
10158   FLT_ROUNDS, on the other hand, expects the following:
10159     -1 Undefined
10160      0 Round to 0
10161      1 Round to nearest
10162      2 Round to +inf
10163      3 Round to -inf
10164
10165   To perform the conversion, we do:
10166     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10167   */
10168
10169   MachineFunction &MF = DAG.getMachineFunction();
10170   const TargetMachine &TM = MF.getTarget();
10171   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10172   unsigned StackAlignment = TFI.getStackAlignment();
10173   EVT VT = Op.getValueType();
10174   DebugLoc DL = Op.getDebugLoc();
10175
10176   // Save FP Control Word to stack slot
10177   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10178   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10179
10180
10181   MachineMemOperand *MMO =
10182    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10183                            MachineMemOperand::MOStore, 2, 2);
10184
10185   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10186   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10187                                           DAG.getVTList(MVT::Other),
10188                                           Ops, 2, MVT::i16, MMO);
10189
10190   // Load FP Control Word from stack slot
10191   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10192                             MachinePointerInfo(), false, false, false, 0);
10193
10194   // Transform as necessary
10195   SDValue CWD1 =
10196     DAG.getNode(ISD::SRL, DL, MVT::i16,
10197                 DAG.getNode(ISD::AND, DL, MVT::i16,
10198                             CWD, DAG.getConstant(0x800, MVT::i16)),
10199                 DAG.getConstant(11, MVT::i8));
10200   SDValue CWD2 =
10201     DAG.getNode(ISD::SRL, DL, MVT::i16,
10202                 DAG.getNode(ISD::AND, DL, MVT::i16,
10203                             CWD, DAG.getConstant(0x400, MVT::i16)),
10204                 DAG.getConstant(9, MVT::i8));
10205
10206   SDValue RetVal =
10207     DAG.getNode(ISD::AND, DL, MVT::i16,
10208                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10209                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10210                             DAG.getConstant(1, MVT::i16)),
10211                 DAG.getConstant(3, MVT::i16));
10212
10213
10214   return DAG.getNode((VT.getSizeInBits() < 16 ?
10215                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10216 }
10217
10218 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10219   EVT VT = Op.getValueType();
10220   EVT OpVT = VT;
10221   unsigned NumBits = VT.getSizeInBits();
10222   DebugLoc dl = Op.getDebugLoc();
10223
10224   Op = Op.getOperand(0);
10225   if (VT == MVT::i8) {
10226     // Zero extend to i32 since there is not an i8 bsr.
10227     OpVT = MVT::i32;
10228     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10229   }
10230
10231   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10232   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10233   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10234
10235   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10236   SDValue Ops[] = {
10237     Op,
10238     DAG.getConstant(NumBits+NumBits-1, OpVT),
10239     DAG.getConstant(X86::COND_E, MVT::i8),
10240     Op.getValue(1)
10241   };
10242   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10243
10244   // Finally xor with NumBits-1.
10245   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10246
10247   if (VT == MVT::i8)
10248     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10249   return Op;
10250 }
10251
10252 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10253                                                 SelectionDAG &DAG) const {
10254   EVT VT = Op.getValueType();
10255   EVT OpVT = VT;
10256   unsigned NumBits = VT.getSizeInBits();
10257   DebugLoc dl = Op.getDebugLoc();
10258
10259   Op = Op.getOperand(0);
10260   if (VT == MVT::i8) {
10261     // Zero extend to i32 since there is not an i8 bsr.
10262     OpVT = MVT::i32;
10263     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10264   }
10265
10266   // Issue a bsr (scan bits in reverse).
10267   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10268   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10269
10270   // And xor with NumBits-1.
10271   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10272
10273   if (VT == MVT::i8)
10274     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10275   return Op;
10276 }
10277
10278 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10279   EVT VT = Op.getValueType();
10280   unsigned NumBits = VT.getSizeInBits();
10281   DebugLoc dl = Op.getDebugLoc();
10282   Op = Op.getOperand(0);
10283
10284   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10285   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10286   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10287
10288   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10289   SDValue Ops[] = {
10290     Op,
10291     DAG.getConstant(NumBits, VT),
10292     DAG.getConstant(X86::COND_E, MVT::i8),
10293     Op.getValue(1)
10294   };
10295   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10296 }
10297
10298 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10299 // ones, and then concatenate the result back.
10300 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10301   EVT VT = Op.getValueType();
10302
10303   assert(VT.is256BitVector() && VT.isInteger() &&
10304          "Unsupported value type for operation");
10305
10306   unsigned NumElems = VT.getVectorNumElements();
10307   DebugLoc dl = Op.getDebugLoc();
10308
10309   // Extract the LHS vectors
10310   SDValue LHS = Op.getOperand(0);
10311   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10312   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10313
10314   // Extract the RHS vectors
10315   SDValue RHS = Op.getOperand(1);
10316   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10317   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10318
10319   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10320   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10321
10322   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10323                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10324                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10325 }
10326
10327 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10328   assert(Op.getValueType().is256BitVector() &&
10329          Op.getValueType().isInteger() &&
10330          "Only handle AVX 256-bit vector integer operation");
10331   return Lower256IntArith(Op, DAG);
10332 }
10333
10334 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10335   assert(Op.getValueType().is256BitVector() &&
10336          Op.getValueType().isInteger() &&
10337          "Only handle AVX 256-bit vector integer operation");
10338   return Lower256IntArith(Op, DAG);
10339 }
10340
10341 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10342   EVT VT = Op.getValueType();
10343
10344   // Decompose 256-bit ops into smaller 128-bit ops.
10345   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10346     return Lower256IntArith(Op, DAG);
10347
10348   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10349          "Only know how to lower V2I64/V4I64 multiply");
10350
10351   DebugLoc dl = Op.getDebugLoc();
10352
10353   //  Ahi = psrlqi(a, 32);
10354   //  Bhi = psrlqi(b, 32);
10355   //
10356   //  AloBlo = pmuludq(a, b);
10357   //  AloBhi = pmuludq(a, Bhi);
10358   //  AhiBlo = pmuludq(Ahi, b);
10359
10360   //  AloBhi = psllqi(AloBhi, 32);
10361   //  AhiBlo = psllqi(AhiBlo, 32);
10362   //  return AloBlo + AloBhi + AhiBlo;
10363
10364   SDValue A = Op.getOperand(0);
10365   SDValue B = Op.getOperand(1);
10366
10367   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10368
10369   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10370   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10371
10372   // Bit cast to 32-bit vectors for MULUDQ
10373   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10374   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10375   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10376   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10377   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10378
10379   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10380   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10381   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10382
10383   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10384   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10385
10386   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10387   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10388 }
10389
10390 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10391
10392   EVT VT = Op.getValueType();
10393   DebugLoc dl = Op.getDebugLoc();
10394   SDValue R = Op.getOperand(0);
10395   SDValue Amt = Op.getOperand(1);
10396   LLVMContext *Context = DAG.getContext();
10397
10398   if (!Subtarget->hasSSE2())
10399     return SDValue();
10400
10401   // Optimize shl/srl/sra with constant shift amount.
10402   if (isSplatVector(Amt.getNode())) {
10403     SDValue SclrAmt = Amt->getOperand(0);
10404     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10405       uint64_t ShiftAmt = C->getZExtValue();
10406
10407       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10408           (Subtarget->hasAVX2() &&
10409            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10410         if (Op.getOpcode() == ISD::SHL)
10411           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10412                              DAG.getConstant(ShiftAmt, MVT::i32));
10413         if (Op.getOpcode() == ISD::SRL)
10414           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10415                              DAG.getConstant(ShiftAmt, MVT::i32));
10416         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10417           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10418                              DAG.getConstant(ShiftAmt, MVT::i32));
10419       }
10420
10421       if (VT == MVT::v16i8) {
10422         if (Op.getOpcode() == ISD::SHL) {
10423           // Make a large shift.
10424           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10425                                     DAG.getConstant(ShiftAmt, MVT::i32));
10426           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10427           // Zero out the rightmost bits.
10428           SmallVector<SDValue, 16> V(16,
10429                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10430                                                      MVT::i8));
10431           return DAG.getNode(ISD::AND, dl, VT, SHL,
10432                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10433         }
10434         if (Op.getOpcode() == ISD::SRL) {
10435           // Make a large shift.
10436           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10437                                     DAG.getConstant(ShiftAmt, MVT::i32));
10438           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10439           // Zero out the leftmost bits.
10440           SmallVector<SDValue, 16> V(16,
10441                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10442                                                      MVT::i8));
10443           return DAG.getNode(ISD::AND, dl, VT, SRL,
10444                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10445         }
10446         if (Op.getOpcode() == ISD::SRA) {
10447           if (ShiftAmt == 7) {
10448             // R s>> 7  ===  R s< 0
10449             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10450             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10451           }
10452
10453           // R s>> a === ((R u>> a) ^ m) - m
10454           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10455           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10456                                                          MVT::i8));
10457           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10458           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10459           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10460           return Res;
10461         }
10462         llvm_unreachable("Unknown shift opcode.");
10463       }
10464
10465       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10466         if (Op.getOpcode() == ISD::SHL) {
10467           // Make a large shift.
10468           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10469                                     DAG.getConstant(ShiftAmt, MVT::i32));
10470           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10471           // Zero out the rightmost bits.
10472           SmallVector<SDValue, 32> V(32,
10473                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10474                                                      MVT::i8));
10475           return DAG.getNode(ISD::AND, dl, VT, SHL,
10476                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10477         }
10478         if (Op.getOpcode() == ISD::SRL) {
10479           // Make a large shift.
10480           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10481                                     DAG.getConstant(ShiftAmt, MVT::i32));
10482           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10483           // Zero out the leftmost bits.
10484           SmallVector<SDValue, 32> V(32,
10485                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10486                                                      MVT::i8));
10487           return DAG.getNode(ISD::AND, dl, VT, SRL,
10488                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10489         }
10490         if (Op.getOpcode() == ISD::SRA) {
10491           if (ShiftAmt == 7) {
10492             // R s>> 7  ===  R s< 0
10493             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10494             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10495           }
10496
10497           // R s>> a === ((R u>> a) ^ m) - m
10498           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10499           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10500                                                          MVT::i8));
10501           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10502           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10503           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10504           return Res;
10505         }
10506         llvm_unreachable("Unknown shift opcode.");
10507       }
10508     }
10509   }
10510
10511   // Lower SHL with variable shift amount.
10512   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10513     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10514                      DAG.getConstant(23, MVT::i32));
10515
10516     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10517     Constant *C = ConstantDataVector::get(*Context, CV);
10518     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10519     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10520                                  MachinePointerInfo::getConstantPool(),
10521                                  false, false, false, 16);
10522
10523     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10524     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10525     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10526     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10527   }
10528   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10529     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10530
10531     // a = a << 5;
10532     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10533                      DAG.getConstant(5, MVT::i32));
10534     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10535
10536     // Turn 'a' into a mask suitable for VSELECT
10537     SDValue VSelM = DAG.getConstant(0x80, VT);
10538     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10539     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10540
10541     SDValue CM1 = DAG.getConstant(0x0f, VT);
10542     SDValue CM2 = DAG.getConstant(0x3f, VT);
10543
10544     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10545     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10546     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10547                             DAG.getConstant(4, MVT::i32), DAG);
10548     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10549     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10550
10551     // a += a
10552     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10553     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10554     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10555
10556     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10557     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10558     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10559                             DAG.getConstant(2, MVT::i32), DAG);
10560     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10561     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10562
10563     // a += a
10564     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10565     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10566     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10567
10568     // return VSELECT(r, r+r, a);
10569     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10570                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10571     return R;
10572   }
10573
10574   // Decompose 256-bit shifts into smaller 128-bit shifts.
10575   if (VT.is256BitVector()) {
10576     unsigned NumElems = VT.getVectorNumElements();
10577     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10578     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10579
10580     // Extract the two vectors
10581     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10582     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10583
10584     // Recreate the shift amount vectors
10585     SDValue Amt1, Amt2;
10586     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10587       // Constant shift amount
10588       SmallVector<SDValue, 4> Amt1Csts;
10589       SmallVector<SDValue, 4> Amt2Csts;
10590       for (unsigned i = 0; i != NumElems/2; ++i)
10591         Amt1Csts.push_back(Amt->getOperand(i));
10592       for (unsigned i = NumElems/2; i != NumElems; ++i)
10593         Amt2Csts.push_back(Amt->getOperand(i));
10594
10595       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10596                                  &Amt1Csts[0], NumElems/2);
10597       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10598                                  &Amt2Csts[0], NumElems/2);
10599     } else {
10600       // Variable shift amount
10601       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10602       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10603     }
10604
10605     // Issue new vector shifts for the smaller types
10606     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10607     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10608
10609     // Concatenate the result back
10610     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10611   }
10612
10613   return SDValue();
10614 }
10615
10616 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10617   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10618   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10619   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10620   // has only one use.
10621   SDNode *N = Op.getNode();
10622   SDValue LHS = N->getOperand(0);
10623   SDValue RHS = N->getOperand(1);
10624   unsigned BaseOp = 0;
10625   unsigned Cond = 0;
10626   DebugLoc DL = Op.getDebugLoc();
10627   switch (Op.getOpcode()) {
10628   default: llvm_unreachable("Unknown ovf instruction!");
10629   case ISD::SADDO:
10630     // A subtract of one will be selected as a INC. Note that INC doesn't
10631     // set CF, so we can't do this for UADDO.
10632     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10633       if (C->isOne()) {
10634         BaseOp = X86ISD::INC;
10635         Cond = X86::COND_O;
10636         break;
10637       }
10638     BaseOp = X86ISD::ADD;
10639     Cond = X86::COND_O;
10640     break;
10641   case ISD::UADDO:
10642     BaseOp = X86ISD::ADD;
10643     Cond = X86::COND_B;
10644     break;
10645   case ISD::SSUBO:
10646     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10647     // set CF, so we can't do this for USUBO.
10648     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10649       if (C->isOne()) {
10650         BaseOp = X86ISD::DEC;
10651         Cond = X86::COND_O;
10652         break;
10653       }
10654     BaseOp = X86ISD::SUB;
10655     Cond = X86::COND_O;
10656     break;
10657   case ISD::USUBO:
10658     BaseOp = X86ISD::SUB;
10659     Cond = X86::COND_B;
10660     break;
10661   case ISD::SMULO:
10662     BaseOp = X86ISD::SMUL;
10663     Cond = X86::COND_O;
10664     break;
10665   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10666     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10667                                  MVT::i32);
10668     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10669
10670     SDValue SetCC =
10671       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10672                   DAG.getConstant(X86::COND_O, MVT::i32),
10673                   SDValue(Sum.getNode(), 2));
10674
10675     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10676   }
10677   }
10678
10679   // Also sets EFLAGS.
10680   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10681   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10682
10683   SDValue SetCC =
10684     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10685                 DAG.getConstant(Cond, MVT::i32),
10686                 SDValue(Sum.getNode(), 1));
10687
10688   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10689 }
10690
10691 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10692                                                   SelectionDAG &DAG) const {
10693   DebugLoc dl = Op.getDebugLoc();
10694   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10695   EVT VT = Op.getValueType();
10696
10697   if (!Subtarget->hasSSE2() || !VT.isVector())
10698     return SDValue();
10699
10700   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10701                       ExtraVT.getScalarType().getSizeInBits();
10702   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10703
10704   switch (VT.getSimpleVT().SimpleTy) {
10705     default: return SDValue();
10706     case MVT::v8i32:
10707     case MVT::v16i16:
10708       if (!Subtarget->hasAVX())
10709         return SDValue();
10710       if (!Subtarget->hasAVX2()) {
10711         // needs to be split
10712         unsigned NumElems = VT.getVectorNumElements();
10713
10714         // Extract the LHS vectors
10715         SDValue LHS = Op.getOperand(0);
10716         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10717         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10718
10719         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10720         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10721
10722         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10723         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10724         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10725                                    ExtraNumElems/2);
10726         SDValue Extra = DAG.getValueType(ExtraVT);
10727
10728         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10729         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10730
10731         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10732       }
10733       // fall through
10734     case MVT::v4i32:
10735     case MVT::v8i16: {
10736       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10737                                          Op.getOperand(0), ShAmt, DAG);
10738       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10739     }
10740   }
10741 }
10742
10743
10744 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10745   DebugLoc dl = Op.getDebugLoc();
10746
10747   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10748   // There isn't any reason to disable it if the target processor supports it.
10749   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10750     SDValue Chain = Op.getOperand(0);
10751     SDValue Zero = DAG.getConstant(0, MVT::i32);
10752     SDValue Ops[] = {
10753       DAG.getRegister(X86::ESP, MVT::i32), // Base
10754       DAG.getTargetConstant(1, MVT::i8),   // Scale
10755       DAG.getRegister(0, MVT::i32),        // Index
10756       DAG.getTargetConstant(0, MVT::i32),  // Disp
10757       DAG.getRegister(0, MVT::i32),        // Segment.
10758       Zero,
10759       Chain
10760     };
10761     SDNode *Res =
10762       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10763                           array_lengthof(Ops));
10764     return SDValue(Res, 0);
10765   }
10766
10767   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10768   if (!isDev)
10769     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10770
10771   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10772   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10773   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10774   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10775
10776   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10777   if (!Op1 && !Op2 && !Op3 && Op4)
10778     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10779
10780   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10781   if (Op1 && !Op2 && !Op3 && !Op4)
10782     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10783
10784   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10785   //           (MFENCE)>;
10786   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10787 }
10788
10789 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10790                                              SelectionDAG &DAG) const {
10791   DebugLoc dl = Op.getDebugLoc();
10792   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10793     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10794   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10795     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10796
10797   // The only fence that needs an instruction is a sequentially-consistent
10798   // cross-thread fence.
10799   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10800     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10801     // no-sse2). There isn't any reason to disable it if the target processor
10802     // supports it.
10803     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10804       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10805
10806     SDValue Chain = Op.getOperand(0);
10807     SDValue Zero = DAG.getConstant(0, MVT::i32);
10808     SDValue Ops[] = {
10809       DAG.getRegister(X86::ESP, MVT::i32), // Base
10810       DAG.getTargetConstant(1, MVT::i8),   // Scale
10811       DAG.getRegister(0, MVT::i32),        // Index
10812       DAG.getTargetConstant(0, MVT::i32),  // Disp
10813       DAG.getRegister(0, MVT::i32),        // Segment.
10814       Zero,
10815       Chain
10816     };
10817     SDNode *Res =
10818       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10819                          array_lengthof(Ops));
10820     return SDValue(Res, 0);
10821   }
10822
10823   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10824   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10825 }
10826
10827
10828 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10829   EVT T = Op.getValueType();
10830   DebugLoc DL = Op.getDebugLoc();
10831   unsigned Reg = 0;
10832   unsigned size = 0;
10833   switch(T.getSimpleVT().SimpleTy) {
10834   default: llvm_unreachable("Invalid value type!");
10835   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10836   case MVT::i16: Reg = X86::AX;  size = 2; break;
10837   case MVT::i32: Reg = X86::EAX; size = 4; break;
10838   case MVT::i64:
10839     assert(Subtarget->is64Bit() && "Node not type legal!");
10840     Reg = X86::RAX; size = 8;
10841     break;
10842   }
10843   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10844                                     Op.getOperand(2), SDValue());
10845   SDValue Ops[] = { cpIn.getValue(0),
10846                     Op.getOperand(1),
10847                     Op.getOperand(3),
10848                     DAG.getTargetConstant(size, MVT::i8),
10849                     cpIn.getValue(1) };
10850   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10851   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10852   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10853                                            Ops, 5, T, MMO);
10854   SDValue cpOut =
10855     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10856   return cpOut;
10857 }
10858
10859 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10860                                                  SelectionDAG &DAG) const {
10861   assert(Subtarget->is64Bit() && "Result not type legalized?");
10862   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10863   SDValue TheChain = Op.getOperand(0);
10864   DebugLoc dl = Op.getDebugLoc();
10865   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10866   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10867   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10868                                    rax.getValue(2));
10869   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10870                             DAG.getConstant(32, MVT::i8));
10871   SDValue Ops[] = {
10872     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10873     rdx.getValue(1)
10874   };
10875   return DAG.getMergeValues(Ops, 2, dl);
10876 }
10877
10878 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10879                                             SelectionDAG &DAG) const {
10880   EVT SrcVT = Op.getOperand(0).getValueType();
10881   EVT DstVT = Op.getValueType();
10882   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10883          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10884   assert((DstVT == MVT::i64 ||
10885           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10886          "Unexpected custom BITCAST");
10887   // i64 <=> MMX conversions are Legal.
10888   if (SrcVT==MVT::i64 && DstVT.isVector())
10889     return Op;
10890   if (DstVT==MVT::i64 && SrcVT.isVector())
10891     return Op;
10892   // MMX <=> MMX conversions are Legal.
10893   if (SrcVT.isVector() && DstVT.isVector())
10894     return Op;
10895   // All other conversions need to be expanded.
10896   return SDValue();
10897 }
10898
10899 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10900   SDNode *Node = Op.getNode();
10901   DebugLoc dl = Node->getDebugLoc();
10902   EVT T = Node->getValueType(0);
10903   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10904                               DAG.getConstant(0, T), Node->getOperand(2));
10905   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10906                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10907                        Node->getOperand(0),
10908                        Node->getOperand(1), negOp,
10909                        cast<AtomicSDNode>(Node)->getSrcValue(),
10910                        cast<AtomicSDNode>(Node)->getAlignment(),
10911                        cast<AtomicSDNode>(Node)->getOrdering(),
10912                        cast<AtomicSDNode>(Node)->getSynchScope());
10913 }
10914
10915 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10916   SDNode *Node = Op.getNode();
10917   DebugLoc dl = Node->getDebugLoc();
10918   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10919
10920   // Convert seq_cst store -> xchg
10921   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10922   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10923   //        (The only way to get a 16-byte store is cmpxchg16b)
10924   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10925   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10926       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10927     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10928                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10929                                  Node->getOperand(0),
10930                                  Node->getOperand(1), Node->getOperand(2),
10931                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10932                                  cast<AtomicSDNode>(Node)->getOrdering(),
10933                                  cast<AtomicSDNode>(Node)->getSynchScope());
10934     return Swap.getValue(1);
10935   }
10936   // Other atomic stores have a simple pattern.
10937   return Op;
10938 }
10939
10940 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10941   EVT VT = Op.getNode()->getValueType(0);
10942
10943   // Let legalize expand this if it isn't a legal type yet.
10944   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10945     return SDValue();
10946
10947   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10948
10949   unsigned Opc;
10950   bool ExtraOp = false;
10951   switch (Op.getOpcode()) {
10952   default: llvm_unreachable("Invalid code");
10953   case ISD::ADDC: Opc = X86ISD::ADD; break;
10954   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10955   case ISD::SUBC: Opc = X86ISD::SUB; break;
10956   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10957   }
10958
10959   if (!ExtraOp)
10960     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10961                        Op.getOperand(1));
10962   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10963                      Op.getOperand(1), Op.getOperand(2));
10964 }
10965
10966 /// LowerOperation - Provide custom lowering hooks for some operations.
10967 ///
10968 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10969   switch (Op.getOpcode()) {
10970   default: llvm_unreachable("Should not custom lower this!");
10971   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10972   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10973   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10974   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10975   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10976   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10977   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10978   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10979   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10980   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10981   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10982   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10983   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10984   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10985   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10986   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10987   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10988   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10989   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10990   case ISD::SHL_PARTS:
10991   case ISD::SRA_PARTS:
10992   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10993   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10994   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10995   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10996   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10997   case ISD::FABS:               return LowerFABS(Op, DAG);
10998   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10999   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11000   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11001   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11002   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11003   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11004   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11005   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11006   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11007   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11008   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11009   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11010   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11011   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11012   case ISD::FRAME_TO_ARGS_OFFSET:
11013                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11014   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11015   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11016   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11017   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11018   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11019   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11020   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11021   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11022   case ISD::MUL:                return LowerMUL(Op, DAG);
11023   case ISD::SRA:
11024   case ISD::SRL:
11025   case ISD::SHL:                return LowerShift(Op, DAG);
11026   case ISD::SADDO:
11027   case ISD::UADDO:
11028   case ISD::SSUBO:
11029   case ISD::USUBO:
11030   case ISD::SMULO:
11031   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11032   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
11033   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11034   case ISD::ADDC:
11035   case ISD::ADDE:
11036   case ISD::SUBC:
11037   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11038   case ISD::ADD:                return LowerADD(Op, DAG);
11039   case ISD::SUB:                return LowerSUB(Op, DAG);
11040   }
11041 }
11042
11043 static void ReplaceATOMIC_LOAD(SDNode *Node,
11044                                   SmallVectorImpl<SDValue> &Results,
11045                                   SelectionDAG &DAG) {
11046   DebugLoc dl = Node->getDebugLoc();
11047   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11048
11049   // Convert wide load -> cmpxchg8b/cmpxchg16b
11050   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11051   //        (The only way to get a 16-byte load is cmpxchg16b)
11052   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11053   SDValue Zero = DAG.getConstant(0, VT);
11054   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11055                                Node->getOperand(0),
11056                                Node->getOperand(1), Zero, Zero,
11057                                cast<AtomicSDNode>(Node)->getMemOperand(),
11058                                cast<AtomicSDNode>(Node)->getOrdering(),
11059                                cast<AtomicSDNode>(Node)->getSynchScope());
11060   Results.push_back(Swap.getValue(0));
11061   Results.push_back(Swap.getValue(1));
11062 }
11063
11064 void X86TargetLowering::
11065 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11066                         SelectionDAG &DAG, unsigned NewOp) const {
11067   DebugLoc dl = Node->getDebugLoc();
11068   assert (Node->getValueType(0) == MVT::i64 &&
11069           "Only know how to expand i64 atomics");
11070
11071   SDValue Chain = Node->getOperand(0);
11072   SDValue In1 = Node->getOperand(1);
11073   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11074                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11075   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11076                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11077   SDValue Ops[] = { Chain, In1, In2L, In2H };
11078   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11079   SDValue Result =
11080     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11081                             cast<MemSDNode>(Node)->getMemOperand());
11082   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11083   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11084   Results.push_back(Result.getValue(2));
11085 }
11086
11087 /// ReplaceNodeResults - Replace a node with an illegal result type
11088 /// with a new node built out of custom code.
11089 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11090                                            SmallVectorImpl<SDValue>&Results,
11091                                            SelectionDAG &DAG) const {
11092   DebugLoc dl = N->getDebugLoc();
11093   switch (N->getOpcode()) {
11094   default:
11095     llvm_unreachable("Do not know how to custom type legalize this operation!");
11096   case ISD::SIGN_EXTEND_INREG:
11097   case ISD::ADDC:
11098   case ISD::ADDE:
11099   case ISD::SUBC:
11100   case ISD::SUBE:
11101     // We don't want to expand or promote these.
11102     return;
11103   case ISD::FP_TO_SINT:
11104   case ISD::FP_TO_UINT: {
11105     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11106
11107     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11108       return;
11109
11110     std::pair<SDValue,SDValue> Vals =
11111         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11112     SDValue FIST = Vals.first, StackSlot = Vals.second;
11113     if (FIST.getNode() != 0) {
11114       EVT VT = N->getValueType(0);
11115       // Return a load from the stack slot.
11116       if (StackSlot.getNode() != 0)
11117         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11118                                       MachinePointerInfo(),
11119                                       false, false, false, 0));
11120       else
11121         Results.push_back(FIST);
11122     }
11123     return;
11124   }
11125   case ISD::READCYCLECOUNTER: {
11126     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11127     SDValue TheChain = N->getOperand(0);
11128     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11129     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11130                                      rd.getValue(1));
11131     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11132                                      eax.getValue(2));
11133     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11134     SDValue Ops[] = { eax, edx };
11135     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11136     Results.push_back(edx.getValue(1));
11137     return;
11138   }
11139   case ISD::ATOMIC_CMP_SWAP: {
11140     EVT T = N->getValueType(0);
11141     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11142     bool Regs64bit = T == MVT::i128;
11143     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11144     SDValue cpInL, cpInH;
11145     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11146                         DAG.getConstant(0, HalfT));
11147     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11148                         DAG.getConstant(1, HalfT));
11149     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11150                              Regs64bit ? X86::RAX : X86::EAX,
11151                              cpInL, SDValue());
11152     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11153                              Regs64bit ? X86::RDX : X86::EDX,
11154                              cpInH, cpInL.getValue(1));
11155     SDValue swapInL, swapInH;
11156     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11157                           DAG.getConstant(0, HalfT));
11158     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11159                           DAG.getConstant(1, HalfT));
11160     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11161                                Regs64bit ? X86::RBX : X86::EBX,
11162                                swapInL, cpInH.getValue(1));
11163     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11164                                Regs64bit ? X86::RCX : X86::ECX,
11165                                swapInH, swapInL.getValue(1));
11166     SDValue Ops[] = { swapInH.getValue(0),
11167                       N->getOperand(1),
11168                       swapInH.getValue(1) };
11169     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11170     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11171     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11172                                   X86ISD::LCMPXCHG8_DAG;
11173     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11174                                              Ops, 3, T, MMO);
11175     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11176                                         Regs64bit ? X86::RAX : X86::EAX,
11177                                         HalfT, Result.getValue(1));
11178     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11179                                         Regs64bit ? X86::RDX : X86::EDX,
11180                                         HalfT, cpOutL.getValue(2));
11181     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11182     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11183     Results.push_back(cpOutH.getValue(1));
11184     return;
11185   }
11186   case ISD::ATOMIC_LOAD_ADD:
11187     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11188     return;
11189   case ISD::ATOMIC_LOAD_AND:
11190     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11191     return;
11192   case ISD::ATOMIC_LOAD_NAND:
11193     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11194     return;
11195   case ISD::ATOMIC_LOAD_OR:
11196     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11197     return;
11198   case ISD::ATOMIC_LOAD_SUB:
11199     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11200     return;
11201   case ISD::ATOMIC_LOAD_XOR:
11202     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11203     return;
11204   case ISD::ATOMIC_SWAP:
11205     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11206     return;
11207   case ISD::ATOMIC_LOAD:
11208     ReplaceATOMIC_LOAD(N, Results, DAG);
11209   }
11210 }
11211
11212 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11213   switch (Opcode) {
11214   default: return NULL;
11215   case X86ISD::BSF:                return "X86ISD::BSF";
11216   case X86ISD::BSR:                return "X86ISD::BSR";
11217   case X86ISD::SHLD:               return "X86ISD::SHLD";
11218   case X86ISD::SHRD:               return "X86ISD::SHRD";
11219   case X86ISD::FAND:               return "X86ISD::FAND";
11220   case X86ISD::FOR:                return "X86ISD::FOR";
11221   case X86ISD::FXOR:               return "X86ISD::FXOR";
11222   case X86ISD::FSRL:               return "X86ISD::FSRL";
11223   case X86ISD::FILD:               return "X86ISD::FILD";
11224   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11225   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11226   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11227   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11228   case X86ISD::FLD:                return "X86ISD::FLD";
11229   case X86ISD::FST:                return "X86ISD::FST";
11230   case X86ISD::CALL:               return "X86ISD::CALL";
11231   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11232   case X86ISD::BT:                 return "X86ISD::BT";
11233   case X86ISD::CMP:                return "X86ISD::CMP";
11234   case X86ISD::COMI:               return "X86ISD::COMI";
11235   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11236   case X86ISD::SETCC:              return "X86ISD::SETCC";
11237   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11238   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11239   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11240   case X86ISD::CMOV:               return "X86ISD::CMOV";
11241   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11242   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11243   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11244   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11245   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11246   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11247   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11248   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11249   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11250   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11251   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11252   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11253   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11254   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11255   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11256   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11257   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11258   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11259   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11260   case X86ISD::HADD:               return "X86ISD::HADD";
11261   case X86ISD::HSUB:               return "X86ISD::HSUB";
11262   case X86ISD::FHADD:              return "X86ISD::FHADD";
11263   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11264   case X86ISD::FMAX:               return "X86ISD::FMAX";
11265   case X86ISD::FMIN:               return "X86ISD::FMIN";
11266   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11267   case X86ISD::FRCP:               return "X86ISD::FRCP";
11268   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11269   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11270   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11271   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11272   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11273   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11274   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11275   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11276   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11277   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11278   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11279   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11280   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11281   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11282   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11283   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11284   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11285   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11286   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11287   case X86ISD::VSHL:               return "X86ISD::VSHL";
11288   case X86ISD::VSRL:               return "X86ISD::VSRL";
11289   case X86ISD::VSRA:               return "X86ISD::VSRA";
11290   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11291   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11292   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11293   case X86ISD::CMPP:               return "X86ISD::CMPP";
11294   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11295   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11296   case X86ISD::ADD:                return "X86ISD::ADD";
11297   case X86ISD::SUB:                return "X86ISD::SUB";
11298   case X86ISD::ADC:                return "X86ISD::ADC";
11299   case X86ISD::SBB:                return "X86ISD::SBB";
11300   case X86ISD::SMUL:               return "X86ISD::SMUL";
11301   case X86ISD::UMUL:               return "X86ISD::UMUL";
11302   case X86ISD::INC:                return "X86ISD::INC";
11303   case X86ISD::DEC:                return "X86ISD::DEC";
11304   case X86ISD::OR:                 return "X86ISD::OR";
11305   case X86ISD::XOR:                return "X86ISD::XOR";
11306   case X86ISD::AND:                return "X86ISD::AND";
11307   case X86ISD::ANDN:               return "X86ISD::ANDN";
11308   case X86ISD::BLSI:               return "X86ISD::BLSI";
11309   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11310   case X86ISD::BLSR:               return "X86ISD::BLSR";
11311   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11312   case X86ISD::PTEST:              return "X86ISD::PTEST";
11313   case X86ISD::TESTP:              return "X86ISD::TESTP";
11314   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11315   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11316   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11317   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11318   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11319   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11320   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11321   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11322   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11323   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11324   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11325   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11326   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11327   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11328   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11329   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11330   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11331   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11332   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11333   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11334   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11335   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11336   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11337   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11338   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11339   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11340   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11341   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11342   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11343   case X86ISD::SAHF:               return "X86ISD::SAHF";
11344   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11345   case X86ISD::FMADD:              return "X86ISD::FMADD";
11346   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11347   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11348   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11349   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11350   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11351   }
11352 }
11353
11354 // isLegalAddressingMode - Return true if the addressing mode represented
11355 // by AM is legal for this target, for a load/store of the specified type.
11356 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11357                                               Type *Ty) const {
11358   // X86 supports extremely general addressing modes.
11359   CodeModel::Model M = getTargetMachine().getCodeModel();
11360   Reloc::Model R = getTargetMachine().getRelocationModel();
11361
11362   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11363   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11364     return false;
11365
11366   if (AM.BaseGV) {
11367     unsigned GVFlags =
11368       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11369
11370     // If a reference to this global requires an extra load, we can't fold it.
11371     if (isGlobalStubReference(GVFlags))
11372       return false;
11373
11374     // If BaseGV requires a register for the PIC base, we cannot also have a
11375     // BaseReg specified.
11376     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11377       return false;
11378
11379     // If lower 4G is not available, then we must use rip-relative addressing.
11380     if ((M != CodeModel::Small || R != Reloc::Static) &&
11381         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11382       return false;
11383   }
11384
11385   switch (AM.Scale) {
11386   case 0:
11387   case 1:
11388   case 2:
11389   case 4:
11390   case 8:
11391     // These scales always work.
11392     break;
11393   case 3:
11394   case 5:
11395   case 9:
11396     // These scales are formed with basereg+scalereg.  Only accept if there is
11397     // no basereg yet.
11398     if (AM.HasBaseReg)
11399       return false;
11400     break;
11401   default:  // Other stuff never works.
11402     return false;
11403   }
11404
11405   return true;
11406 }
11407
11408
11409 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11410   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11411     return false;
11412   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11413   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11414   if (NumBits1 <= NumBits2)
11415     return false;
11416   return true;
11417 }
11418
11419 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11420   return Imm == (int32_t)Imm;
11421 }
11422
11423 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11424   // Can also use sub to handle negated immediates.
11425   return Imm == (int32_t)Imm;
11426 }
11427
11428 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11429   if (!VT1.isInteger() || !VT2.isInteger())
11430     return false;
11431   unsigned NumBits1 = VT1.getSizeInBits();
11432   unsigned NumBits2 = VT2.getSizeInBits();
11433   if (NumBits1 <= NumBits2)
11434     return false;
11435   return true;
11436 }
11437
11438 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11439   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11440   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11441 }
11442
11443 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11444   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11445   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11446 }
11447
11448 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11449   // i16 instructions are longer (0x66 prefix) and potentially slower.
11450   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11451 }
11452
11453 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11454 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11455 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11456 /// are assumed to be legal.
11457 bool
11458 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11459                                       EVT VT) const {
11460   // Very little shuffling can be done for 64-bit vectors right now.
11461   if (VT.getSizeInBits() == 64)
11462     return false;
11463
11464   // FIXME: pshufb, blends, shifts.
11465   return (VT.getVectorNumElements() == 2 ||
11466           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11467           isMOVLMask(M, VT) ||
11468           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11469           isPSHUFDMask(M, VT) ||
11470           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11471           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11472           isPALIGNRMask(M, VT, Subtarget) ||
11473           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11474           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11475           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11476           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11477 }
11478
11479 bool
11480 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11481                                           EVT VT) const {
11482   unsigned NumElts = VT.getVectorNumElements();
11483   // FIXME: This collection of masks seems suspect.
11484   if (NumElts == 2)
11485     return true;
11486   if (NumElts == 4 && VT.is128BitVector()) {
11487     return (isMOVLMask(Mask, VT)  ||
11488             isCommutedMOVLMask(Mask, VT, true) ||
11489             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11490             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11491   }
11492   return false;
11493 }
11494
11495 //===----------------------------------------------------------------------===//
11496 //                           X86 Scheduler Hooks
11497 //===----------------------------------------------------------------------===//
11498
11499 // private utility function
11500 MachineBasicBlock *
11501 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11502                                                        MachineBasicBlock *MBB,
11503                                                        unsigned regOpc,
11504                                                        unsigned immOpc,
11505                                                        unsigned LoadOpc,
11506                                                        unsigned CXchgOpc,
11507                                                        unsigned notOpc,
11508                                                        unsigned EAXreg,
11509                                                  const TargetRegisterClass *RC,
11510                                                        bool Invert) const {
11511   // For the atomic bitwise operator, we generate
11512   //   thisMBB:
11513   //   newMBB:
11514   //     ld  t1 = [bitinstr.addr]
11515   //     op  t2 = t1, [bitinstr.val]
11516   //     not t3 = t2  (if Invert)
11517   //     mov EAX = t1
11518   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11519   //     bz  newMBB
11520   //     fallthrough -->nextMBB
11521   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11522   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11523   MachineFunction::iterator MBBIter = MBB;
11524   ++MBBIter;
11525
11526   /// First build the CFG
11527   MachineFunction *F = MBB->getParent();
11528   MachineBasicBlock *thisMBB = MBB;
11529   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11530   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11531   F->insert(MBBIter, newMBB);
11532   F->insert(MBBIter, nextMBB);
11533
11534   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11535   nextMBB->splice(nextMBB->begin(), thisMBB,
11536                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11537                   thisMBB->end());
11538   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11539
11540   // Update thisMBB to fall through to newMBB
11541   thisMBB->addSuccessor(newMBB);
11542
11543   // newMBB jumps to itself and fall through to nextMBB
11544   newMBB->addSuccessor(nextMBB);
11545   newMBB->addSuccessor(newMBB);
11546
11547   // Insert instructions into newMBB based on incoming instruction
11548   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11549          "unexpected number of operands");
11550   DebugLoc dl = bInstr->getDebugLoc();
11551   MachineOperand& destOper = bInstr->getOperand(0);
11552   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11553   int numArgs = bInstr->getNumOperands() - 1;
11554   for (int i=0; i < numArgs; ++i)
11555     argOpers[i] = &bInstr->getOperand(i+1);
11556
11557   // x86 address has 4 operands: base, index, scale, and displacement
11558   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11559   int valArgIndx = lastAddrIndx + 1;
11560
11561   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11562   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11563   for (int i=0; i <= lastAddrIndx; ++i)
11564     (*MIB).addOperand(*argOpers[i]);
11565
11566   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11567   assert((argOpers[valArgIndx]->isReg() ||
11568           argOpers[valArgIndx]->isImm()) &&
11569          "invalid operand");
11570   if (argOpers[valArgIndx]->isReg())
11571     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11572   else
11573     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11574   MIB.addReg(t1);
11575   (*MIB).addOperand(*argOpers[valArgIndx]);
11576
11577   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11578   if (Invert) {
11579     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11580   }
11581   else
11582     t3 = t2;
11583
11584   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11585   MIB.addReg(t1);
11586
11587   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11588   for (int i=0; i <= lastAddrIndx; ++i)
11589     (*MIB).addOperand(*argOpers[i]);
11590   MIB.addReg(t3);
11591   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11592   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11593                     bInstr->memoperands_end());
11594
11595   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11596   MIB.addReg(EAXreg);
11597
11598   // insert branch
11599   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11600
11601   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11602   return nextMBB;
11603 }
11604
11605 // private utility function:  64 bit atomics on 32 bit host.
11606 MachineBasicBlock *
11607 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11608                                                        MachineBasicBlock *MBB,
11609                                                        unsigned regOpcL,
11610                                                        unsigned regOpcH,
11611                                                        unsigned immOpcL,
11612                                                        unsigned immOpcH,
11613                                                        bool Invert) const {
11614   // For the atomic bitwise operator, we generate
11615   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11616   //     ld t1,t2 = [bitinstr.addr]
11617   //   newMBB:
11618   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11619   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11620   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11621   //     neg t7, t8 < t5, t6  (if Invert)
11622   //     mov ECX, EBX <- t5, t6
11623   //     mov EAX, EDX <- t1, t2
11624   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11625   //     mov t3, t4 <- EAX, EDX
11626   //     bz  newMBB
11627   //     result in out1, out2
11628   //     fallthrough -->nextMBB
11629
11630   const TargetRegisterClass *RC = &X86::GR32RegClass;
11631   const unsigned LoadOpc = X86::MOV32rm;
11632   const unsigned NotOpc = X86::NOT32r;
11633   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11634   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11635   MachineFunction::iterator MBBIter = MBB;
11636   ++MBBIter;
11637
11638   /// First build the CFG
11639   MachineFunction *F = MBB->getParent();
11640   MachineBasicBlock *thisMBB = MBB;
11641   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11642   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11643   F->insert(MBBIter, newMBB);
11644   F->insert(MBBIter, nextMBB);
11645
11646   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11647   nextMBB->splice(nextMBB->begin(), thisMBB,
11648                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11649                   thisMBB->end());
11650   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11651
11652   // Update thisMBB to fall through to newMBB
11653   thisMBB->addSuccessor(newMBB);
11654
11655   // newMBB jumps to itself and fall through to nextMBB
11656   newMBB->addSuccessor(nextMBB);
11657   newMBB->addSuccessor(newMBB);
11658
11659   DebugLoc dl = bInstr->getDebugLoc();
11660   // Insert instructions into newMBB based on incoming instruction
11661   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11662   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11663          "unexpected number of operands");
11664   MachineOperand& dest1Oper = bInstr->getOperand(0);
11665   MachineOperand& dest2Oper = bInstr->getOperand(1);
11666   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11667   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11668     argOpers[i] = &bInstr->getOperand(i+2);
11669
11670     // We use some of the operands multiple times, so conservatively just
11671     // clear any kill flags that might be present.
11672     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11673       argOpers[i]->setIsKill(false);
11674   }
11675
11676   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11677   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11678
11679   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11680   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11681   for (int i=0; i <= lastAddrIndx; ++i)
11682     (*MIB).addOperand(*argOpers[i]);
11683   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11684   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11685   // add 4 to displacement.
11686   for (int i=0; i <= lastAddrIndx-2; ++i)
11687     (*MIB).addOperand(*argOpers[i]);
11688   MachineOperand newOp3 = *(argOpers[3]);
11689   if (newOp3.isImm())
11690     newOp3.setImm(newOp3.getImm()+4);
11691   else
11692     newOp3.setOffset(newOp3.getOffset()+4);
11693   (*MIB).addOperand(newOp3);
11694   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11695
11696   // t3/4 are defined later, at the bottom of the loop
11697   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11698   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11699   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11700     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11701   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11702     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11703
11704   // The subsequent operations should be using the destination registers of
11705   // the PHI instructions.
11706   t1 = dest1Oper.getReg();
11707   t2 = dest2Oper.getReg();
11708
11709   int valArgIndx = lastAddrIndx + 1;
11710   assert((argOpers[valArgIndx]->isReg() ||
11711           argOpers[valArgIndx]->isImm()) &&
11712          "invalid operand");
11713   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11714   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11715   if (argOpers[valArgIndx]->isReg())
11716     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11717   else
11718     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11719   if (regOpcL != X86::MOV32rr)
11720     MIB.addReg(t1);
11721   (*MIB).addOperand(*argOpers[valArgIndx]);
11722   assert(argOpers[valArgIndx + 1]->isReg() ==
11723          argOpers[valArgIndx]->isReg());
11724   assert(argOpers[valArgIndx + 1]->isImm() ==
11725          argOpers[valArgIndx]->isImm());
11726   if (argOpers[valArgIndx + 1]->isReg())
11727     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11728   else
11729     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11730   if (regOpcH != X86::MOV32rr)
11731     MIB.addReg(t2);
11732   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11733
11734   unsigned t7, t8;
11735   if (Invert) {
11736     t7 = F->getRegInfo().createVirtualRegister(RC);
11737     t8 = F->getRegInfo().createVirtualRegister(RC);
11738     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11739     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11740   } else {
11741     t7 = t5;
11742     t8 = t6;
11743   }
11744
11745   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11746   MIB.addReg(t1);
11747   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11748   MIB.addReg(t2);
11749
11750   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11751   MIB.addReg(t7);
11752   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11753   MIB.addReg(t8);
11754
11755   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11756   for (int i=0; i <= lastAddrIndx; ++i)
11757     (*MIB).addOperand(*argOpers[i]);
11758
11759   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11760   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11761                     bInstr->memoperands_end());
11762
11763   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11764   MIB.addReg(X86::EAX);
11765   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11766   MIB.addReg(X86::EDX);
11767
11768   // insert branch
11769   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11770
11771   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11772   return nextMBB;
11773 }
11774
11775 // private utility function
11776 MachineBasicBlock *
11777 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11778                                                       MachineBasicBlock *MBB,
11779                                                       unsigned cmovOpc) const {
11780   // For the atomic min/max operator, we generate
11781   //   thisMBB:
11782   //   newMBB:
11783   //     ld t1 = [min/max.addr]
11784   //     mov t2 = [min/max.val]
11785   //     cmp  t1, t2
11786   //     cmov[cond] t2 = t1
11787   //     mov EAX = t1
11788   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11789   //     bz   newMBB
11790   //     fallthrough -->nextMBB
11791   //
11792   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11793   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11794   MachineFunction::iterator MBBIter = MBB;
11795   ++MBBIter;
11796
11797   /// First build the CFG
11798   MachineFunction *F = MBB->getParent();
11799   MachineBasicBlock *thisMBB = MBB;
11800   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11801   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11802   F->insert(MBBIter, newMBB);
11803   F->insert(MBBIter, nextMBB);
11804
11805   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11806   nextMBB->splice(nextMBB->begin(), thisMBB,
11807                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11808                   thisMBB->end());
11809   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11810
11811   // Update thisMBB to fall through to newMBB
11812   thisMBB->addSuccessor(newMBB);
11813
11814   // newMBB jumps to newMBB and fall through to nextMBB
11815   newMBB->addSuccessor(nextMBB);
11816   newMBB->addSuccessor(newMBB);
11817
11818   DebugLoc dl = mInstr->getDebugLoc();
11819   // Insert instructions into newMBB based on incoming instruction
11820   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11821          "unexpected number of operands");
11822   MachineOperand& destOper = mInstr->getOperand(0);
11823   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11824   int numArgs = mInstr->getNumOperands() - 1;
11825   for (int i=0; i < numArgs; ++i)
11826     argOpers[i] = &mInstr->getOperand(i+1);
11827
11828   // x86 address has 4 operands: base, index, scale, and displacement
11829   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11830   int valArgIndx = lastAddrIndx + 1;
11831
11832   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11833   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11834   for (int i=0; i <= lastAddrIndx; ++i)
11835     (*MIB).addOperand(*argOpers[i]);
11836
11837   // We only support register and immediate values
11838   assert((argOpers[valArgIndx]->isReg() ||
11839           argOpers[valArgIndx]->isImm()) &&
11840          "invalid operand");
11841
11842   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11843   if (argOpers[valArgIndx]->isReg())
11844     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11845   else
11846     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11847   (*MIB).addOperand(*argOpers[valArgIndx]);
11848
11849   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11850   MIB.addReg(t1);
11851
11852   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11853   MIB.addReg(t1);
11854   MIB.addReg(t2);
11855
11856   // Generate movc
11857   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11858   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11859   MIB.addReg(t2);
11860   MIB.addReg(t1);
11861
11862   // Cmp and exchange if none has modified the memory location
11863   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11864   for (int i=0; i <= lastAddrIndx; ++i)
11865     (*MIB).addOperand(*argOpers[i]);
11866   MIB.addReg(t3);
11867   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11868   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11869                     mInstr->memoperands_end());
11870
11871   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11872   MIB.addReg(X86::EAX);
11873
11874   // insert branch
11875   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11876
11877   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11878   return nextMBB;
11879 }
11880
11881 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11882 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11883 // in the .td file.
11884 MachineBasicBlock *
11885 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11886                             unsigned numArgs, bool memArg) const {
11887   assert(Subtarget->hasSSE42() &&
11888          "Target must have SSE4.2 or AVX features enabled");
11889
11890   DebugLoc dl = MI->getDebugLoc();
11891   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11892   unsigned Opc;
11893   if (!Subtarget->hasAVX()) {
11894     if (memArg)
11895       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11896     else
11897       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11898   } else {
11899     if (memArg)
11900       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11901     else
11902       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11903   }
11904
11905   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11906   for (unsigned i = 0; i < numArgs; ++i) {
11907     MachineOperand &Op = MI->getOperand(i+1);
11908     if (!(Op.isReg() && Op.isImplicit()))
11909       MIB.addOperand(Op);
11910   }
11911   BuildMI(*BB, MI, dl,
11912     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
11913     .addReg(X86::XMM0);
11914
11915   MI->eraseFromParent();
11916   return BB;
11917 }
11918
11919 MachineBasicBlock *
11920 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11921   DebugLoc dl = MI->getDebugLoc();
11922   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11923
11924   // Address into RAX/EAX, other two args into ECX, EDX.
11925   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11926   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11927   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11928   for (int i = 0; i < X86::AddrNumOperands; ++i)
11929     MIB.addOperand(MI->getOperand(i));
11930
11931   unsigned ValOps = X86::AddrNumOperands;
11932   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11933     .addReg(MI->getOperand(ValOps).getReg());
11934   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11935     .addReg(MI->getOperand(ValOps+1).getReg());
11936
11937   // The instruction doesn't actually take any operands though.
11938   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11939
11940   MI->eraseFromParent(); // The pseudo is gone now.
11941   return BB;
11942 }
11943
11944 MachineBasicBlock *
11945 X86TargetLowering::EmitVAARG64WithCustomInserter(
11946                    MachineInstr *MI,
11947                    MachineBasicBlock *MBB) const {
11948   // Emit va_arg instruction on X86-64.
11949
11950   // Operands to this pseudo-instruction:
11951   // 0  ) Output        : destination address (reg)
11952   // 1-5) Input         : va_list address (addr, i64mem)
11953   // 6  ) ArgSize       : Size (in bytes) of vararg type
11954   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11955   // 8  ) Align         : Alignment of type
11956   // 9  ) EFLAGS (implicit-def)
11957
11958   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11959   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11960
11961   unsigned DestReg = MI->getOperand(0).getReg();
11962   MachineOperand &Base = MI->getOperand(1);
11963   MachineOperand &Scale = MI->getOperand(2);
11964   MachineOperand &Index = MI->getOperand(3);
11965   MachineOperand &Disp = MI->getOperand(4);
11966   MachineOperand &Segment = MI->getOperand(5);
11967   unsigned ArgSize = MI->getOperand(6).getImm();
11968   unsigned ArgMode = MI->getOperand(7).getImm();
11969   unsigned Align = MI->getOperand(8).getImm();
11970
11971   // Memory Reference
11972   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11973   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11974   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11975
11976   // Machine Information
11977   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11978   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11979   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11980   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11981   DebugLoc DL = MI->getDebugLoc();
11982
11983   // struct va_list {
11984   //   i32   gp_offset
11985   //   i32   fp_offset
11986   //   i64   overflow_area (address)
11987   //   i64   reg_save_area (address)
11988   // }
11989   // sizeof(va_list) = 24
11990   // alignment(va_list) = 8
11991
11992   unsigned TotalNumIntRegs = 6;
11993   unsigned TotalNumXMMRegs = 8;
11994   bool UseGPOffset = (ArgMode == 1);
11995   bool UseFPOffset = (ArgMode == 2);
11996   unsigned MaxOffset = TotalNumIntRegs * 8 +
11997                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11998
11999   /* Align ArgSize to a multiple of 8 */
12000   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12001   bool NeedsAlign = (Align > 8);
12002
12003   MachineBasicBlock *thisMBB = MBB;
12004   MachineBasicBlock *overflowMBB;
12005   MachineBasicBlock *offsetMBB;
12006   MachineBasicBlock *endMBB;
12007
12008   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12009   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12010   unsigned OffsetReg = 0;
12011
12012   if (!UseGPOffset && !UseFPOffset) {
12013     // If we only pull from the overflow region, we don't create a branch.
12014     // We don't need to alter control flow.
12015     OffsetDestReg = 0; // unused
12016     OverflowDestReg = DestReg;
12017
12018     offsetMBB = NULL;
12019     overflowMBB = thisMBB;
12020     endMBB = thisMBB;
12021   } else {
12022     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12023     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12024     // If not, pull from overflow_area. (branch to overflowMBB)
12025     //
12026     //       thisMBB
12027     //         |     .
12028     //         |        .
12029     //     offsetMBB   overflowMBB
12030     //         |        .
12031     //         |     .
12032     //        endMBB
12033
12034     // Registers for the PHI in endMBB
12035     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12036     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12037
12038     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12039     MachineFunction *MF = MBB->getParent();
12040     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12041     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12042     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12043
12044     MachineFunction::iterator MBBIter = MBB;
12045     ++MBBIter;
12046
12047     // Insert the new basic blocks
12048     MF->insert(MBBIter, offsetMBB);
12049     MF->insert(MBBIter, overflowMBB);
12050     MF->insert(MBBIter, endMBB);
12051
12052     // Transfer the remainder of MBB and its successor edges to endMBB.
12053     endMBB->splice(endMBB->begin(), thisMBB,
12054                     llvm::next(MachineBasicBlock::iterator(MI)),
12055                     thisMBB->end());
12056     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12057
12058     // Make offsetMBB and overflowMBB successors of thisMBB
12059     thisMBB->addSuccessor(offsetMBB);
12060     thisMBB->addSuccessor(overflowMBB);
12061
12062     // endMBB is a successor of both offsetMBB and overflowMBB
12063     offsetMBB->addSuccessor(endMBB);
12064     overflowMBB->addSuccessor(endMBB);
12065
12066     // Load the offset value into a register
12067     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12068     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12069       .addOperand(Base)
12070       .addOperand(Scale)
12071       .addOperand(Index)
12072       .addDisp(Disp, UseFPOffset ? 4 : 0)
12073       .addOperand(Segment)
12074       .setMemRefs(MMOBegin, MMOEnd);
12075
12076     // Check if there is enough room left to pull this argument.
12077     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12078       .addReg(OffsetReg)
12079       .addImm(MaxOffset + 8 - ArgSizeA8);
12080
12081     // Branch to "overflowMBB" if offset >= max
12082     // Fall through to "offsetMBB" otherwise
12083     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12084       .addMBB(overflowMBB);
12085   }
12086
12087   // In offsetMBB, emit code to use the reg_save_area.
12088   if (offsetMBB) {
12089     assert(OffsetReg != 0);
12090
12091     // Read the reg_save_area address.
12092     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12093     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12094       .addOperand(Base)
12095       .addOperand(Scale)
12096       .addOperand(Index)
12097       .addDisp(Disp, 16)
12098       .addOperand(Segment)
12099       .setMemRefs(MMOBegin, MMOEnd);
12100
12101     // Zero-extend the offset
12102     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12103       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12104         .addImm(0)
12105         .addReg(OffsetReg)
12106         .addImm(X86::sub_32bit);
12107
12108     // Add the offset to the reg_save_area to get the final address.
12109     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12110       .addReg(OffsetReg64)
12111       .addReg(RegSaveReg);
12112
12113     // Compute the offset for the next argument
12114     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12115     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12116       .addReg(OffsetReg)
12117       .addImm(UseFPOffset ? 16 : 8);
12118
12119     // Store it back into the va_list.
12120     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12121       .addOperand(Base)
12122       .addOperand(Scale)
12123       .addOperand(Index)
12124       .addDisp(Disp, UseFPOffset ? 4 : 0)
12125       .addOperand(Segment)
12126       .addReg(NextOffsetReg)
12127       .setMemRefs(MMOBegin, MMOEnd);
12128
12129     // Jump to endMBB
12130     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12131       .addMBB(endMBB);
12132   }
12133
12134   //
12135   // Emit code to use overflow area
12136   //
12137
12138   // Load the overflow_area address into a register.
12139   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12140   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12141     .addOperand(Base)
12142     .addOperand(Scale)
12143     .addOperand(Index)
12144     .addDisp(Disp, 8)
12145     .addOperand(Segment)
12146     .setMemRefs(MMOBegin, MMOEnd);
12147
12148   // If we need to align it, do so. Otherwise, just copy the address
12149   // to OverflowDestReg.
12150   if (NeedsAlign) {
12151     // Align the overflow address
12152     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12153     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12154
12155     // aligned_addr = (addr + (align-1)) & ~(align-1)
12156     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12157       .addReg(OverflowAddrReg)
12158       .addImm(Align-1);
12159
12160     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12161       .addReg(TmpReg)
12162       .addImm(~(uint64_t)(Align-1));
12163   } else {
12164     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12165       .addReg(OverflowAddrReg);
12166   }
12167
12168   // Compute the next overflow address after this argument.
12169   // (the overflow address should be kept 8-byte aligned)
12170   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12171   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12172     .addReg(OverflowDestReg)
12173     .addImm(ArgSizeA8);
12174
12175   // Store the new overflow address.
12176   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12177     .addOperand(Base)
12178     .addOperand(Scale)
12179     .addOperand(Index)
12180     .addDisp(Disp, 8)
12181     .addOperand(Segment)
12182     .addReg(NextAddrReg)
12183     .setMemRefs(MMOBegin, MMOEnd);
12184
12185   // If we branched, emit the PHI to the front of endMBB.
12186   if (offsetMBB) {
12187     BuildMI(*endMBB, endMBB->begin(), DL,
12188             TII->get(X86::PHI), DestReg)
12189       .addReg(OffsetDestReg).addMBB(offsetMBB)
12190       .addReg(OverflowDestReg).addMBB(overflowMBB);
12191   }
12192
12193   // Erase the pseudo instruction
12194   MI->eraseFromParent();
12195
12196   return endMBB;
12197 }
12198
12199 MachineBasicBlock *
12200 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12201                                                  MachineInstr *MI,
12202                                                  MachineBasicBlock *MBB) const {
12203   // Emit code to save XMM registers to the stack. The ABI says that the
12204   // number of registers to save is given in %al, so it's theoretically
12205   // possible to do an indirect jump trick to avoid saving all of them,
12206   // however this code takes a simpler approach and just executes all
12207   // of the stores if %al is non-zero. It's less code, and it's probably
12208   // easier on the hardware branch predictor, and stores aren't all that
12209   // expensive anyway.
12210
12211   // Create the new basic blocks. One block contains all the XMM stores,
12212   // and one block is the final destination regardless of whether any
12213   // stores were performed.
12214   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12215   MachineFunction *F = MBB->getParent();
12216   MachineFunction::iterator MBBIter = MBB;
12217   ++MBBIter;
12218   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12219   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12220   F->insert(MBBIter, XMMSaveMBB);
12221   F->insert(MBBIter, EndMBB);
12222
12223   // Transfer the remainder of MBB and its successor edges to EndMBB.
12224   EndMBB->splice(EndMBB->begin(), MBB,
12225                  llvm::next(MachineBasicBlock::iterator(MI)),
12226                  MBB->end());
12227   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12228
12229   // The original block will now fall through to the XMM save block.
12230   MBB->addSuccessor(XMMSaveMBB);
12231   // The XMMSaveMBB will fall through to the end block.
12232   XMMSaveMBB->addSuccessor(EndMBB);
12233
12234   // Now add the instructions.
12235   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12236   DebugLoc DL = MI->getDebugLoc();
12237
12238   unsigned CountReg = MI->getOperand(0).getReg();
12239   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12240   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12241
12242   if (!Subtarget->isTargetWin64()) {
12243     // If %al is 0, branch around the XMM save block.
12244     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12245     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12246     MBB->addSuccessor(EndMBB);
12247   }
12248
12249   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12250   // In the XMM save block, save all the XMM argument registers.
12251   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12252     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12253     MachineMemOperand *MMO =
12254       F->getMachineMemOperand(
12255           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12256         MachineMemOperand::MOStore,
12257         /*Size=*/16, /*Align=*/16);
12258     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12259       .addFrameIndex(RegSaveFrameIndex)
12260       .addImm(/*Scale=*/1)
12261       .addReg(/*IndexReg=*/0)
12262       .addImm(/*Disp=*/Offset)
12263       .addReg(/*Segment=*/0)
12264       .addReg(MI->getOperand(i).getReg())
12265       .addMemOperand(MMO);
12266   }
12267
12268   MI->eraseFromParent();   // The pseudo instruction is gone now.
12269
12270   return EndMBB;
12271 }
12272
12273 // The EFLAGS operand of SelectItr might be missing a kill marker
12274 // because there were multiple uses of EFLAGS, and ISel didn't know
12275 // which to mark. Figure out whether SelectItr should have had a
12276 // kill marker, and set it if it should. Returns the correct kill
12277 // marker value.
12278 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12279                                      MachineBasicBlock* BB,
12280                                      const TargetRegisterInfo* TRI) {
12281   // Scan forward through BB for a use/def of EFLAGS.
12282   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12283   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12284     const MachineInstr& mi = *miI;
12285     if (mi.readsRegister(X86::EFLAGS))
12286       return false;
12287     if (mi.definesRegister(X86::EFLAGS))
12288       break; // Should have kill-flag - update below.
12289   }
12290
12291   // If we hit the end of the block, check whether EFLAGS is live into a
12292   // successor.
12293   if (miI == BB->end()) {
12294     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12295                                           sEnd = BB->succ_end();
12296          sItr != sEnd; ++sItr) {
12297       MachineBasicBlock* succ = *sItr;
12298       if (succ->isLiveIn(X86::EFLAGS))
12299         return false;
12300     }
12301   }
12302
12303   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12304   // out. SelectMI should have a kill flag on EFLAGS.
12305   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12306   return true;
12307 }
12308
12309 MachineBasicBlock *
12310 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12311                                      MachineBasicBlock *BB) const {
12312   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12313   DebugLoc DL = MI->getDebugLoc();
12314
12315   // To "insert" a SELECT_CC instruction, we actually have to insert the
12316   // diamond control-flow pattern.  The incoming instruction knows the
12317   // destination vreg to set, the condition code register to branch on, the
12318   // true/false values to select between, and a branch opcode to use.
12319   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12320   MachineFunction::iterator It = BB;
12321   ++It;
12322
12323   //  thisMBB:
12324   //  ...
12325   //   TrueVal = ...
12326   //   cmpTY ccX, r1, r2
12327   //   bCC copy1MBB
12328   //   fallthrough --> copy0MBB
12329   MachineBasicBlock *thisMBB = BB;
12330   MachineFunction *F = BB->getParent();
12331   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12332   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12333   F->insert(It, copy0MBB);
12334   F->insert(It, sinkMBB);
12335
12336   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12337   // live into the sink and copy blocks.
12338   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12339   if (!MI->killsRegister(X86::EFLAGS) &&
12340       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12341     copy0MBB->addLiveIn(X86::EFLAGS);
12342     sinkMBB->addLiveIn(X86::EFLAGS);
12343   }
12344
12345   // Transfer the remainder of BB and its successor edges to sinkMBB.
12346   sinkMBB->splice(sinkMBB->begin(), BB,
12347                   llvm::next(MachineBasicBlock::iterator(MI)),
12348                   BB->end());
12349   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12350
12351   // Add the true and fallthrough blocks as its successors.
12352   BB->addSuccessor(copy0MBB);
12353   BB->addSuccessor(sinkMBB);
12354
12355   // Create the conditional branch instruction.
12356   unsigned Opc =
12357     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12358   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12359
12360   //  copy0MBB:
12361   //   %FalseValue = ...
12362   //   # fallthrough to sinkMBB
12363   copy0MBB->addSuccessor(sinkMBB);
12364
12365   //  sinkMBB:
12366   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12367   //  ...
12368   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12369           TII->get(X86::PHI), MI->getOperand(0).getReg())
12370     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12371     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12372
12373   MI->eraseFromParent();   // The pseudo instruction is gone now.
12374   return sinkMBB;
12375 }
12376
12377 MachineBasicBlock *
12378 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12379                                         bool Is64Bit) const {
12380   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12381   DebugLoc DL = MI->getDebugLoc();
12382   MachineFunction *MF = BB->getParent();
12383   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12384
12385   assert(getTargetMachine().Options.EnableSegmentedStacks);
12386
12387   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12388   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12389
12390   // BB:
12391   //  ... [Till the alloca]
12392   // If stacklet is not large enough, jump to mallocMBB
12393   //
12394   // bumpMBB:
12395   //  Allocate by subtracting from RSP
12396   //  Jump to continueMBB
12397   //
12398   // mallocMBB:
12399   //  Allocate by call to runtime
12400   //
12401   // continueMBB:
12402   //  ...
12403   //  [rest of original BB]
12404   //
12405
12406   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12407   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12408   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12409
12410   MachineRegisterInfo &MRI = MF->getRegInfo();
12411   const TargetRegisterClass *AddrRegClass =
12412     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12413
12414   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12415     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12416     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12417     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12418     sizeVReg = MI->getOperand(1).getReg(),
12419     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12420
12421   MachineFunction::iterator MBBIter = BB;
12422   ++MBBIter;
12423
12424   MF->insert(MBBIter, bumpMBB);
12425   MF->insert(MBBIter, mallocMBB);
12426   MF->insert(MBBIter, continueMBB);
12427
12428   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12429                       (MachineBasicBlock::iterator(MI)), BB->end());
12430   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12431
12432   // Add code to the main basic block to check if the stack limit has been hit,
12433   // and if so, jump to mallocMBB otherwise to bumpMBB.
12434   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12435   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12436     .addReg(tmpSPVReg).addReg(sizeVReg);
12437   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12438     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12439     .addReg(SPLimitVReg);
12440   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12441
12442   // bumpMBB simply decreases the stack pointer, since we know the current
12443   // stacklet has enough space.
12444   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12445     .addReg(SPLimitVReg);
12446   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12447     .addReg(SPLimitVReg);
12448   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12449
12450   // Calls into a routine in libgcc to allocate more space from the heap.
12451   const uint32_t *RegMask =
12452     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12453   if (Is64Bit) {
12454     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12455       .addReg(sizeVReg);
12456     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12457       .addExternalSymbol("__morestack_allocate_stack_space")
12458       .addRegMask(RegMask)
12459       .addReg(X86::RDI, RegState::Implicit)
12460       .addReg(X86::RAX, RegState::ImplicitDefine);
12461   } else {
12462     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12463       .addImm(12);
12464     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12465     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12466       .addExternalSymbol("__morestack_allocate_stack_space")
12467       .addRegMask(RegMask)
12468       .addReg(X86::EAX, RegState::ImplicitDefine);
12469   }
12470
12471   if (!Is64Bit)
12472     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12473       .addImm(16);
12474
12475   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12476     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12477   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12478
12479   // Set up the CFG correctly.
12480   BB->addSuccessor(bumpMBB);
12481   BB->addSuccessor(mallocMBB);
12482   mallocMBB->addSuccessor(continueMBB);
12483   bumpMBB->addSuccessor(continueMBB);
12484
12485   // Take care of the PHI nodes.
12486   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12487           MI->getOperand(0).getReg())
12488     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12489     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12490
12491   // Delete the original pseudo instruction.
12492   MI->eraseFromParent();
12493
12494   // And we're done.
12495   return continueMBB;
12496 }
12497
12498 MachineBasicBlock *
12499 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12500                                           MachineBasicBlock *BB) const {
12501   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12502   DebugLoc DL = MI->getDebugLoc();
12503
12504   assert(!Subtarget->isTargetEnvMacho());
12505
12506   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12507   // non-trivial part is impdef of ESP.
12508
12509   if (Subtarget->isTargetWin64()) {
12510     if (Subtarget->isTargetCygMing()) {
12511       // ___chkstk(Mingw64):
12512       // Clobbers R10, R11, RAX and EFLAGS.
12513       // Updates RSP.
12514       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12515         .addExternalSymbol("___chkstk")
12516         .addReg(X86::RAX, RegState::Implicit)
12517         .addReg(X86::RSP, RegState::Implicit)
12518         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12519         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12520         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12521     } else {
12522       // __chkstk(MSVCRT): does not update stack pointer.
12523       // Clobbers R10, R11 and EFLAGS.
12524       // FIXME: RAX(allocated size) might be reused and not killed.
12525       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12526         .addExternalSymbol("__chkstk")
12527         .addReg(X86::RAX, RegState::Implicit)
12528         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12529       // RAX has the offset to subtracted from RSP.
12530       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12531         .addReg(X86::RSP)
12532         .addReg(X86::RAX);
12533     }
12534   } else {
12535     const char *StackProbeSymbol =
12536       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12537
12538     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12539       .addExternalSymbol(StackProbeSymbol)
12540       .addReg(X86::EAX, RegState::Implicit)
12541       .addReg(X86::ESP, RegState::Implicit)
12542       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12543       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12544       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12545   }
12546
12547   MI->eraseFromParent();   // The pseudo instruction is gone now.
12548   return BB;
12549 }
12550
12551 MachineBasicBlock *
12552 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12553                                       MachineBasicBlock *BB) const {
12554   // This is pretty easy.  We're taking the value that we received from
12555   // our load from the relocation, sticking it in either RDI (x86-64)
12556   // or EAX and doing an indirect call.  The return value will then
12557   // be in the normal return register.
12558   const X86InstrInfo *TII
12559     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12560   DebugLoc DL = MI->getDebugLoc();
12561   MachineFunction *F = BB->getParent();
12562
12563   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12564   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12565
12566   // Get a register mask for the lowered call.
12567   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12568   // proper register mask.
12569   const uint32_t *RegMask =
12570     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12571   if (Subtarget->is64Bit()) {
12572     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12573                                       TII->get(X86::MOV64rm), X86::RDI)
12574     .addReg(X86::RIP)
12575     .addImm(0).addReg(0)
12576     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12577                       MI->getOperand(3).getTargetFlags())
12578     .addReg(0);
12579     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12580     addDirectMem(MIB, X86::RDI);
12581     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12582   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12583     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12584                                       TII->get(X86::MOV32rm), X86::EAX)
12585     .addReg(0)
12586     .addImm(0).addReg(0)
12587     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12588                       MI->getOperand(3).getTargetFlags())
12589     .addReg(0);
12590     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12591     addDirectMem(MIB, X86::EAX);
12592     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12593   } else {
12594     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12595                                       TII->get(X86::MOV32rm), X86::EAX)
12596     .addReg(TII->getGlobalBaseReg(F))
12597     .addImm(0).addReg(0)
12598     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12599                       MI->getOperand(3).getTargetFlags())
12600     .addReg(0);
12601     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12602     addDirectMem(MIB, X86::EAX);
12603     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12604   }
12605
12606   MI->eraseFromParent(); // The pseudo instruction is gone now.
12607   return BB;
12608 }
12609
12610 MachineBasicBlock *
12611 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12612                                                MachineBasicBlock *BB) const {
12613   switch (MI->getOpcode()) {
12614   default: llvm_unreachable("Unexpected instr type to insert");
12615   case X86::TAILJMPd64:
12616   case X86::TAILJMPr64:
12617   case X86::TAILJMPm64:
12618     llvm_unreachable("TAILJMP64 would not be touched here.");
12619   case X86::TCRETURNdi64:
12620   case X86::TCRETURNri64:
12621   case X86::TCRETURNmi64:
12622     return BB;
12623   case X86::WIN_ALLOCA:
12624     return EmitLoweredWinAlloca(MI, BB);
12625   case X86::SEG_ALLOCA_32:
12626     return EmitLoweredSegAlloca(MI, BB, false);
12627   case X86::SEG_ALLOCA_64:
12628     return EmitLoweredSegAlloca(MI, BB, true);
12629   case X86::TLSCall_32:
12630   case X86::TLSCall_64:
12631     return EmitLoweredTLSCall(MI, BB);
12632   case X86::CMOV_GR8:
12633   case X86::CMOV_FR32:
12634   case X86::CMOV_FR64:
12635   case X86::CMOV_V4F32:
12636   case X86::CMOV_V2F64:
12637   case X86::CMOV_V2I64:
12638   case X86::CMOV_V8F32:
12639   case X86::CMOV_V4F64:
12640   case X86::CMOV_V4I64:
12641   case X86::CMOV_GR16:
12642   case X86::CMOV_GR32:
12643   case X86::CMOV_RFP32:
12644   case X86::CMOV_RFP64:
12645   case X86::CMOV_RFP80:
12646     return EmitLoweredSelect(MI, BB);
12647
12648   case X86::FP32_TO_INT16_IN_MEM:
12649   case X86::FP32_TO_INT32_IN_MEM:
12650   case X86::FP32_TO_INT64_IN_MEM:
12651   case X86::FP64_TO_INT16_IN_MEM:
12652   case X86::FP64_TO_INT32_IN_MEM:
12653   case X86::FP64_TO_INT64_IN_MEM:
12654   case X86::FP80_TO_INT16_IN_MEM:
12655   case X86::FP80_TO_INT32_IN_MEM:
12656   case X86::FP80_TO_INT64_IN_MEM: {
12657     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12658     DebugLoc DL = MI->getDebugLoc();
12659
12660     // Change the floating point control register to use "round towards zero"
12661     // mode when truncating to an integer value.
12662     MachineFunction *F = BB->getParent();
12663     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12664     addFrameReference(BuildMI(*BB, MI, DL,
12665                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12666
12667     // Load the old value of the high byte of the control word...
12668     unsigned OldCW =
12669       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12670     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12671                       CWFrameIdx);
12672
12673     // Set the high part to be round to zero...
12674     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12675       .addImm(0xC7F);
12676
12677     // Reload the modified control word now...
12678     addFrameReference(BuildMI(*BB, MI, DL,
12679                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12680
12681     // Restore the memory image of control word to original value
12682     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12683       .addReg(OldCW);
12684
12685     // Get the X86 opcode to use.
12686     unsigned Opc;
12687     switch (MI->getOpcode()) {
12688     default: llvm_unreachable("illegal opcode!");
12689     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12690     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12691     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12692     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12693     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12694     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12695     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12696     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12697     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12698     }
12699
12700     X86AddressMode AM;
12701     MachineOperand &Op = MI->getOperand(0);
12702     if (Op.isReg()) {
12703       AM.BaseType = X86AddressMode::RegBase;
12704       AM.Base.Reg = Op.getReg();
12705     } else {
12706       AM.BaseType = X86AddressMode::FrameIndexBase;
12707       AM.Base.FrameIndex = Op.getIndex();
12708     }
12709     Op = MI->getOperand(1);
12710     if (Op.isImm())
12711       AM.Scale = Op.getImm();
12712     Op = MI->getOperand(2);
12713     if (Op.isImm())
12714       AM.IndexReg = Op.getImm();
12715     Op = MI->getOperand(3);
12716     if (Op.isGlobal()) {
12717       AM.GV = Op.getGlobal();
12718     } else {
12719       AM.Disp = Op.getImm();
12720     }
12721     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12722                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12723
12724     // Reload the original control word now.
12725     addFrameReference(BuildMI(*BB, MI, DL,
12726                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12727
12728     MI->eraseFromParent();   // The pseudo instruction is gone now.
12729     return BB;
12730   }
12731     // String/text processing lowering.
12732   case X86::PCMPISTRM128REG:
12733   case X86::VPCMPISTRM128REG:
12734     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12735   case X86::PCMPISTRM128MEM:
12736   case X86::VPCMPISTRM128MEM:
12737     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12738   case X86::PCMPESTRM128REG:
12739   case X86::VPCMPESTRM128REG:
12740     return EmitPCMP(MI, BB, 5, false /* in mem */);
12741   case X86::PCMPESTRM128MEM:
12742   case X86::VPCMPESTRM128MEM:
12743     return EmitPCMP(MI, BB, 5, true /* in mem */);
12744
12745     // Thread synchronization.
12746   case X86::MONITOR:
12747     return EmitMonitor(MI, BB);
12748
12749     // Atomic Lowering.
12750   case X86::ATOMAND32:
12751     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12752                                                X86::AND32ri, X86::MOV32rm,
12753                                                X86::LCMPXCHG32,
12754                                                X86::NOT32r, X86::EAX,
12755                                                &X86::GR32RegClass);
12756   case X86::ATOMOR32:
12757     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12758                                                X86::OR32ri, X86::MOV32rm,
12759                                                X86::LCMPXCHG32,
12760                                                X86::NOT32r, X86::EAX,
12761                                                &X86::GR32RegClass);
12762   case X86::ATOMXOR32:
12763     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12764                                                X86::XOR32ri, X86::MOV32rm,
12765                                                X86::LCMPXCHG32,
12766                                                X86::NOT32r, X86::EAX,
12767                                                &X86::GR32RegClass);
12768   case X86::ATOMNAND32:
12769     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12770                                                X86::AND32ri, X86::MOV32rm,
12771                                                X86::LCMPXCHG32,
12772                                                X86::NOT32r, X86::EAX,
12773                                                &X86::GR32RegClass, true);
12774   case X86::ATOMMIN32:
12775     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12776   case X86::ATOMMAX32:
12777     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12778   case X86::ATOMUMIN32:
12779     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12780   case X86::ATOMUMAX32:
12781     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12782
12783   case X86::ATOMAND16:
12784     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12785                                                X86::AND16ri, X86::MOV16rm,
12786                                                X86::LCMPXCHG16,
12787                                                X86::NOT16r, X86::AX,
12788                                                &X86::GR16RegClass);
12789   case X86::ATOMOR16:
12790     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12791                                                X86::OR16ri, X86::MOV16rm,
12792                                                X86::LCMPXCHG16,
12793                                                X86::NOT16r, X86::AX,
12794                                                &X86::GR16RegClass);
12795   case X86::ATOMXOR16:
12796     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12797                                                X86::XOR16ri, X86::MOV16rm,
12798                                                X86::LCMPXCHG16,
12799                                                X86::NOT16r, X86::AX,
12800                                                &X86::GR16RegClass);
12801   case X86::ATOMNAND16:
12802     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12803                                                X86::AND16ri, X86::MOV16rm,
12804                                                X86::LCMPXCHG16,
12805                                                X86::NOT16r, X86::AX,
12806                                                &X86::GR16RegClass, true);
12807   case X86::ATOMMIN16:
12808     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12809   case X86::ATOMMAX16:
12810     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12811   case X86::ATOMUMIN16:
12812     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12813   case X86::ATOMUMAX16:
12814     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12815
12816   case X86::ATOMAND8:
12817     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12818                                                X86::AND8ri, X86::MOV8rm,
12819                                                X86::LCMPXCHG8,
12820                                                X86::NOT8r, X86::AL,
12821                                                &X86::GR8RegClass);
12822   case X86::ATOMOR8:
12823     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12824                                                X86::OR8ri, X86::MOV8rm,
12825                                                X86::LCMPXCHG8,
12826                                                X86::NOT8r, X86::AL,
12827                                                &X86::GR8RegClass);
12828   case X86::ATOMXOR8:
12829     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12830                                                X86::XOR8ri, X86::MOV8rm,
12831                                                X86::LCMPXCHG8,
12832                                                X86::NOT8r, X86::AL,
12833                                                &X86::GR8RegClass);
12834   case X86::ATOMNAND8:
12835     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12836                                                X86::AND8ri, X86::MOV8rm,
12837                                                X86::LCMPXCHG8,
12838                                                X86::NOT8r, X86::AL,
12839                                                &X86::GR8RegClass, true);
12840   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12841   // This group is for 64-bit host.
12842   case X86::ATOMAND64:
12843     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12844                                                X86::AND64ri32, X86::MOV64rm,
12845                                                X86::LCMPXCHG64,
12846                                                X86::NOT64r, X86::RAX,
12847                                                &X86::GR64RegClass);
12848   case X86::ATOMOR64:
12849     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12850                                                X86::OR64ri32, X86::MOV64rm,
12851                                                X86::LCMPXCHG64,
12852                                                X86::NOT64r, X86::RAX,
12853                                                &X86::GR64RegClass);
12854   case X86::ATOMXOR64:
12855     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12856                                                X86::XOR64ri32, X86::MOV64rm,
12857                                                X86::LCMPXCHG64,
12858                                                X86::NOT64r, X86::RAX,
12859                                                &X86::GR64RegClass);
12860   case X86::ATOMNAND64:
12861     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12862                                                X86::AND64ri32, X86::MOV64rm,
12863                                                X86::LCMPXCHG64,
12864                                                X86::NOT64r, X86::RAX,
12865                                                &X86::GR64RegClass, true);
12866   case X86::ATOMMIN64:
12867     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12868   case X86::ATOMMAX64:
12869     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12870   case X86::ATOMUMIN64:
12871     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12872   case X86::ATOMUMAX64:
12873     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12874
12875   // This group does 64-bit operations on a 32-bit host.
12876   case X86::ATOMAND6432:
12877     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12878                                                X86::AND32rr, X86::AND32rr,
12879                                                X86::AND32ri, X86::AND32ri,
12880                                                false);
12881   case X86::ATOMOR6432:
12882     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12883                                                X86::OR32rr, X86::OR32rr,
12884                                                X86::OR32ri, X86::OR32ri,
12885                                                false);
12886   case X86::ATOMXOR6432:
12887     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12888                                                X86::XOR32rr, X86::XOR32rr,
12889                                                X86::XOR32ri, X86::XOR32ri,
12890                                                false);
12891   case X86::ATOMNAND6432:
12892     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12893                                                X86::AND32rr, X86::AND32rr,
12894                                                X86::AND32ri, X86::AND32ri,
12895                                                true);
12896   case X86::ATOMADD6432:
12897     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12898                                                X86::ADD32rr, X86::ADC32rr,
12899                                                X86::ADD32ri, X86::ADC32ri,
12900                                                false);
12901   case X86::ATOMSUB6432:
12902     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12903                                                X86::SUB32rr, X86::SBB32rr,
12904                                                X86::SUB32ri, X86::SBB32ri,
12905                                                false);
12906   case X86::ATOMSWAP6432:
12907     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12908                                                X86::MOV32rr, X86::MOV32rr,
12909                                                X86::MOV32ri, X86::MOV32ri,
12910                                                false);
12911   case X86::VASTART_SAVE_XMM_REGS:
12912     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12913
12914   case X86::VAARG_64:
12915     return EmitVAARG64WithCustomInserter(MI, BB);
12916   }
12917 }
12918
12919 //===----------------------------------------------------------------------===//
12920 //                           X86 Optimization Hooks
12921 //===----------------------------------------------------------------------===//
12922
12923 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12924                                                        APInt &KnownZero,
12925                                                        APInt &KnownOne,
12926                                                        const SelectionDAG &DAG,
12927                                                        unsigned Depth) const {
12928   unsigned BitWidth = KnownZero.getBitWidth();
12929   unsigned Opc = Op.getOpcode();
12930   assert((Opc >= ISD::BUILTIN_OP_END ||
12931           Opc == ISD::INTRINSIC_WO_CHAIN ||
12932           Opc == ISD::INTRINSIC_W_CHAIN ||
12933           Opc == ISD::INTRINSIC_VOID) &&
12934          "Should use MaskedValueIsZero if you don't know whether Op"
12935          " is a target node!");
12936
12937   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
12938   switch (Opc) {
12939   default: break;
12940   case X86ISD::ADD:
12941   case X86ISD::SUB:
12942   case X86ISD::ADC:
12943   case X86ISD::SBB:
12944   case X86ISD::SMUL:
12945   case X86ISD::UMUL:
12946   case X86ISD::INC:
12947   case X86ISD::DEC:
12948   case X86ISD::OR:
12949   case X86ISD::XOR:
12950   case X86ISD::AND:
12951     // These nodes' second result is a boolean.
12952     if (Op.getResNo() == 0)
12953       break;
12954     // Fallthrough
12955   case X86ISD::SETCC:
12956     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12957     break;
12958   case ISD::INTRINSIC_WO_CHAIN: {
12959     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12960     unsigned NumLoBits = 0;
12961     switch (IntId) {
12962     default: break;
12963     case Intrinsic::x86_sse_movmsk_ps:
12964     case Intrinsic::x86_avx_movmsk_ps_256:
12965     case Intrinsic::x86_sse2_movmsk_pd:
12966     case Intrinsic::x86_avx_movmsk_pd_256:
12967     case Intrinsic::x86_mmx_pmovmskb:
12968     case Intrinsic::x86_sse2_pmovmskb_128:
12969     case Intrinsic::x86_avx2_pmovmskb: {
12970       // High bits of movmskp{s|d}, pmovmskb are known zero.
12971       switch (IntId) {
12972         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12973         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12974         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12975         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12976         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12977         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12978         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12979         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
12980       }
12981       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
12982       break;
12983     }
12984     }
12985     break;
12986   }
12987   }
12988 }
12989
12990 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12991                                                          unsigned Depth) const {
12992   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12993   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12994     return Op.getValueType().getScalarType().getSizeInBits();
12995
12996   // Fallback case.
12997   return 1;
12998 }
12999
13000 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13001 /// node is a GlobalAddress + offset.
13002 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13003                                        const GlobalValue* &GA,
13004                                        int64_t &Offset) const {
13005   if (N->getOpcode() == X86ISD::Wrapper) {
13006     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13007       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13008       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13009       return true;
13010     }
13011   }
13012   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13013 }
13014
13015 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13016 /// same as extracting the high 128-bit part of 256-bit vector and then
13017 /// inserting the result into the low part of a new 256-bit vector
13018 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13019   EVT VT = SVOp->getValueType(0);
13020   unsigned NumElems = VT.getVectorNumElements();
13021
13022   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13023   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13024     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13025         SVOp->getMaskElt(j) >= 0)
13026       return false;
13027
13028   return true;
13029 }
13030
13031 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13032 /// same as extracting the low 128-bit part of 256-bit vector and then
13033 /// inserting the result into the high part of a new 256-bit vector
13034 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13035   EVT VT = SVOp->getValueType(0);
13036   unsigned NumElems = VT.getVectorNumElements();
13037
13038   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13039   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13040     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13041         SVOp->getMaskElt(j) >= 0)
13042       return false;
13043
13044   return true;
13045 }
13046
13047 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13048 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13049                                         TargetLowering::DAGCombinerInfo &DCI,
13050                                         const X86Subtarget* Subtarget) {
13051   DebugLoc dl = N->getDebugLoc();
13052   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13053   SDValue V1 = SVOp->getOperand(0);
13054   SDValue V2 = SVOp->getOperand(1);
13055   EVT VT = SVOp->getValueType(0);
13056   unsigned NumElems = VT.getVectorNumElements();
13057
13058   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13059       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13060     //
13061     //                   0,0,0,...
13062     //                      |
13063     //    V      UNDEF    BUILD_VECTOR    UNDEF
13064     //     \      /           \           /
13065     //  CONCAT_VECTOR         CONCAT_VECTOR
13066     //         \                  /
13067     //          \                /
13068     //          RESULT: V + zero extended
13069     //
13070     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13071         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13072         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13073       return SDValue();
13074
13075     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13076       return SDValue();
13077
13078     // To match the shuffle mask, the first half of the mask should
13079     // be exactly the first vector, and all the rest a splat with the
13080     // first element of the second one.
13081     for (unsigned i = 0; i != NumElems/2; ++i)
13082       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13083           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13084         return SDValue();
13085
13086     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13087     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13088       if (Ld->hasNUsesOfValue(1, 0)) {
13089         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13090         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13091         SDValue ResNode =
13092           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13093                                   Ld->getMemoryVT(),
13094                                   Ld->getPointerInfo(),
13095                                   Ld->getAlignment(),
13096                                   false/*isVolatile*/, true/*ReadMem*/,
13097                                   false/*WriteMem*/);
13098         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13099       }
13100     }
13101
13102     // Emit a zeroed vector and insert the desired subvector on its
13103     // first half.
13104     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13105     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13106     return DCI.CombineTo(N, InsV);
13107   }
13108
13109   //===--------------------------------------------------------------------===//
13110   // Combine some shuffles into subvector extracts and inserts:
13111   //
13112
13113   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13114   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13115     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13116     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13117     return DCI.CombineTo(N, InsV);
13118   }
13119
13120   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13121   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13122     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13123     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13124     return DCI.CombineTo(N, InsV);
13125   }
13126
13127   return SDValue();
13128 }
13129
13130 /// PerformShuffleCombine - Performs several different shuffle combines.
13131 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13132                                      TargetLowering::DAGCombinerInfo &DCI,
13133                                      const X86Subtarget *Subtarget) {
13134   DebugLoc dl = N->getDebugLoc();
13135   EVT VT = N->getValueType(0);
13136
13137   // Don't create instructions with illegal types after legalize types has run.
13138   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13139   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13140     return SDValue();
13141
13142   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13143   if (Subtarget->hasAVX() && VT.is256BitVector() &&
13144       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13145     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13146
13147   // Only handle 128 wide vector from here on.
13148   if (!VT.is128BitVector())
13149     return SDValue();
13150
13151   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13152   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13153   // consecutive, non-overlapping, and in the right order.
13154   SmallVector<SDValue, 16> Elts;
13155   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13156     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13157
13158   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13159 }
13160
13161
13162 /// DCI, PerformTruncateCombine - Converts truncate operation to
13163 /// a sequence of vector shuffle operations.
13164 /// It is possible when we truncate 256-bit vector to 128-bit vector
13165
13166 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13167                                                   DAGCombinerInfo &DCI) const {
13168   if (!DCI.isBeforeLegalizeOps())
13169     return SDValue();
13170
13171   if (!Subtarget->hasAVX())
13172     return SDValue();
13173
13174   EVT VT = N->getValueType(0);
13175   SDValue Op = N->getOperand(0);
13176   EVT OpVT = Op.getValueType();
13177   DebugLoc dl = N->getDebugLoc();
13178
13179   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13180
13181     if (Subtarget->hasAVX2()) {
13182       // AVX2: v4i64 -> v4i32
13183
13184       // VPERMD
13185       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13186
13187       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13188       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13189                                 ShufMask);
13190
13191       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13192                          DAG.getIntPtrConstant(0));
13193     }
13194
13195     // AVX: v4i64 -> v4i32
13196     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13197                                DAG.getIntPtrConstant(0));
13198
13199     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13200                                DAG.getIntPtrConstant(2));
13201
13202     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13203     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13204
13205     // PSHUFD
13206     static const int ShufMask1[] = {0, 2, 0, 0};
13207
13208     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13209     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13210
13211     // MOVLHPS
13212     static const int ShufMask2[] = {0, 1, 4, 5};
13213
13214     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13215   }
13216
13217   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13218
13219     if (Subtarget->hasAVX2()) {
13220       // AVX2: v8i32 -> v8i16
13221
13222       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13223
13224       // PSHUFB
13225       SmallVector<SDValue,32> pshufbMask;
13226       for (unsigned i = 0; i < 2; ++i) {
13227         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13228         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13229         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13230         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13231         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13232         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13233         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13234         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13235         for (unsigned j = 0; j < 8; ++j)
13236           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13237       }
13238       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13239                                &pshufbMask[0], 32);
13240       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13241
13242       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13243
13244       static const int ShufMask[] = {0,  2,  -1,  -1};
13245       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13246                                 &ShufMask[0]);
13247
13248       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13249                        DAG.getIntPtrConstant(0));
13250
13251       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13252     }
13253
13254     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13255                                DAG.getIntPtrConstant(0));
13256
13257     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13258                                DAG.getIntPtrConstant(4));
13259
13260     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13261     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13262
13263     // PSHUFB
13264     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13265                                    -1, -1, -1, -1, -1, -1, -1, -1};
13266
13267     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13268                                 ShufMask1);
13269     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13270                                 ShufMask1);
13271
13272     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13273     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13274
13275     // MOVLHPS
13276     static const int ShufMask2[] = {0, 1, 4, 5};
13277
13278     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13279     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13280   }
13281
13282   return SDValue();
13283 }
13284
13285 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13286 /// specific shuffle of a load can be folded into a single element load.
13287 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13288 /// shuffles have been customed lowered so we need to handle those here.
13289 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13290                                          TargetLowering::DAGCombinerInfo &DCI) {
13291   if (DCI.isBeforeLegalizeOps())
13292     return SDValue();
13293
13294   SDValue InVec = N->getOperand(0);
13295   SDValue EltNo = N->getOperand(1);
13296
13297   if (!isa<ConstantSDNode>(EltNo))
13298     return SDValue();
13299
13300   EVT VT = InVec.getValueType();
13301
13302   bool HasShuffleIntoBitcast = false;
13303   if (InVec.getOpcode() == ISD::BITCAST) {
13304     // Don't duplicate a load with other uses.
13305     if (!InVec.hasOneUse())
13306       return SDValue();
13307     EVT BCVT = InVec.getOperand(0).getValueType();
13308     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13309       return SDValue();
13310     InVec = InVec.getOperand(0);
13311     HasShuffleIntoBitcast = true;
13312   }
13313
13314   if (!isTargetShuffle(InVec.getOpcode()))
13315     return SDValue();
13316
13317   // Don't duplicate a load with other uses.
13318   if (!InVec.hasOneUse())
13319     return SDValue();
13320
13321   SmallVector<int, 16> ShuffleMask;
13322   bool UnaryShuffle;
13323   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13324                             UnaryShuffle))
13325     return SDValue();
13326
13327   // Select the input vector, guarding against out of range extract vector.
13328   unsigned NumElems = VT.getVectorNumElements();
13329   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13330   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13331   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13332                                          : InVec.getOperand(1);
13333
13334   // If inputs to shuffle are the same for both ops, then allow 2 uses
13335   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13336
13337   if (LdNode.getOpcode() == ISD::BITCAST) {
13338     // Don't duplicate a load with other uses.
13339     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13340       return SDValue();
13341
13342     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13343     LdNode = LdNode.getOperand(0);
13344   }
13345
13346   if (!ISD::isNormalLoad(LdNode.getNode()))
13347     return SDValue();
13348
13349   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13350
13351   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13352     return SDValue();
13353
13354   if (HasShuffleIntoBitcast) {
13355     // If there's a bitcast before the shuffle, check if the load type and
13356     // alignment is valid.
13357     unsigned Align = LN0->getAlignment();
13358     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13359     unsigned NewAlign = TLI.getTargetData()->
13360       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13361
13362     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13363       return SDValue();
13364   }
13365
13366   // All checks match so transform back to vector_shuffle so that DAG combiner
13367   // can finish the job
13368   DebugLoc dl = N->getDebugLoc();
13369
13370   // Create shuffle node taking into account the case that its a unary shuffle
13371   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13372   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13373                                  InVec.getOperand(0), Shuffle,
13374                                  &ShuffleMask[0]);
13375   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13376   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13377                      EltNo);
13378 }
13379
13380 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13381 /// generation and convert it from being a bunch of shuffles and extracts
13382 /// to a simple store and scalar loads to extract the elements.
13383 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13384                                          TargetLowering::DAGCombinerInfo &DCI) {
13385   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13386   if (NewOp.getNode())
13387     return NewOp;
13388
13389   SDValue InputVector = N->getOperand(0);
13390
13391   // Only operate on vectors of 4 elements, where the alternative shuffling
13392   // gets to be more expensive.
13393   if (InputVector.getValueType() != MVT::v4i32)
13394     return SDValue();
13395
13396   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13397   // single use which is a sign-extend or zero-extend, and all elements are
13398   // used.
13399   SmallVector<SDNode *, 4> Uses;
13400   unsigned ExtractedElements = 0;
13401   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13402        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13403     if (UI.getUse().getResNo() != InputVector.getResNo())
13404       return SDValue();
13405
13406     SDNode *Extract = *UI;
13407     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13408       return SDValue();
13409
13410     if (Extract->getValueType(0) != MVT::i32)
13411       return SDValue();
13412     if (!Extract->hasOneUse())
13413       return SDValue();
13414     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13415         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13416       return SDValue();
13417     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13418       return SDValue();
13419
13420     // Record which element was extracted.
13421     ExtractedElements |=
13422       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13423
13424     Uses.push_back(Extract);
13425   }
13426
13427   // If not all the elements were used, this may not be worthwhile.
13428   if (ExtractedElements != 15)
13429     return SDValue();
13430
13431   // Ok, we've now decided to do the transformation.
13432   DebugLoc dl = InputVector.getDebugLoc();
13433
13434   // Store the value to a temporary stack slot.
13435   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13436   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13437                             MachinePointerInfo(), false, false, 0);
13438
13439   // Replace each use (extract) with a load of the appropriate element.
13440   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13441        UE = Uses.end(); UI != UE; ++UI) {
13442     SDNode *Extract = *UI;
13443
13444     // cOMpute the element's address.
13445     SDValue Idx = Extract->getOperand(1);
13446     unsigned EltSize =
13447         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13448     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13449     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13450     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13451
13452     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13453                                      StackPtr, OffsetVal);
13454
13455     // Load the scalar.
13456     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13457                                      ScalarAddr, MachinePointerInfo(),
13458                                      false, false, false, 0);
13459
13460     // Replace the exact with the load.
13461     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13462   }
13463
13464   // The replacement was made in place; don't return anything.
13465   return SDValue();
13466 }
13467
13468 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13469 /// nodes.
13470 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13471                                     TargetLowering::DAGCombinerInfo &DCI,
13472                                     const X86Subtarget *Subtarget) {
13473   DebugLoc DL = N->getDebugLoc();
13474   SDValue Cond = N->getOperand(0);
13475   // Get the LHS/RHS of the select.
13476   SDValue LHS = N->getOperand(1);
13477   SDValue RHS = N->getOperand(2);
13478   EVT VT = LHS.getValueType();
13479
13480   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13481   // instructions match the semantics of the common C idiom x<y?x:y but not
13482   // x<=y?x:y, because of how they handle negative zero (which can be
13483   // ignored in unsafe-math mode).
13484   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13485       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13486       (Subtarget->hasSSE2() ||
13487        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13488     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13489
13490     unsigned Opcode = 0;
13491     // Check for x CC y ? x : y.
13492     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13493         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13494       switch (CC) {
13495       default: break;
13496       case ISD::SETULT:
13497         // Converting this to a min would handle NaNs incorrectly, and swapping
13498         // the operands would cause it to handle comparisons between positive
13499         // and negative zero incorrectly.
13500         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13501           if (!DAG.getTarget().Options.UnsafeFPMath &&
13502               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13503             break;
13504           std::swap(LHS, RHS);
13505         }
13506         Opcode = X86ISD::FMIN;
13507         break;
13508       case ISD::SETOLE:
13509         // Converting this to a min would handle comparisons between positive
13510         // and negative zero incorrectly.
13511         if (!DAG.getTarget().Options.UnsafeFPMath &&
13512             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13513           break;
13514         Opcode = X86ISD::FMIN;
13515         break;
13516       case ISD::SETULE:
13517         // Converting this to a min would handle both negative zeros and NaNs
13518         // incorrectly, but we can swap the operands to fix both.
13519         std::swap(LHS, RHS);
13520       case ISD::SETOLT:
13521       case ISD::SETLT:
13522       case ISD::SETLE:
13523         Opcode = X86ISD::FMIN;
13524         break;
13525
13526       case ISD::SETOGE:
13527         // Converting this to a max would handle comparisons between positive
13528         // and negative zero incorrectly.
13529         if (!DAG.getTarget().Options.UnsafeFPMath &&
13530             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13531           break;
13532         Opcode = X86ISD::FMAX;
13533         break;
13534       case ISD::SETUGT:
13535         // Converting this to a max would handle NaNs incorrectly, and swapping
13536         // the operands would cause it to handle comparisons between positive
13537         // and negative zero incorrectly.
13538         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13539           if (!DAG.getTarget().Options.UnsafeFPMath &&
13540               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13541             break;
13542           std::swap(LHS, RHS);
13543         }
13544         Opcode = X86ISD::FMAX;
13545         break;
13546       case ISD::SETUGE:
13547         // Converting this to a max would handle both negative zeros and NaNs
13548         // incorrectly, but we can swap the operands to fix both.
13549         std::swap(LHS, RHS);
13550       case ISD::SETOGT:
13551       case ISD::SETGT:
13552       case ISD::SETGE:
13553         Opcode = X86ISD::FMAX;
13554         break;
13555       }
13556     // Check for x CC y ? y : x -- a min/max with reversed arms.
13557     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13558                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13559       switch (CC) {
13560       default: break;
13561       case ISD::SETOGE:
13562         // Converting this to a min would handle comparisons between positive
13563         // and negative zero incorrectly, and swapping the operands would
13564         // cause it to handle NaNs incorrectly.
13565         if (!DAG.getTarget().Options.UnsafeFPMath &&
13566             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13567           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13568             break;
13569           std::swap(LHS, RHS);
13570         }
13571         Opcode = X86ISD::FMIN;
13572         break;
13573       case ISD::SETUGT:
13574         // Converting this to a min would handle NaNs incorrectly.
13575         if (!DAG.getTarget().Options.UnsafeFPMath &&
13576             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13577           break;
13578         Opcode = X86ISD::FMIN;
13579         break;
13580       case ISD::SETUGE:
13581         // Converting this to a min would handle both negative zeros and NaNs
13582         // incorrectly, but we can swap the operands to fix both.
13583         std::swap(LHS, RHS);
13584       case ISD::SETOGT:
13585       case ISD::SETGT:
13586       case ISD::SETGE:
13587         Opcode = X86ISD::FMIN;
13588         break;
13589
13590       case ISD::SETULT:
13591         // Converting this to a max would handle NaNs incorrectly.
13592         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13593           break;
13594         Opcode = X86ISD::FMAX;
13595         break;
13596       case ISD::SETOLE:
13597         // Converting this to a max would handle comparisons between positive
13598         // and negative zero incorrectly, and swapping the operands would
13599         // cause it to handle NaNs incorrectly.
13600         if (!DAG.getTarget().Options.UnsafeFPMath &&
13601             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13602           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13603             break;
13604           std::swap(LHS, RHS);
13605         }
13606         Opcode = X86ISD::FMAX;
13607         break;
13608       case ISD::SETULE:
13609         // Converting this to a max would handle both negative zeros and NaNs
13610         // incorrectly, but we can swap the operands to fix both.
13611         std::swap(LHS, RHS);
13612       case ISD::SETOLT:
13613       case ISD::SETLT:
13614       case ISD::SETLE:
13615         Opcode = X86ISD::FMAX;
13616         break;
13617       }
13618     }
13619
13620     if (Opcode)
13621       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13622   }
13623
13624   // If this is a select between two integer constants, try to do some
13625   // optimizations.
13626   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13627     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13628       // Don't do this for crazy integer types.
13629       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13630         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13631         // so that TrueC (the true value) is larger than FalseC.
13632         bool NeedsCondInvert = false;
13633
13634         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13635             // Efficiently invertible.
13636             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13637              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13638               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13639           NeedsCondInvert = true;
13640           std::swap(TrueC, FalseC);
13641         }
13642
13643         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13644         if (FalseC->getAPIntValue() == 0 &&
13645             TrueC->getAPIntValue().isPowerOf2()) {
13646           if (NeedsCondInvert) // Invert the condition if needed.
13647             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13648                                DAG.getConstant(1, Cond.getValueType()));
13649
13650           // Zero extend the condition if needed.
13651           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13652
13653           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13654           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13655                              DAG.getConstant(ShAmt, MVT::i8));
13656         }
13657
13658         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13659         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13660           if (NeedsCondInvert) // Invert the condition if needed.
13661             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13662                                DAG.getConstant(1, Cond.getValueType()));
13663
13664           // Zero extend the condition if needed.
13665           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13666                              FalseC->getValueType(0), Cond);
13667           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13668                              SDValue(FalseC, 0));
13669         }
13670
13671         // Optimize cases that will turn into an LEA instruction.  This requires
13672         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13673         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13674           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13675           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13676
13677           bool isFastMultiplier = false;
13678           if (Diff < 10) {
13679             switch ((unsigned char)Diff) {
13680               default: break;
13681               case 1:  // result = add base, cond
13682               case 2:  // result = lea base(    , cond*2)
13683               case 3:  // result = lea base(cond, cond*2)
13684               case 4:  // result = lea base(    , cond*4)
13685               case 5:  // result = lea base(cond, cond*4)
13686               case 8:  // result = lea base(    , cond*8)
13687               case 9:  // result = lea base(cond, cond*8)
13688                 isFastMultiplier = true;
13689                 break;
13690             }
13691           }
13692
13693           if (isFastMultiplier) {
13694             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13695             if (NeedsCondInvert) // Invert the condition if needed.
13696               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13697                                  DAG.getConstant(1, Cond.getValueType()));
13698
13699             // Zero extend the condition if needed.
13700             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13701                                Cond);
13702             // Scale the condition by the difference.
13703             if (Diff != 1)
13704               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13705                                  DAG.getConstant(Diff, Cond.getValueType()));
13706
13707             // Add the base if non-zero.
13708             if (FalseC->getAPIntValue() != 0)
13709               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13710                                  SDValue(FalseC, 0));
13711             return Cond;
13712           }
13713         }
13714       }
13715   }
13716
13717   // Canonicalize max and min:
13718   // (x > y) ? x : y -> (x >= y) ? x : y
13719   // (x < y) ? x : y -> (x <= y) ? x : y
13720   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13721   // the need for an extra compare
13722   // against zero. e.g.
13723   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13724   // subl   %esi, %edi
13725   // testl  %edi, %edi
13726   // movl   $0, %eax
13727   // cmovgl %edi, %eax
13728   // =>
13729   // xorl   %eax, %eax
13730   // subl   %esi, $edi
13731   // cmovsl %eax, %edi
13732   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13733       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13734       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13735     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13736     switch (CC) {
13737     default: break;
13738     case ISD::SETLT:
13739     case ISD::SETGT: {
13740       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13741       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13742                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13743       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13744     }
13745     }
13746   }
13747
13748   // If we know that this node is legal then we know that it is going to be
13749   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13750   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13751   // to simplify previous instructions.
13752   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13753   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13754       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
13755     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13756
13757     // Don't optimize vector selects that map to mask-registers.
13758     if (BitWidth == 1)
13759       return SDValue();
13760
13761     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13762     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13763
13764     APInt KnownZero, KnownOne;
13765     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13766                                           DCI.isBeforeLegalizeOps());
13767     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13768         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13769       DCI.CommitTargetLoweringOpt(TLO);
13770   }
13771
13772   return SDValue();
13773 }
13774
13775 // Check whether a boolean test is testing a boolean value generated by
13776 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
13777 // code.
13778 //
13779 // Simplify the following patterns:
13780 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
13781 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
13782 // to (Op EFLAGS Cond)
13783 //
13784 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
13785 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
13786 // to (Op EFLAGS !Cond)
13787 //
13788 // where Op could be BRCOND or CMOV.
13789 //
13790 static SDValue BoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
13791   // Quit if not CMP and SUB with its value result used.
13792   if (Cmp.getOpcode() != X86ISD::CMP &&
13793       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
13794       return SDValue();
13795
13796   // Quit if not used as a boolean value.
13797   if (CC != X86::COND_E && CC != X86::COND_NE)
13798     return SDValue();
13799
13800   // Check CMP operands. One of them should be 0 or 1 and the other should be
13801   // an SetCC or extended from it.
13802   SDValue Op1 = Cmp.getOperand(0);
13803   SDValue Op2 = Cmp.getOperand(1);
13804
13805   SDValue SetCC;
13806   const ConstantSDNode* C = 0;
13807   bool needOppositeCond = (CC == X86::COND_E);
13808
13809   if ((C = dyn_cast<ConstantSDNode>(Op1)))
13810     SetCC = Op2;
13811   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
13812     SetCC = Op1;
13813   else // Quit if all operands are not constants.
13814     return SDValue();
13815
13816   if (C->getZExtValue() == 1)
13817     needOppositeCond = !needOppositeCond;
13818   else if (C->getZExtValue() != 0)
13819     // Quit if the constant is neither 0 or 1.
13820     return SDValue();
13821
13822   // Skip 'zext' node.
13823   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
13824     SetCC = SetCC.getOperand(0);
13825
13826   // Quit if not SETCC.
13827   // FIXME: So far we only handle the boolean value generated from SETCC. If
13828   // there is other ways to generate boolean values, we need handle them here
13829   // as well.
13830   if (SetCC.getOpcode() != X86ISD::SETCC)
13831     return SDValue();
13832
13833   // Set the condition code or opposite one if necessary.
13834   CC = X86::CondCode(SetCC.getConstantOperandVal(0));
13835   if (needOppositeCond)
13836     CC = X86::GetOppositeBranchCondition(CC);
13837
13838   return SetCC.getOperand(1);
13839 }
13840
13841 static bool IsValidFCMOVCondition(X86::CondCode CC) {
13842   switch (CC) {
13843   default:
13844     return false;
13845   case X86::COND_B:
13846   case X86::COND_BE:
13847   case X86::COND_E:
13848   case X86::COND_P:
13849   case X86::COND_AE:
13850   case X86::COND_A:
13851   case X86::COND_NE:
13852   case X86::COND_NP:
13853     return true;
13854   }
13855 }
13856
13857 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13858 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13859                                   TargetLowering::DAGCombinerInfo &DCI) {
13860   DebugLoc DL = N->getDebugLoc();
13861
13862   // If the flag operand isn't dead, don't touch this CMOV.
13863   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13864     return SDValue();
13865
13866   SDValue FalseOp = N->getOperand(0);
13867   SDValue TrueOp = N->getOperand(1);
13868   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13869   SDValue Cond = N->getOperand(3);
13870
13871   if (CC == X86::COND_E || CC == X86::COND_NE) {
13872     switch (Cond.getOpcode()) {
13873     default: break;
13874     case X86ISD::BSR:
13875     case X86ISD::BSF:
13876       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13877       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13878         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13879     }
13880   }
13881
13882   SDValue Flags;
13883
13884   Flags = BoolTestSetCCCombine(Cond, CC);
13885   if (Flags.getNode() &&
13886       // Extra check as FCMOV only supports a subset of X86 cond.
13887       (FalseOp.getValueType() != MVT::f80 || IsValidFCMOVCondition(CC))) {
13888     SDValue Ops[] = { FalseOp, TrueOp,
13889                       DAG.getConstant(CC, MVT::i8), Flags };
13890     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
13891                        Ops, array_lengthof(Ops));
13892   }
13893
13894   // If this is a select between two integer constants, try to do some
13895   // optimizations.  Note that the operands are ordered the opposite of SELECT
13896   // operands.
13897   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13898     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13899       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13900       // larger than FalseC (the false value).
13901       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13902         CC = X86::GetOppositeBranchCondition(CC);
13903         std::swap(TrueC, FalseC);
13904       }
13905
13906       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13907       // This is efficient for any integer data type (including i8/i16) and
13908       // shift amount.
13909       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13910         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13911                            DAG.getConstant(CC, MVT::i8), Cond);
13912
13913         // Zero extend the condition if needed.
13914         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13915
13916         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13917         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13918                            DAG.getConstant(ShAmt, MVT::i8));
13919         if (N->getNumValues() == 2)  // Dead flag value?
13920           return DCI.CombineTo(N, Cond, SDValue());
13921         return Cond;
13922       }
13923
13924       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13925       // for any integer data type, including i8/i16.
13926       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13927         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13928                            DAG.getConstant(CC, MVT::i8), Cond);
13929
13930         // Zero extend the condition if needed.
13931         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13932                            FalseC->getValueType(0), Cond);
13933         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13934                            SDValue(FalseC, 0));
13935
13936         if (N->getNumValues() == 2)  // Dead flag value?
13937           return DCI.CombineTo(N, Cond, SDValue());
13938         return Cond;
13939       }
13940
13941       // Optimize cases that will turn into an LEA instruction.  This requires
13942       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13943       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13944         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13945         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13946
13947         bool isFastMultiplier = false;
13948         if (Diff < 10) {
13949           switch ((unsigned char)Diff) {
13950           default: break;
13951           case 1:  // result = add base, cond
13952           case 2:  // result = lea base(    , cond*2)
13953           case 3:  // result = lea base(cond, cond*2)
13954           case 4:  // result = lea base(    , cond*4)
13955           case 5:  // result = lea base(cond, cond*4)
13956           case 8:  // result = lea base(    , cond*8)
13957           case 9:  // result = lea base(cond, cond*8)
13958             isFastMultiplier = true;
13959             break;
13960           }
13961         }
13962
13963         if (isFastMultiplier) {
13964           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13965           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13966                              DAG.getConstant(CC, MVT::i8), Cond);
13967           // Zero extend the condition if needed.
13968           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13969                              Cond);
13970           // Scale the condition by the difference.
13971           if (Diff != 1)
13972             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13973                                DAG.getConstant(Diff, Cond.getValueType()));
13974
13975           // Add the base if non-zero.
13976           if (FalseC->getAPIntValue() != 0)
13977             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13978                                SDValue(FalseC, 0));
13979           if (N->getNumValues() == 2)  // Dead flag value?
13980             return DCI.CombineTo(N, Cond, SDValue());
13981           return Cond;
13982         }
13983       }
13984     }
13985   }
13986   return SDValue();
13987 }
13988
13989
13990 /// PerformMulCombine - Optimize a single multiply with constant into two
13991 /// in order to implement it with two cheaper instructions, e.g.
13992 /// LEA + SHL, LEA + LEA.
13993 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13994                                  TargetLowering::DAGCombinerInfo &DCI) {
13995   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13996     return SDValue();
13997
13998   EVT VT = N->getValueType(0);
13999   if (VT != MVT::i64)
14000     return SDValue();
14001
14002   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14003   if (!C)
14004     return SDValue();
14005   uint64_t MulAmt = C->getZExtValue();
14006   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14007     return SDValue();
14008
14009   uint64_t MulAmt1 = 0;
14010   uint64_t MulAmt2 = 0;
14011   if ((MulAmt % 9) == 0) {
14012     MulAmt1 = 9;
14013     MulAmt2 = MulAmt / 9;
14014   } else if ((MulAmt % 5) == 0) {
14015     MulAmt1 = 5;
14016     MulAmt2 = MulAmt / 5;
14017   } else if ((MulAmt % 3) == 0) {
14018     MulAmt1 = 3;
14019     MulAmt2 = MulAmt / 3;
14020   }
14021   if (MulAmt2 &&
14022       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14023     DebugLoc DL = N->getDebugLoc();
14024
14025     if (isPowerOf2_64(MulAmt2) &&
14026         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14027       // If second multiplifer is pow2, issue it first. We want the multiply by
14028       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14029       // is an add.
14030       std::swap(MulAmt1, MulAmt2);
14031
14032     SDValue NewMul;
14033     if (isPowerOf2_64(MulAmt1))
14034       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14035                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14036     else
14037       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14038                            DAG.getConstant(MulAmt1, VT));
14039
14040     if (isPowerOf2_64(MulAmt2))
14041       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14042                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14043     else
14044       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14045                            DAG.getConstant(MulAmt2, VT));
14046
14047     // Do not add new nodes to DAG combiner worklist.
14048     DCI.CombineTo(N, NewMul, false);
14049   }
14050   return SDValue();
14051 }
14052
14053 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14054   SDValue N0 = N->getOperand(0);
14055   SDValue N1 = N->getOperand(1);
14056   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14057   EVT VT = N0.getValueType();
14058
14059   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14060   // since the result of setcc_c is all zero's or all ones.
14061   if (VT.isInteger() && !VT.isVector() &&
14062       N1C && N0.getOpcode() == ISD::AND &&
14063       N0.getOperand(1).getOpcode() == ISD::Constant) {
14064     SDValue N00 = N0.getOperand(0);
14065     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14066         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14067           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14068          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14069       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14070       APInt ShAmt = N1C->getAPIntValue();
14071       Mask = Mask.shl(ShAmt);
14072       if (Mask != 0)
14073         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14074                            N00, DAG.getConstant(Mask, VT));
14075     }
14076   }
14077
14078
14079   // Hardware support for vector shifts is sparse which makes us scalarize the
14080   // vector operations in many cases. Also, on sandybridge ADD is faster than
14081   // shl.
14082   // (shl V, 1) -> add V,V
14083   if (isSplatVector(N1.getNode())) {
14084     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14085     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14086     // We shift all of the values by one. In many cases we do not have
14087     // hardware support for this operation. This is better expressed as an ADD
14088     // of two values.
14089     if (N1C && (1 == N1C->getZExtValue())) {
14090       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14091     }
14092   }
14093
14094   return SDValue();
14095 }
14096
14097 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14098 ///                       when possible.
14099 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14100                                    TargetLowering::DAGCombinerInfo &DCI,
14101                                    const X86Subtarget *Subtarget) {
14102   EVT VT = N->getValueType(0);
14103   if (N->getOpcode() == ISD::SHL) {
14104     SDValue V = PerformSHLCombine(N, DAG);
14105     if (V.getNode()) return V;
14106   }
14107
14108   // On X86 with SSE2 support, we can transform this to a vector shift if
14109   // all elements are shifted by the same amount.  We can't do this in legalize
14110   // because the a constant vector is typically transformed to a constant pool
14111   // so we have no knowledge of the shift amount.
14112   if (!Subtarget->hasSSE2())
14113     return SDValue();
14114
14115   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14116       (!Subtarget->hasAVX2() ||
14117        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14118     return SDValue();
14119
14120   SDValue ShAmtOp = N->getOperand(1);
14121   EVT EltVT = VT.getVectorElementType();
14122   DebugLoc DL = N->getDebugLoc();
14123   SDValue BaseShAmt = SDValue();
14124   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14125     unsigned NumElts = VT.getVectorNumElements();
14126     unsigned i = 0;
14127     for (; i != NumElts; ++i) {
14128       SDValue Arg = ShAmtOp.getOperand(i);
14129       if (Arg.getOpcode() == ISD::UNDEF) continue;
14130       BaseShAmt = Arg;
14131       break;
14132     }
14133     // Handle the case where the build_vector is all undef
14134     // FIXME: Should DAG allow this?
14135     if (i == NumElts)
14136       return SDValue();
14137
14138     for (; i != NumElts; ++i) {
14139       SDValue Arg = ShAmtOp.getOperand(i);
14140       if (Arg.getOpcode() == ISD::UNDEF) continue;
14141       if (Arg != BaseShAmt) {
14142         return SDValue();
14143       }
14144     }
14145   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14146              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14147     SDValue InVec = ShAmtOp.getOperand(0);
14148     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14149       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14150       unsigned i = 0;
14151       for (; i != NumElts; ++i) {
14152         SDValue Arg = InVec.getOperand(i);
14153         if (Arg.getOpcode() == ISD::UNDEF) continue;
14154         BaseShAmt = Arg;
14155         break;
14156       }
14157     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14158        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14159          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14160          if (C->getZExtValue() == SplatIdx)
14161            BaseShAmt = InVec.getOperand(1);
14162        }
14163     }
14164     if (BaseShAmt.getNode() == 0) {
14165       // Don't create instructions with illegal types after legalize
14166       // types has run.
14167       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14168           !DCI.isBeforeLegalize())
14169         return SDValue();
14170
14171       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14172                               DAG.getIntPtrConstant(0));
14173     }
14174   } else
14175     return SDValue();
14176
14177   // The shift amount is an i32.
14178   if (EltVT.bitsGT(MVT::i32))
14179     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14180   else if (EltVT.bitsLT(MVT::i32))
14181     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14182
14183   // The shift amount is identical so we can do a vector shift.
14184   SDValue  ValOp = N->getOperand(0);
14185   switch (N->getOpcode()) {
14186   default:
14187     llvm_unreachable("Unknown shift opcode!");
14188   case ISD::SHL:
14189     switch (VT.getSimpleVT().SimpleTy) {
14190     default: return SDValue();
14191     case MVT::v2i64:
14192     case MVT::v4i32:
14193     case MVT::v8i16:
14194     case MVT::v4i64:
14195     case MVT::v8i32:
14196     case MVT::v16i16:
14197       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14198     }
14199   case ISD::SRA:
14200     switch (VT.getSimpleVT().SimpleTy) {
14201     default: return SDValue();
14202     case MVT::v4i32:
14203     case MVT::v8i16:
14204     case MVT::v8i32:
14205     case MVT::v16i16:
14206       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14207     }
14208   case ISD::SRL:
14209     switch (VT.getSimpleVT().SimpleTy) {
14210     default: return SDValue();
14211     case MVT::v2i64:
14212     case MVT::v4i32:
14213     case MVT::v8i16:
14214     case MVT::v4i64:
14215     case MVT::v8i32:
14216     case MVT::v16i16:
14217       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14218     }
14219   }
14220 }
14221
14222
14223 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14224 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14225 // and friends.  Likewise for OR -> CMPNEQSS.
14226 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14227                             TargetLowering::DAGCombinerInfo &DCI,
14228                             const X86Subtarget *Subtarget) {
14229   unsigned opcode;
14230
14231   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14232   // we're requiring SSE2 for both.
14233   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14234     SDValue N0 = N->getOperand(0);
14235     SDValue N1 = N->getOperand(1);
14236     SDValue CMP0 = N0->getOperand(1);
14237     SDValue CMP1 = N1->getOperand(1);
14238     DebugLoc DL = N->getDebugLoc();
14239
14240     // The SETCCs should both refer to the same CMP.
14241     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14242       return SDValue();
14243
14244     SDValue CMP00 = CMP0->getOperand(0);
14245     SDValue CMP01 = CMP0->getOperand(1);
14246     EVT     VT    = CMP00.getValueType();
14247
14248     if (VT == MVT::f32 || VT == MVT::f64) {
14249       bool ExpectingFlags = false;
14250       // Check for any users that want flags:
14251       for (SDNode::use_iterator UI = N->use_begin(),
14252              UE = N->use_end();
14253            !ExpectingFlags && UI != UE; ++UI)
14254         switch (UI->getOpcode()) {
14255         default:
14256         case ISD::BR_CC:
14257         case ISD::BRCOND:
14258         case ISD::SELECT:
14259           ExpectingFlags = true;
14260           break;
14261         case ISD::CopyToReg:
14262         case ISD::SIGN_EXTEND:
14263         case ISD::ZERO_EXTEND:
14264         case ISD::ANY_EXTEND:
14265           break;
14266         }
14267
14268       if (!ExpectingFlags) {
14269         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14270         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14271
14272         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14273           X86::CondCode tmp = cc0;
14274           cc0 = cc1;
14275           cc1 = tmp;
14276         }
14277
14278         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14279             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14280           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14281           X86ISD::NodeType NTOperator = is64BitFP ?
14282             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14283           // FIXME: need symbolic constants for these magic numbers.
14284           // See X86ATTInstPrinter.cpp:printSSECC().
14285           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14286           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14287                                               DAG.getConstant(x86cc, MVT::i8));
14288           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14289                                               OnesOrZeroesF);
14290           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14291                                       DAG.getConstant(1, MVT::i32));
14292           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14293           return OneBitOfTruth;
14294         }
14295       }
14296     }
14297   }
14298   return SDValue();
14299 }
14300
14301 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14302 /// so it can be folded inside ANDNP.
14303 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14304   EVT VT = N->getValueType(0);
14305
14306   // Match direct AllOnes for 128 and 256-bit vectors
14307   if (ISD::isBuildVectorAllOnes(N))
14308     return true;
14309
14310   // Look through a bit convert.
14311   if (N->getOpcode() == ISD::BITCAST)
14312     N = N->getOperand(0).getNode();
14313
14314   // Sometimes the operand may come from a insert_subvector building a 256-bit
14315   // allones vector
14316   if (VT.is256BitVector() &&
14317       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14318     SDValue V1 = N->getOperand(0);
14319     SDValue V2 = N->getOperand(1);
14320
14321     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14322         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14323         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14324         ISD::isBuildVectorAllOnes(V2.getNode()))
14325       return true;
14326   }
14327
14328   return false;
14329 }
14330
14331 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14332                                  TargetLowering::DAGCombinerInfo &DCI,
14333                                  const X86Subtarget *Subtarget) {
14334   if (DCI.isBeforeLegalizeOps())
14335     return SDValue();
14336
14337   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14338   if (R.getNode())
14339     return R;
14340
14341   EVT VT = N->getValueType(0);
14342
14343   // Create ANDN, BLSI, and BLSR instructions
14344   // BLSI is X & (-X)
14345   // BLSR is X & (X-1)
14346   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14347     SDValue N0 = N->getOperand(0);
14348     SDValue N1 = N->getOperand(1);
14349     DebugLoc DL = N->getDebugLoc();
14350
14351     // Check LHS for not
14352     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14353       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14354     // Check RHS for not
14355     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14356       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14357
14358     // Check LHS for neg
14359     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14360         isZero(N0.getOperand(0)))
14361       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14362
14363     // Check RHS for neg
14364     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14365         isZero(N1.getOperand(0)))
14366       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14367
14368     // Check LHS for X-1
14369     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14370         isAllOnes(N0.getOperand(1)))
14371       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14372
14373     // Check RHS for X-1
14374     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14375         isAllOnes(N1.getOperand(1)))
14376       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14377
14378     return SDValue();
14379   }
14380
14381   // Want to form ANDNP nodes:
14382   // 1) In the hopes of then easily combining them with OR and AND nodes
14383   //    to form PBLEND/PSIGN.
14384   // 2) To match ANDN packed intrinsics
14385   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14386     return SDValue();
14387
14388   SDValue N0 = N->getOperand(0);
14389   SDValue N1 = N->getOperand(1);
14390   DebugLoc DL = N->getDebugLoc();
14391
14392   // Check LHS for vnot
14393   if (N0.getOpcode() == ISD::XOR &&
14394       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14395       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14396     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14397
14398   // Check RHS for vnot
14399   if (N1.getOpcode() == ISD::XOR &&
14400       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14401       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14402     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14403
14404   return SDValue();
14405 }
14406
14407 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14408                                 TargetLowering::DAGCombinerInfo &DCI,
14409                                 const X86Subtarget *Subtarget) {
14410   if (DCI.isBeforeLegalizeOps())
14411     return SDValue();
14412
14413   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14414   if (R.getNode())
14415     return R;
14416
14417   EVT VT = N->getValueType(0);
14418
14419   SDValue N0 = N->getOperand(0);
14420   SDValue N1 = N->getOperand(1);
14421
14422   // look for psign/blend
14423   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14424     if (!Subtarget->hasSSSE3() ||
14425         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14426       return SDValue();
14427
14428     // Canonicalize pandn to RHS
14429     if (N0.getOpcode() == X86ISD::ANDNP)
14430       std::swap(N0, N1);
14431     // or (and (m, y), (pandn m, x))
14432     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14433       SDValue Mask = N1.getOperand(0);
14434       SDValue X    = N1.getOperand(1);
14435       SDValue Y;
14436       if (N0.getOperand(0) == Mask)
14437         Y = N0.getOperand(1);
14438       if (N0.getOperand(1) == Mask)
14439         Y = N0.getOperand(0);
14440
14441       // Check to see if the mask appeared in both the AND and ANDNP and
14442       if (!Y.getNode())
14443         return SDValue();
14444
14445       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14446       // Look through mask bitcast.
14447       if (Mask.getOpcode() == ISD::BITCAST)
14448         Mask = Mask.getOperand(0);
14449       if (X.getOpcode() == ISD::BITCAST)
14450         X = X.getOperand(0);
14451       if (Y.getOpcode() == ISD::BITCAST)
14452         Y = Y.getOperand(0);
14453
14454       EVT MaskVT = Mask.getValueType();
14455
14456       // Validate that the Mask operand is a vector sra node.
14457       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14458       // there is no psrai.b
14459       if (Mask.getOpcode() != X86ISD::VSRAI)
14460         return SDValue();
14461
14462       // Check that the SRA is all signbits.
14463       SDValue SraC = Mask.getOperand(1);
14464       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14465       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14466       if ((SraAmt + 1) != EltBits)
14467         return SDValue();
14468
14469       DebugLoc DL = N->getDebugLoc();
14470
14471       // Now we know we at least have a plendvb with the mask val.  See if
14472       // we can form a psignb/w/d.
14473       // psign = x.type == y.type == mask.type && y = sub(0, x);
14474       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14475           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14476           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14477         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14478                "Unsupported VT for PSIGN");
14479         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14480         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14481       }
14482       // PBLENDVB only available on SSE 4.1
14483       if (!Subtarget->hasSSE41())
14484         return SDValue();
14485
14486       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14487
14488       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14489       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14490       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14491       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14492       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14493     }
14494   }
14495
14496   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14497     return SDValue();
14498
14499   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14500   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14501     std::swap(N0, N1);
14502   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14503     return SDValue();
14504   if (!N0.hasOneUse() || !N1.hasOneUse())
14505     return SDValue();
14506
14507   SDValue ShAmt0 = N0.getOperand(1);
14508   if (ShAmt0.getValueType() != MVT::i8)
14509     return SDValue();
14510   SDValue ShAmt1 = N1.getOperand(1);
14511   if (ShAmt1.getValueType() != MVT::i8)
14512     return SDValue();
14513   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14514     ShAmt0 = ShAmt0.getOperand(0);
14515   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14516     ShAmt1 = ShAmt1.getOperand(0);
14517
14518   DebugLoc DL = N->getDebugLoc();
14519   unsigned Opc = X86ISD::SHLD;
14520   SDValue Op0 = N0.getOperand(0);
14521   SDValue Op1 = N1.getOperand(0);
14522   if (ShAmt0.getOpcode() == ISD::SUB) {
14523     Opc = X86ISD::SHRD;
14524     std::swap(Op0, Op1);
14525     std::swap(ShAmt0, ShAmt1);
14526   }
14527
14528   unsigned Bits = VT.getSizeInBits();
14529   if (ShAmt1.getOpcode() == ISD::SUB) {
14530     SDValue Sum = ShAmt1.getOperand(0);
14531     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14532       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14533       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14534         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14535       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14536         return DAG.getNode(Opc, DL, VT,
14537                            Op0, Op1,
14538                            DAG.getNode(ISD::TRUNCATE, DL,
14539                                        MVT::i8, ShAmt0));
14540     }
14541   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14542     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14543     if (ShAmt0C &&
14544         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14545       return DAG.getNode(Opc, DL, VT,
14546                          N0.getOperand(0), N1.getOperand(0),
14547                          DAG.getNode(ISD::TRUNCATE, DL,
14548                                        MVT::i8, ShAmt0));
14549   }
14550
14551   return SDValue();
14552 }
14553
14554 // Generate NEG and CMOV for integer abs.
14555 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14556   EVT VT = N->getValueType(0);
14557
14558   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14559   // 8-bit integer abs to NEG and CMOV.
14560   if (VT.isInteger() && VT.getSizeInBits() == 8)
14561     return SDValue();
14562
14563   SDValue N0 = N->getOperand(0);
14564   SDValue N1 = N->getOperand(1);
14565   DebugLoc DL = N->getDebugLoc();
14566
14567   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14568   // and change it to SUB and CMOV.
14569   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14570       N0.getOpcode() == ISD::ADD &&
14571       N0.getOperand(1) == N1 &&
14572       N1.getOpcode() == ISD::SRA &&
14573       N1.getOperand(0) == N0.getOperand(0))
14574     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14575       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14576         // Generate SUB & CMOV.
14577         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14578                                   DAG.getConstant(0, VT), N0.getOperand(0));
14579
14580         SDValue Ops[] = { N0.getOperand(0), Neg,
14581                           DAG.getConstant(X86::COND_GE, MVT::i8),
14582                           SDValue(Neg.getNode(), 1) };
14583         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14584                            Ops, array_lengthof(Ops));
14585       }
14586   return SDValue();
14587 }
14588
14589 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14590 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14591                                  TargetLowering::DAGCombinerInfo &DCI,
14592                                  const X86Subtarget *Subtarget) {
14593   if (DCI.isBeforeLegalizeOps())
14594     return SDValue();
14595
14596   if (Subtarget->hasCMov()) {
14597     SDValue RV = performIntegerAbsCombine(N, DAG);
14598     if (RV.getNode())
14599       return RV;
14600   }
14601
14602   // Try forming BMI if it is available.
14603   if (!Subtarget->hasBMI())
14604     return SDValue();
14605
14606   EVT VT = N->getValueType(0);
14607
14608   if (VT != MVT::i32 && VT != MVT::i64)
14609     return SDValue();
14610
14611   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14612
14613   // Create BLSMSK instructions by finding X ^ (X-1)
14614   SDValue N0 = N->getOperand(0);
14615   SDValue N1 = N->getOperand(1);
14616   DebugLoc DL = N->getDebugLoc();
14617
14618   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14619       isAllOnes(N0.getOperand(1)))
14620     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14621
14622   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14623       isAllOnes(N1.getOperand(1)))
14624     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14625
14626   return SDValue();
14627 }
14628
14629 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14630 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14631                                   TargetLowering::DAGCombinerInfo &DCI,
14632                                   const X86Subtarget *Subtarget) {
14633   LoadSDNode *Ld = cast<LoadSDNode>(N);
14634   EVT RegVT = Ld->getValueType(0);
14635   EVT MemVT = Ld->getMemoryVT();
14636   DebugLoc dl = Ld->getDebugLoc();
14637   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14638
14639   ISD::LoadExtType Ext = Ld->getExtensionType();
14640
14641   // If this is a vector EXT Load then attempt to optimize it using a
14642   // shuffle. We need SSE4 for the shuffles.
14643   // TODO: It is possible to support ZExt by zeroing the undef values
14644   // during the shuffle phase or after the shuffle.
14645   if (RegVT.isVector() && RegVT.isInteger() &&
14646       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14647     assert(MemVT != RegVT && "Cannot extend to the same type");
14648     assert(MemVT.isVector() && "Must load a vector from memory");
14649
14650     unsigned NumElems = RegVT.getVectorNumElements();
14651     unsigned RegSz = RegVT.getSizeInBits();
14652     unsigned MemSz = MemVT.getSizeInBits();
14653     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14654
14655     // All sizes must be a power of two.
14656     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
14657       return SDValue();
14658
14659     // Attempt to load the original value using scalar loads.
14660     // Find the largest scalar type that divides the total loaded size.
14661     MVT SclrLoadTy = MVT::i8;
14662     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14663          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14664       MVT Tp = (MVT::SimpleValueType)tp;
14665       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14666         SclrLoadTy = Tp;
14667       }
14668     }
14669
14670     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14671     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14672         (64 <= MemSz))
14673       SclrLoadTy = MVT::f64;
14674
14675     // Calculate the number of scalar loads that we need to perform
14676     // in order to load our vector from memory.
14677     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14678
14679     // Represent our vector as a sequence of elements which are the
14680     // largest scalar that we can load.
14681     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14682       RegSz/SclrLoadTy.getSizeInBits());
14683
14684     // Represent the data using the same element type that is stored in
14685     // memory. In practice, we ''widen'' MemVT.
14686     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14687                                   RegSz/MemVT.getScalarType().getSizeInBits());
14688
14689     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14690       "Invalid vector type");
14691
14692     // We can't shuffle using an illegal type.
14693     if (!TLI.isTypeLegal(WideVecVT))
14694       return SDValue();
14695
14696     SmallVector<SDValue, 8> Chains;
14697     SDValue Ptr = Ld->getBasePtr();
14698     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
14699                                         TLI.getPointerTy());
14700     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14701
14702     for (unsigned i = 0; i < NumLoads; ++i) {
14703       // Perform a single load.
14704       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14705                                        Ptr, Ld->getPointerInfo(),
14706                                        Ld->isVolatile(), Ld->isNonTemporal(),
14707                                        Ld->isInvariant(), Ld->getAlignment());
14708       Chains.push_back(ScalarLoad.getValue(1));
14709       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14710       // another round of DAGCombining.
14711       if (i == 0)
14712         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14713       else
14714         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14715                           ScalarLoad, DAG.getIntPtrConstant(i));
14716
14717       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14718     }
14719
14720     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14721                                Chains.size());
14722
14723     // Bitcast the loaded value to a vector of the original element type, in
14724     // the size of the target vector type.
14725     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14726     unsigned SizeRatio = RegSz/MemSz;
14727
14728     // Redistribute the loaded elements into the different locations.
14729     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14730     for (unsigned i = 0; i != NumElems; ++i)
14731       ShuffleVec[i*SizeRatio] = i;
14732
14733     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14734                                          DAG.getUNDEF(WideVecVT),
14735                                          &ShuffleVec[0]);
14736
14737     // Bitcast to the requested type.
14738     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14739     // Replace the original load with the new sequence
14740     // and return the new chain.
14741     return DCI.CombineTo(N, Shuff, TF, true);
14742   }
14743
14744   return SDValue();
14745 }
14746
14747 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14748 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14749                                    const X86Subtarget *Subtarget) {
14750   StoreSDNode *St = cast<StoreSDNode>(N);
14751   EVT VT = St->getValue().getValueType();
14752   EVT StVT = St->getMemoryVT();
14753   DebugLoc dl = St->getDebugLoc();
14754   SDValue StoredVal = St->getOperand(1);
14755   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14756
14757   // If we are saving a concatenation of two XMM registers, perform two stores.
14758   // On Sandy Bridge, 256-bit memory operations are executed by two
14759   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14760   // memory  operation.
14761   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
14762       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14763       StoredVal.getNumOperands() == 2) {
14764     SDValue Value0 = StoredVal.getOperand(0);
14765     SDValue Value1 = StoredVal.getOperand(1);
14766
14767     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14768     SDValue Ptr0 = St->getBasePtr();
14769     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14770
14771     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14772                                 St->getPointerInfo(), St->isVolatile(),
14773                                 St->isNonTemporal(), St->getAlignment());
14774     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14775                                 St->getPointerInfo(), St->isVolatile(),
14776                                 St->isNonTemporal(), St->getAlignment());
14777     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14778   }
14779
14780   // Optimize trunc store (of multiple scalars) to shuffle and store.
14781   // First, pack all of the elements in one place. Next, store to memory
14782   // in fewer chunks.
14783   if (St->isTruncatingStore() && VT.isVector()) {
14784     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14785     unsigned NumElems = VT.getVectorNumElements();
14786     assert(StVT != VT && "Cannot truncate to the same type");
14787     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14788     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14789
14790     // From, To sizes and ElemCount must be pow of two
14791     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14792     // We are going to use the original vector elt for storing.
14793     // Accumulated smaller vector elements must be a multiple of the store size.
14794     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14795
14796     unsigned SizeRatio  = FromSz / ToSz;
14797
14798     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14799
14800     // Create a type on which we perform the shuffle
14801     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14802             StVT.getScalarType(), NumElems*SizeRatio);
14803
14804     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14805
14806     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14807     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14808     for (unsigned i = 0; i != NumElems; ++i)
14809       ShuffleVec[i] = i * SizeRatio;
14810
14811     // Can't shuffle using an illegal type.
14812     if (!TLI.isTypeLegal(WideVecVT))
14813       return SDValue();
14814
14815     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14816                                          DAG.getUNDEF(WideVecVT),
14817                                          &ShuffleVec[0]);
14818     // At this point all of the data is stored at the bottom of the
14819     // register. We now need to save it to mem.
14820
14821     // Find the largest store unit
14822     MVT StoreType = MVT::i8;
14823     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14824          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14825       MVT Tp = (MVT::SimpleValueType)tp;
14826       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
14827         StoreType = Tp;
14828     }
14829
14830     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14831     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
14832         (64 <= NumElems * ToSz))
14833       StoreType = MVT::f64;
14834
14835     // Bitcast the original vector into a vector of store-size units
14836     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14837             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
14838     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14839     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14840     SmallVector<SDValue, 8> Chains;
14841     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14842                                         TLI.getPointerTy());
14843     SDValue Ptr = St->getBasePtr();
14844
14845     // Perform one or more big stores into memory.
14846     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14847       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14848                                    StoreType, ShuffWide,
14849                                    DAG.getIntPtrConstant(i));
14850       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14851                                 St->getPointerInfo(), St->isVolatile(),
14852                                 St->isNonTemporal(), St->getAlignment());
14853       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14854       Chains.push_back(Ch);
14855     }
14856
14857     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14858                                Chains.size());
14859   }
14860
14861
14862   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14863   // the FP state in cases where an emms may be missing.
14864   // A preferable solution to the general problem is to figure out the right
14865   // places to insert EMMS.  This qualifies as a quick hack.
14866
14867   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14868   if (VT.getSizeInBits() != 64)
14869     return SDValue();
14870
14871   const Function *F = DAG.getMachineFunction().getFunction();
14872   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14873   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14874                      && Subtarget->hasSSE2();
14875   if ((VT.isVector() ||
14876        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14877       isa<LoadSDNode>(St->getValue()) &&
14878       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14879       St->getChain().hasOneUse() && !St->isVolatile()) {
14880     SDNode* LdVal = St->getValue().getNode();
14881     LoadSDNode *Ld = 0;
14882     int TokenFactorIndex = -1;
14883     SmallVector<SDValue, 8> Ops;
14884     SDNode* ChainVal = St->getChain().getNode();
14885     // Must be a store of a load.  We currently handle two cases:  the load
14886     // is a direct child, and it's under an intervening TokenFactor.  It is
14887     // possible to dig deeper under nested TokenFactors.
14888     if (ChainVal == LdVal)
14889       Ld = cast<LoadSDNode>(St->getChain());
14890     else if (St->getValue().hasOneUse() &&
14891              ChainVal->getOpcode() == ISD::TokenFactor) {
14892       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14893         if (ChainVal->getOperand(i).getNode() == LdVal) {
14894           TokenFactorIndex = i;
14895           Ld = cast<LoadSDNode>(St->getValue());
14896         } else
14897           Ops.push_back(ChainVal->getOperand(i));
14898       }
14899     }
14900
14901     if (!Ld || !ISD::isNormalLoad(Ld))
14902       return SDValue();
14903
14904     // If this is not the MMX case, i.e. we are just turning i64 load/store
14905     // into f64 load/store, avoid the transformation if there are multiple
14906     // uses of the loaded value.
14907     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14908       return SDValue();
14909
14910     DebugLoc LdDL = Ld->getDebugLoc();
14911     DebugLoc StDL = N->getDebugLoc();
14912     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14913     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14914     // pair instead.
14915     if (Subtarget->is64Bit() || F64IsLegal) {
14916       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14917       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14918                                   Ld->getPointerInfo(), Ld->isVolatile(),
14919                                   Ld->isNonTemporal(), Ld->isInvariant(),
14920                                   Ld->getAlignment());
14921       SDValue NewChain = NewLd.getValue(1);
14922       if (TokenFactorIndex != -1) {
14923         Ops.push_back(NewChain);
14924         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14925                                Ops.size());
14926       }
14927       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14928                           St->getPointerInfo(),
14929                           St->isVolatile(), St->isNonTemporal(),
14930                           St->getAlignment());
14931     }
14932
14933     // Otherwise, lower to two pairs of 32-bit loads / stores.
14934     SDValue LoAddr = Ld->getBasePtr();
14935     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14936                                  DAG.getConstant(4, MVT::i32));
14937
14938     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14939                                Ld->getPointerInfo(),
14940                                Ld->isVolatile(), Ld->isNonTemporal(),
14941                                Ld->isInvariant(), Ld->getAlignment());
14942     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14943                                Ld->getPointerInfo().getWithOffset(4),
14944                                Ld->isVolatile(), Ld->isNonTemporal(),
14945                                Ld->isInvariant(),
14946                                MinAlign(Ld->getAlignment(), 4));
14947
14948     SDValue NewChain = LoLd.getValue(1);
14949     if (TokenFactorIndex != -1) {
14950       Ops.push_back(LoLd);
14951       Ops.push_back(HiLd);
14952       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14953                              Ops.size());
14954     }
14955
14956     LoAddr = St->getBasePtr();
14957     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14958                          DAG.getConstant(4, MVT::i32));
14959
14960     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14961                                 St->getPointerInfo(),
14962                                 St->isVolatile(), St->isNonTemporal(),
14963                                 St->getAlignment());
14964     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14965                                 St->getPointerInfo().getWithOffset(4),
14966                                 St->isVolatile(),
14967                                 St->isNonTemporal(),
14968                                 MinAlign(St->getAlignment(), 4));
14969     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14970   }
14971   return SDValue();
14972 }
14973
14974 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14975 /// and return the operands for the horizontal operation in LHS and RHS.  A
14976 /// horizontal operation performs the binary operation on successive elements
14977 /// of its first operand, then on successive elements of its second operand,
14978 /// returning the resulting values in a vector.  For example, if
14979 ///   A = < float a0, float a1, float a2, float a3 >
14980 /// and
14981 ///   B = < float b0, float b1, float b2, float b3 >
14982 /// then the result of doing a horizontal operation on A and B is
14983 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14984 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14985 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14986 /// set to A, RHS to B, and the routine returns 'true'.
14987 /// Note that the binary operation should have the property that if one of the
14988 /// operands is UNDEF then the result is UNDEF.
14989 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14990   // Look for the following pattern: if
14991   //   A = < float a0, float a1, float a2, float a3 >
14992   //   B = < float b0, float b1, float b2, float b3 >
14993   // and
14994   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14995   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14996   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14997   // which is A horizontal-op B.
14998
14999   // At least one of the operands should be a vector shuffle.
15000   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15001       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15002     return false;
15003
15004   EVT VT = LHS.getValueType();
15005
15006   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15007          "Unsupported vector type for horizontal add/sub");
15008
15009   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15010   // operate independently on 128-bit lanes.
15011   unsigned NumElts = VT.getVectorNumElements();
15012   unsigned NumLanes = VT.getSizeInBits()/128;
15013   unsigned NumLaneElts = NumElts / NumLanes;
15014   assert((NumLaneElts % 2 == 0) &&
15015          "Vector type should have an even number of elements in each lane");
15016   unsigned HalfLaneElts = NumLaneElts/2;
15017
15018   // View LHS in the form
15019   //   LHS = VECTOR_SHUFFLE A, B, LMask
15020   // If LHS is not a shuffle then pretend it is the shuffle
15021   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15022   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15023   // type VT.
15024   SDValue A, B;
15025   SmallVector<int, 16> LMask(NumElts);
15026   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15027     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15028       A = LHS.getOperand(0);
15029     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15030       B = LHS.getOperand(1);
15031     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15032     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15033   } else {
15034     if (LHS.getOpcode() != ISD::UNDEF)
15035       A = LHS;
15036     for (unsigned i = 0; i != NumElts; ++i)
15037       LMask[i] = i;
15038   }
15039
15040   // Likewise, view RHS in the form
15041   //   RHS = VECTOR_SHUFFLE C, D, RMask
15042   SDValue C, D;
15043   SmallVector<int, 16> RMask(NumElts);
15044   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15045     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15046       C = RHS.getOperand(0);
15047     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15048       D = RHS.getOperand(1);
15049     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15050     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15051   } else {
15052     if (RHS.getOpcode() != ISD::UNDEF)
15053       C = RHS;
15054     for (unsigned i = 0; i != NumElts; ++i)
15055       RMask[i] = i;
15056   }
15057
15058   // Check that the shuffles are both shuffling the same vectors.
15059   if (!(A == C && B == D) && !(A == D && B == C))
15060     return false;
15061
15062   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15063   if (!A.getNode() && !B.getNode())
15064     return false;
15065
15066   // If A and B occur in reverse order in RHS, then "swap" them (which means
15067   // rewriting the mask).
15068   if (A != C)
15069     CommuteVectorShuffleMask(RMask, NumElts);
15070
15071   // At this point LHS and RHS are equivalent to
15072   //   LHS = VECTOR_SHUFFLE A, B, LMask
15073   //   RHS = VECTOR_SHUFFLE A, B, RMask
15074   // Check that the masks correspond to performing a horizontal operation.
15075   for (unsigned i = 0; i != NumElts; ++i) {
15076     int LIdx = LMask[i], RIdx = RMask[i];
15077
15078     // Ignore any UNDEF components.
15079     if (LIdx < 0 || RIdx < 0 ||
15080         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15081         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15082       continue;
15083
15084     // Check that successive elements are being operated on.  If not, this is
15085     // not a horizontal operation.
15086     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15087     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15088     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15089     if (!(LIdx == Index && RIdx == Index + 1) &&
15090         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15091       return false;
15092   }
15093
15094   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15095   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15096   return true;
15097 }
15098
15099 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15100 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15101                                   const X86Subtarget *Subtarget) {
15102   EVT VT = N->getValueType(0);
15103   SDValue LHS = N->getOperand(0);
15104   SDValue RHS = N->getOperand(1);
15105
15106   // Try to synthesize horizontal adds from adds of shuffles.
15107   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15108        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15109       isHorizontalBinOp(LHS, RHS, true))
15110     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15111   return SDValue();
15112 }
15113
15114 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15115 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15116                                   const X86Subtarget *Subtarget) {
15117   EVT VT = N->getValueType(0);
15118   SDValue LHS = N->getOperand(0);
15119   SDValue RHS = N->getOperand(1);
15120
15121   // Try to synthesize horizontal subs from subs of shuffles.
15122   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15123        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15124       isHorizontalBinOp(LHS, RHS, false))
15125     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15126   return SDValue();
15127 }
15128
15129 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15130 /// X86ISD::FXOR nodes.
15131 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15132   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15133   // F[X]OR(0.0, x) -> x
15134   // F[X]OR(x, 0.0) -> x
15135   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15136     if (C->getValueAPF().isPosZero())
15137       return N->getOperand(1);
15138   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15139     if (C->getValueAPF().isPosZero())
15140       return N->getOperand(0);
15141   return SDValue();
15142 }
15143
15144 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15145 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15146   // FAND(0.0, x) -> 0.0
15147   // FAND(x, 0.0) -> 0.0
15148   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15149     if (C->getValueAPF().isPosZero())
15150       return N->getOperand(0);
15151   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15152     if (C->getValueAPF().isPosZero())
15153       return N->getOperand(1);
15154   return SDValue();
15155 }
15156
15157 static SDValue PerformBTCombine(SDNode *N,
15158                                 SelectionDAG &DAG,
15159                                 TargetLowering::DAGCombinerInfo &DCI) {
15160   // BT ignores high bits in the bit index operand.
15161   SDValue Op1 = N->getOperand(1);
15162   if (Op1.hasOneUse()) {
15163     unsigned BitWidth = Op1.getValueSizeInBits();
15164     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15165     APInt KnownZero, KnownOne;
15166     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15167                                           !DCI.isBeforeLegalizeOps());
15168     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15169     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15170         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15171       DCI.CommitTargetLoweringOpt(TLO);
15172   }
15173   return SDValue();
15174 }
15175
15176 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15177   SDValue Op = N->getOperand(0);
15178   if (Op.getOpcode() == ISD::BITCAST)
15179     Op = Op.getOperand(0);
15180   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15181   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15182       VT.getVectorElementType().getSizeInBits() ==
15183       OpVT.getVectorElementType().getSizeInBits()) {
15184     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15185   }
15186   return SDValue();
15187 }
15188
15189 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15190                                   TargetLowering::DAGCombinerInfo &DCI,
15191                                   const X86Subtarget *Subtarget) {
15192   if (!DCI.isBeforeLegalizeOps())
15193     return SDValue();
15194
15195   if (!Subtarget->hasAVX())
15196     return SDValue();
15197
15198   EVT VT = N->getValueType(0);
15199   SDValue Op = N->getOperand(0);
15200   EVT OpVT = Op.getValueType();
15201   DebugLoc dl = N->getDebugLoc();
15202
15203   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15204       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15205
15206     if (Subtarget->hasAVX2())
15207       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15208
15209     // Optimize vectors in AVX mode
15210     // Sign extend  v8i16 to v8i32 and
15211     //              v4i32 to v4i64
15212     //
15213     // Divide input vector into two parts
15214     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15215     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15216     // concat the vectors to original VT
15217
15218     unsigned NumElems = OpVT.getVectorNumElements();
15219     SmallVector<int,8> ShufMask1(NumElems, -1);
15220     for (unsigned i = 0; i != NumElems/2; ++i)
15221       ShufMask1[i] = i;
15222
15223     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15224                                         &ShufMask1[0]);
15225
15226     SmallVector<int,8> ShufMask2(NumElems, -1);
15227     for (unsigned i = 0; i != NumElems/2; ++i)
15228       ShufMask2[i] = i + NumElems/2;
15229
15230     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15231                                         &ShufMask2[0]);
15232
15233     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15234                                   VT.getVectorNumElements()/2);
15235
15236     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15237     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15238
15239     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15240   }
15241   return SDValue();
15242 }
15243
15244 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15245                                  const X86Subtarget* Subtarget) {
15246   DebugLoc dl = N->getDebugLoc();
15247   EVT VT = N->getValueType(0);
15248
15249   EVT ScalarVT = VT.getScalarType();
15250   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasFMA())
15251     return SDValue();
15252
15253   SDValue A = N->getOperand(0);
15254   SDValue B = N->getOperand(1);
15255   SDValue C = N->getOperand(2);
15256
15257   bool NegA = (A.getOpcode() == ISD::FNEG);
15258   bool NegB = (B.getOpcode() == ISD::FNEG);
15259   bool NegC = (C.getOpcode() == ISD::FNEG);
15260
15261   // Negative multiplication when NegA xor NegB
15262   bool NegMul = (NegA != NegB);
15263   if (NegA)
15264     A = A.getOperand(0);
15265   if (NegB)
15266     B = B.getOperand(0);
15267   if (NegC)
15268     C = C.getOperand(0);
15269
15270   unsigned Opcode;
15271   if (!NegMul)
15272     Opcode = (!NegC)? X86ISD::FMADD : X86ISD::FMSUB;
15273   else
15274     Opcode = (!NegC)? X86ISD::FNMADD : X86ISD::FNMSUB;
15275   return DAG.getNode(Opcode, dl, VT, A, B, C);
15276 }
15277
15278 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15279                                   TargetLowering::DAGCombinerInfo &DCI,
15280                                   const X86Subtarget *Subtarget) {
15281   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15282   //           (and (i32 x86isd::setcc_carry), 1)
15283   // This eliminates the zext. This transformation is necessary because
15284   // ISD::SETCC is always legalized to i8.
15285   DebugLoc dl = N->getDebugLoc();
15286   SDValue N0 = N->getOperand(0);
15287   EVT VT = N->getValueType(0);
15288   EVT OpVT = N0.getValueType();
15289
15290   if (N0.getOpcode() == ISD::AND &&
15291       N0.hasOneUse() &&
15292       N0.getOperand(0).hasOneUse()) {
15293     SDValue N00 = N0.getOperand(0);
15294     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15295       return SDValue();
15296     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15297     if (!C || C->getZExtValue() != 1)
15298       return SDValue();
15299     return DAG.getNode(ISD::AND, dl, VT,
15300                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15301                                    N00.getOperand(0), N00.getOperand(1)),
15302                        DAG.getConstant(1, VT));
15303   }
15304
15305   // Optimize vectors in AVX mode:
15306   //
15307   //   v8i16 -> v8i32
15308   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15309   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15310   //   Concat upper and lower parts.
15311   //
15312   //   v4i32 -> v4i64
15313   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15314   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15315   //   Concat upper and lower parts.
15316   //
15317   if (!DCI.isBeforeLegalizeOps())
15318     return SDValue();
15319
15320   if (!Subtarget->hasAVX())
15321     return SDValue();
15322
15323   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15324       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15325
15326     if (Subtarget->hasAVX2())
15327       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15328
15329     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15330     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15331     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15332
15333     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15334                                VT.getVectorNumElements()/2);
15335
15336     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15337     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15338
15339     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15340   }
15341
15342   return SDValue();
15343 }
15344
15345 // Optimize x == -y --> x+y == 0
15346 //          x != -y --> x+y != 0
15347 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15348   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15349   SDValue LHS = N->getOperand(0);
15350   SDValue RHS = N->getOperand(1);
15351
15352   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15353     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15354       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15355         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15356                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15357         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15358                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15359       }
15360   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15361     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15362       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15363         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15364                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15365         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15366                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15367       }
15368   return SDValue();
15369 }
15370
15371 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15372 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15373   DebugLoc DL = N->getDebugLoc();
15374   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15375   SDValue EFLAGS = N->getOperand(1);
15376
15377   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15378   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15379   // cases.
15380   if (CC == X86::COND_B)
15381     return DAG.getNode(ISD::AND, DL, MVT::i8,
15382                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15383                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
15384                        DAG.getConstant(1, MVT::i8));
15385
15386   SDValue Flags;
15387
15388   Flags = BoolTestSetCCCombine(EFLAGS, CC);
15389   if (Flags.getNode()) {
15390     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15391     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15392   }
15393
15394   return SDValue();
15395 }
15396
15397 // Optimize branch condition evaluation.
15398 //
15399 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15400                                     TargetLowering::DAGCombinerInfo &DCI,
15401                                     const X86Subtarget *Subtarget) {
15402   DebugLoc DL = N->getDebugLoc();
15403   SDValue Chain = N->getOperand(0);
15404   SDValue Dest = N->getOperand(1);
15405   SDValue EFLAGS = N->getOperand(3);
15406   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15407
15408   SDValue Flags;
15409
15410   Flags = BoolTestSetCCCombine(EFLAGS, CC);
15411   if (Flags.getNode()) {
15412     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15413     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15414                        Flags);
15415   }
15416
15417   return SDValue();
15418 }
15419
15420 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15421   SDValue Op0 = N->getOperand(0);
15422   EVT InVT = Op0->getValueType(0);
15423
15424   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15425   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15426     DebugLoc dl = N->getDebugLoc();
15427     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15428     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15429     // Notice that we use SINT_TO_FP because we know that the high bits
15430     // are zero and SINT_TO_FP is better supported by the hardware.
15431     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15432   }
15433
15434   return SDValue();
15435 }
15436
15437 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15438                                         const X86TargetLowering *XTLI) {
15439   SDValue Op0 = N->getOperand(0);
15440   EVT InVT = Op0->getValueType(0);
15441
15442   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15443   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15444     DebugLoc dl = N->getDebugLoc();
15445     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15446     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15447     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15448   }
15449
15450   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15451   // a 32-bit target where SSE doesn't support i64->FP operations.
15452   if (Op0.getOpcode() == ISD::LOAD) {
15453     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15454     EVT VT = Ld->getValueType(0);
15455     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15456         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15457         !XTLI->getSubtarget()->is64Bit() &&
15458         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15459       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15460                                           Ld->getChain(), Op0, DAG);
15461       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15462       return FILDChain;
15463     }
15464   }
15465   return SDValue();
15466 }
15467
15468 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15469   EVT VT = N->getValueType(0);
15470
15471   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15472   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15473     DebugLoc dl = N->getDebugLoc();
15474     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15475     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15476     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15477   }
15478
15479   return SDValue();
15480 }
15481
15482 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15483 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15484                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15485   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15486   // the result is either zero or one (depending on the input carry bit).
15487   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15488   if (X86::isZeroNode(N->getOperand(0)) &&
15489       X86::isZeroNode(N->getOperand(1)) &&
15490       // We don't have a good way to replace an EFLAGS use, so only do this when
15491       // dead right now.
15492       SDValue(N, 1).use_empty()) {
15493     DebugLoc DL = N->getDebugLoc();
15494     EVT VT = N->getValueType(0);
15495     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15496     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15497                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15498                                            DAG.getConstant(X86::COND_B,MVT::i8),
15499                                            N->getOperand(2)),
15500                                DAG.getConstant(1, VT));
15501     return DCI.CombineTo(N, Res1, CarryOut);
15502   }
15503
15504   return SDValue();
15505 }
15506
15507 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15508 //      (add Y, (setne X, 0)) -> sbb -1, Y
15509 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15510 //      (sub (setne X, 0), Y) -> adc -1, Y
15511 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15512   DebugLoc DL = N->getDebugLoc();
15513
15514   // Look through ZExts.
15515   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15516   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15517     return SDValue();
15518
15519   SDValue SetCC = Ext.getOperand(0);
15520   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15521     return SDValue();
15522
15523   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15524   if (CC != X86::COND_E && CC != X86::COND_NE)
15525     return SDValue();
15526
15527   SDValue Cmp = SetCC.getOperand(1);
15528   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15529       !X86::isZeroNode(Cmp.getOperand(1)) ||
15530       !Cmp.getOperand(0).getValueType().isInteger())
15531     return SDValue();
15532
15533   SDValue CmpOp0 = Cmp.getOperand(0);
15534   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15535                                DAG.getConstant(1, CmpOp0.getValueType()));
15536
15537   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15538   if (CC == X86::COND_NE)
15539     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15540                        DL, OtherVal.getValueType(), OtherVal,
15541                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15542   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15543                      DL, OtherVal.getValueType(), OtherVal,
15544                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15545 }
15546
15547 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15548 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15549                                  const X86Subtarget *Subtarget) {
15550   EVT VT = N->getValueType(0);
15551   SDValue Op0 = N->getOperand(0);
15552   SDValue Op1 = N->getOperand(1);
15553
15554   // Try to synthesize horizontal adds from adds of shuffles.
15555   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15556        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15557       isHorizontalBinOp(Op0, Op1, true))
15558     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15559
15560   return OptimizeConditionalInDecrement(N, DAG);
15561 }
15562
15563 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15564                                  const X86Subtarget *Subtarget) {
15565   SDValue Op0 = N->getOperand(0);
15566   SDValue Op1 = N->getOperand(1);
15567
15568   // X86 can't encode an immediate LHS of a sub. See if we can push the
15569   // negation into a preceding instruction.
15570   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15571     // If the RHS of the sub is a XOR with one use and a constant, invert the
15572     // immediate. Then add one to the LHS of the sub so we can turn
15573     // X-Y -> X+~Y+1, saving one register.
15574     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15575         isa<ConstantSDNode>(Op1.getOperand(1))) {
15576       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15577       EVT VT = Op0.getValueType();
15578       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15579                                    Op1.getOperand(0),
15580                                    DAG.getConstant(~XorC, VT));
15581       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15582                          DAG.getConstant(C->getAPIntValue()+1, VT));
15583     }
15584   }
15585
15586   // Try to synthesize horizontal adds from adds of shuffles.
15587   EVT VT = N->getValueType(0);
15588   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15589        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15590       isHorizontalBinOp(Op0, Op1, true))
15591     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15592
15593   return OptimizeConditionalInDecrement(N, DAG);
15594 }
15595
15596 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15597                                              DAGCombinerInfo &DCI) const {
15598   SelectionDAG &DAG = DCI.DAG;
15599   switch (N->getOpcode()) {
15600   default: break;
15601   case ISD::EXTRACT_VECTOR_ELT:
15602     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15603   case ISD::VSELECT:
15604   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15605   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
15606   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15607   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15608   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
15609   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
15610   case ISD::SHL:
15611   case ISD::SRA:
15612   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
15613   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
15614   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
15615   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
15616   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
15617   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
15618   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
15619   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
15620   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
15621   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
15622   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
15623   case X86ISD::FXOR:
15624   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
15625   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
15626   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
15627   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
15628   case ISD::ANY_EXTEND:
15629   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
15630   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
15631   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
15632   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
15633   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
15634   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
15635   case X86ISD::SHUFP:       // Handle all target specific shuffles
15636   case X86ISD::PALIGN:
15637   case X86ISD::UNPCKH:
15638   case X86ISD::UNPCKL:
15639   case X86ISD::MOVHLPS:
15640   case X86ISD::MOVLHPS:
15641   case X86ISD::PSHUFD:
15642   case X86ISD::PSHUFHW:
15643   case X86ISD::PSHUFLW:
15644   case X86ISD::MOVSS:
15645   case X86ISD::MOVSD:
15646   case X86ISD::VPERMILP:
15647   case X86ISD::VPERM2X128:
15648   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15649   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
15650   }
15651
15652   return SDValue();
15653 }
15654
15655 /// isTypeDesirableForOp - Return true if the target has native support for
15656 /// the specified value type and it is 'desirable' to use the type for the
15657 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15658 /// instruction encodings are longer and some i16 instructions are slow.
15659 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15660   if (!isTypeLegal(VT))
15661     return false;
15662   if (VT != MVT::i16)
15663     return true;
15664
15665   switch (Opc) {
15666   default:
15667     return true;
15668   case ISD::LOAD:
15669   case ISD::SIGN_EXTEND:
15670   case ISD::ZERO_EXTEND:
15671   case ISD::ANY_EXTEND:
15672   case ISD::SHL:
15673   case ISD::SRL:
15674   case ISD::SUB:
15675   case ISD::ADD:
15676   case ISD::MUL:
15677   case ISD::AND:
15678   case ISD::OR:
15679   case ISD::XOR:
15680     return false;
15681   }
15682 }
15683
15684 /// IsDesirableToPromoteOp - This method query the target whether it is
15685 /// beneficial for dag combiner to promote the specified node. If true, it
15686 /// should return the desired promotion type by reference.
15687 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15688   EVT VT = Op.getValueType();
15689   if (VT != MVT::i16)
15690     return false;
15691
15692   bool Promote = false;
15693   bool Commute = false;
15694   switch (Op.getOpcode()) {
15695   default: break;
15696   case ISD::LOAD: {
15697     LoadSDNode *LD = cast<LoadSDNode>(Op);
15698     // If the non-extending load has a single use and it's not live out, then it
15699     // might be folded.
15700     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15701                                                      Op.hasOneUse()*/) {
15702       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15703              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15704         // The only case where we'd want to promote LOAD (rather then it being
15705         // promoted as an operand is when it's only use is liveout.
15706         if (UI->getOpcode() != ISD::CopyToReg)
15707           return false;
15708       }
15709     }
15710     Promote = true;
15711     break;
15712   }
15713   case ISD::SIGN_EXTEND:
15714   case ISD::ZERO_EXTEND:
15715   case ISD::ANY_EXTEND:
15716     Promote = true;
15717     break;
15718   case ISD::SHL:
15719   case ISD::SRL: {
15720     SDValue N0 = Op.getOperand(0);
15721     // Look out for (store (shl (load), x)).
15722     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15723       return false;
15724     Promote = true;
15725     break;
15726   }
15727   case ISD::ADD:
15728   case ISD::MUL:
15729   case ISD::AND:
15730   case ISD::OR:
15731   case ISD::XOR:
15732     Commute = true;
15733     // fallthrough
15734   case ISD::SUB: {
15735     SDValue N0 = Op.getOperand(0);
15736     SDValue N1 = Op.getOperand(1);
15737     if (!Commute && MayFoldLoad(N1))
15738       return false;
15739     // Avoid disabling potential load folding opportunities.
15740     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15741       return false;
15742     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15743       return false;
15744     Promote = true;
15745   }
15746   }
15747
15748   PVT = MVT::i32;
15749   return Promote;
15750 }
15751
15752 //===----------------------------------------------------------------------===//
15753 //                           X86 Inline Assembly Support
15754 //===----------------------------------------------------------------------===//
15755
15756 namespace {
15757   // Helper to match a string separated by whitespace.
15758   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15759     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15760
15761     for (unsigned i = 0, e = args.size(); i != e; ++i) {
15762       StringRef piece(*args[i]);
15763       if (!s.startswith(piece)) // Check if the piece matches.
15764         return false;
15765
15766       s = s.substr(piece.size());
15767       StringRef::size_type pos = s.find_first_not_of(" \t");
15768       if (pos == 0) // We matched a prefix.
15769         return false;
15770
15771       s = s.substr(pos);
15772     }
15773
15774     return s.empty();
15775   }
15776   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15777 }
15778
15779 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15780   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15781
15782   std::string AsmStr = IA->getAsmString();
15783
15784   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15785   if (!Ty || Ty->getBitWidth() % 16 != 0)
15786     return false;
15787
15788   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15789   SmallVector<StringRef, 4> AsmPieces;
15790   SplitString(AsmStr, AsmPieces, ";\n");
15791
15792   switch (AsmPieces.size()) {
15793   default: return false;
15794   case 1:
15795     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15796     // we will turn this bswap into something that will be lowered to logical
15797     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
15798     // lower so don't worry about this.
15799     // bswap $0
15800     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15801         matchAsm(AsmPieces[0], "bswapl", "$0") ||
15802         matchAsm(AsmPieces[0], "bswapq", "$0") ||
15803         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15804         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15805         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15806       // No need to check constraints, nothing other than the equivalent of
15807       // "=r,0" would be valid here.
15808       return IntrinsicLowering::LowerToByteSwap(CI);
15809     }
15810
15811     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15812     if (CI->getType()->isIntegerTy(16) &&
15813         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15814         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15815          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15816       AsmPieces.clear();
15817       const std::string &ConstraintsStr = IA->getConstraintString();
15818       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15819       std::sort(AsmPieces.begin(), AsmPieces.end());
15820       if (AsmPieces.size() == 4 &&
15821           AsmPieces[0] == "~{cc}" &&
15822           AsmPieces[1] == "~{dirflag}" &&
15823           AsmPieces[2] == "~{flags}" &&
15824           AsmPieces[3] == "~{fpsr}")
15825       return IntrinsicLowering::LowerToByteSwap(CI);
15826     }
15827     break;
15828   case 3:
15829     if (CI->getType()->isIntegerTy(32) &&
15830         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15831         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15832         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15833         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15834       AsmPieces.clear();
15835       const std::string &ConstraintsStr = IA->getConstraintString();
15836       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15837       std::sort(AsmPieces.begin(), AsmPieces.end());
15838       if (AsmPieces.size() == 4 &&
15839           AsmPieces[0] == "~{cc}" &&
15840           AsmPieces[1] == "~{dirflag}" &&
15841           AsmPieces[2] == "~{flags}" &&
15842           AsmPieces[3] == "~{fpsr}")
15843         return IntrinsicLowering::LowerToByteSwap(CI);
15844     }
15845
15846     if (CI->getType()->isIntegerTy(64)) {
15847       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15848       if (Constraints.size() >= 2 &&
15849           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15850           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15851         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15852         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15853             matchAsm(AsmPieces[1], "bswap", "%edx") &&
15854             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15855           return IntrinsicLowering::LowerToByteSwap(CI);
15856       }
15857     }
15858     break;
15859   }
15860   return false;
15861 }
15862
15863
15864
15865 /// getConstraintType - Given a constraint letter, return the type of
15866 /// constraint it is for this target.
15867 X86TargetLowering::ConstraintType
15868 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15869   if (Constraint.size() == 1) {
15870     switch (Constraint[0]) {
15871     case 'R':
15872     case 'q':
15873     case 'Q':
15874     case 'f':
15875     case 't':
15876     case 'u':
15877     case 'y':
15878     case 'x':
15879     case 'Y':
15880     case 'l':
15881       return C_RegisterClass;
15882     case 'a':
15883     case 'b':
15884     case 'c':
15885     case 'd':
15886     case 'S':
15887     case 'D':
15888     case 'A':
15889       return C_Register;
15890     case 'I':
15891     case 'J':
15892     case 'K':
15893     case 'L':
15894     case 'M':
15895     case 'N':
15896     case 'G':
15897     case 'C':
15898     case 'e':
15899     case 'Z':
15900       return C_Other;
15901     default:
15902       break;
15903     }
15904   }
15905   return TargetLowering::getConstraintType(Constraint);
15906 }
15907
15908 /// Examine constraint type and operand type and determine a weight value.
15909 /// This object must already have been set up with the operand type
15910 /// and the current alternative constraint selected.
15911 TargetLowering::ConstraintWeight
15912   X86TargetLowering::getSingleConstraintMatchWeight(
15913     AsmOperandInfo &info, const char *constraint) const {
15914   ConstraintWeight weight = CW_Invalid;
15915   Value *CallOperandVal = info.CallOperandVal;
15916     // If we don't have a value, we can't do a match,
15917     // but allow it at the lowest weight.
15918   if (CallOperandVal == NULL)
15919     return CW_Default;
15920   Type *type = CallOperandVal->getType();
15921   // Look at the constraint type.
15922   switch (*constraint) {
15923   default:
15924     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15925   case 'R':
15926   case 'q':
15927   case 'Q':
15928   case 'a':
15929   case 'b':
15930   case 'c':
15931   case 'd':
15932   case 'S':
15933   case 'D':
15934   case 'A':
15935     if (CallOperandVal->getType()->isIntegerTy())
15936       weight = CW_SpecificReg;
15937     break;
15938   case 'f':
15939   case 't':
15940   case 'u':
15941       if (type->isFloatingPointTy())
15942         weight = CW_SpecificReg;
15943       break;
15944   case 'y':
15945       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15946         weight = CW_SpecificReg;
15947       break;
15948   case 'x':
15949   case 'Y':
15950     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15951         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15952       weight = CW_Register;
15953     break;
15954   case 'I':
15955     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15956       if (C->getZExtValue() <= 31)
15957         weight = CW_Constant;
15958     }
15959     break;
15960   case 'J':
15961     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15962       if (C->getZExtValue() <= 63)
15963         weight = CW_Constant;
15964     }
15965     break;
15966   case 'K':
15967     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15968       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15969         weight = CW_Constant;
15970     }
15971     break;
15972   case 'L':
15973     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15974       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15975         weight = CW_Constant;
15976     }
15977     break;
15978   case 'M':
15979     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15980       if (C->getZExtValue() <= 3)
15981         weight = CW_Constant;
15982     }
15983     break;
15984   case 'N':
15985     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15986       if (C->getZExtValue() <= 0xff)
15987         weight = CW_Constant;
15988     }
15989     break;
15990   case 'G':
15991   case 'C':
15992     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15993       weight = CW_Constant;
15994     }
15995     break;
15996   case 'e':
15997     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15998       if ((C->getSExtValue() >= -0x80000000LL) &&
15999           (C->getSExtValue() <= 0x7fffffffLL))
16000         weight = CW_Constant;
16001     }
16002     break;
16003   case 'Z':
16004     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16005       if (C->getZExtValue() <= 0xffffffff)
16006         weight = CW_Constant;
16007     }
16008     break;
16009   }
16010   return weight;
16011 }
16012
16013 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16014 /// with another that has more specific requirements based on the type of the
16015 /// corresponding operand.
16016 const char *X86TargetLowering::
16017 LowerXConstraint(EVT ConstraintVT) const {
16018   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16019   // 'f' like normal targets.
16020   if (ConstraintVT.isFloatingPoint()) {
16021     if (Subtarget->hasSSE2())
16022       return "Y";
16023     if (Subtarget->hasSSE1())
16024       return "x";
16025   }
16026
16027   return TargetLowering::LowerXConstraint(ConstraintVT);
16028 }
16029
16030 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16031 /// vector.  If it is invalid, don't add anything to Ops.
16032 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16033                                                      std::string &Constraint,
16034                                                      std::vector<SDValue>&Ops,
16035                                                      SelectionDAG &DAG) const {
16036   SDValue Result(0, 0);
16037
16038   // Only support length 1 constraints for now.
16039   if (Constraint.length() > 1) return;
16040
16041   char ConstraintLetter = Constraint[0];
16042   switch (ConstraintLetter) {
16043   default: break;
16044   case 'I':
16045     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16046       if (C->getZExtValue() <= 31) {
16047         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16048         break;
16049       }
16050     }
16051     return;
16052   case 'J':
16053     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16054       if (C->getZExtValue() <= 63) {
16055         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16056         break;
16057       }
16058     }
16059     return;
16060   case 'K':
16061     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16062       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16063         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16064         break;
16065       }
16066     }
16067     return;
16068   case 'N':
16069     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16070       if (C->getZExtValue() <= 255) {
16071         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16072         break;
16073       }
16074     }
16075     return;
16076   case 'e': {
16077     // 32-bit signed value
16078     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16079       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16080                                            C->getSExtValue())) {
16081         // Widen to 64 bits here to get it sign extended.
16082         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16083         break;
16084       }
16085     // FIXME gcc accepts some relocatable values here too, but only in certain
16086     // memory models; it's complicated.
16087     }
16088     return;
16089   }
16090   case 'Z': {
16091     // 32-bit unsigned value
16092     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16093       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16094                                            C->getZExtValue())) {
16095         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16096         break;
16097       }
16098     }
16099     // FIXME gcc accepts some relocatable values here too, but only in certain
16100     // memory models; it's complicated.
16101     return;
16102   }
16103   case 'i': {
16104     // Literal immediates are always ok.
16105     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16106       // Widen to 64 bits here to get it sign extended.
16107       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16108       break;
16109     }
16110
16111     // In any sort of PIC mode addresses need to be computed at runtime by
16112     // adding in a register or some sort of table lookup.  These can't
16113     // be used as immediates.
16114     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16115       return;
16116
16117     // If we are in non-pic codegen mode, we allow the address of a global (with
16118     // an optional displacement) to be used with 'i'.
16119     GlobalAddressSDNode *GA = 0;
16120     int64_t Offset = 0;
16121
16122     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16123     while (1) {
16124       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16125         Offset += GA->getOffset();
16126         break;
16127       } else if (Op.getOpcode() == ISD::ADD) {
16128         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16129           Offset += C->getZExtValue();
16130           Op = Op.getOperand(0);
16131           continue;
16132         }
16133       } else if (Op.getOpcode() == ISD::SUB) {
16134         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16135           Offset += -C->getZExtValue();
16136           Op = Op.getOperand(0);
16137           continue;
16138         }
16139       }
16140
16141       // Otherwise, this isn't something we can handle, reject it.
16142       return;
16143     }
16144
16145     const GlobalValue *GV = GA->getGlobal();
16146     // If we require an extra load to get this address, as in PIC mode, we
16147     // can't accept it.
16148     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16149                                                         getTargetMachine())))
16150       return;
16151
16152     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16153                                         GA->getValueType(0), Offset);
16154     break;
16155   }
16156   }
16157
16158   if (Result.getNode()) {
16159     Ops.push_back(Result);
16160     return;
16161   }
16162   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16163 }
16164
16165 std::pair<unsigned, const TargetRegisterClass*>
16166 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16167                                                 EVT VT) const {
16168   // First, see if this is a constraint that directly corresponds to an LLVM
16169   // register class.
16170   if (Constraint.size() == 1) {
16171     // GCC Constraint Letters
16172     switch (Constraint[0]) {
16173     default: break;
16174       // TODO: Slight differences here in allocation order and leaving
16175       // RIP in the class. Do they matter any more here than they do
16176       // in the normal allocation?
16177     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16178       if (Subtarget->is64Bit()) {
16179         if (VT == MVT::i32 || VT == MVT::f32)
16180           return std::make_pair(0U, &X86::GR32RegClass);
16181         if (VT == MVT::i16)
16182           return std::make_pair(0U, &X86::GR16RegClass);
16183         if (VT == MVT::i8 || VT == MVT::i1)
16184           return std::make_pair(0U, &X86::GR8RegClass);
16185         if (VT == MVT::i64 || VT == MVT::f64)
16186           return std::make_pair(0U, &X86::GR64RegClass);
16187         break;
16188       }
16189       // 32-bit fallthrough
16190     case 'Q':   // Q_REGS
16191       if (VT == MVT::i32 || VT == MVT::f32)
16192         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16193       if (VT == MVT::i16)
16194         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16195       if (VT == MVT::i8 || VT == MVT::i1)
16196         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16197       if (VT == MVT::i64)
16198         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16199       break;
16200     case 'r':   // GENERAL_REGS
16201     case 'l':   // INDEX_REGS
16202       if (VT == MVT::i8 || VT == MVT::i1)
16203         return std::make_pair(0U, &X86::GR8RegClass);
16204       if (VT == MVT::i16)
16205         return std::make_pair(0U, &X86::GR16RegClass);
16206       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16207         return std::make_pair(0U, &X86::GR32RegClass);
16208       return std::make_pair(0U, &X86::GR64RegClass);
16209     case 'R':   // LEGACY_REGS
16210       if (VT == MVT::i8 || VT == MVT::i1)
16211         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16212       if (VT == MVT::i16)
16213         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16214       if (VT == MVT::i32 || !Subtarget->is64Bit())
16215         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16216       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16217     case 'f':  // FP Stack registers.
16218       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16219       // value to the correct fpstack register class.
16220       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16221         return std::make_pair(0U, &X86::RFP32RegClass);
16222       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16223         return std::make_pair(0U, &X86::RFP64RegClass);
16224       return std::make_pair(0U, &X86::RFP80RegClass);
16225     case 'y':   // MMX_REGS if MMX allowed.
16226       if (!Subtarget->hasMMX()) break;
16227       return std::make_pair(0U, &X86::VR64RegClass);
16228     case 'Y':   // SSE_REGS if SSE2 allowed
16229       if (!Subtarget->hasSSE2()) break;
16230       // FALL THROUGH.
16231     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16232       if (!Subtarget->hasSSE1()) break;
16233
16234       switch (VT.getSimpleVT().SimpleTy) {
16235       default: break;
16236       // Scalar SSE types.
16237       case MVT::f32:
16238       case MVT::i32:
16239         return std::make_pair(0U, &X86::FR32RegClass);
16240       case MVT::f64:
16241       case MVT::i64:
16242         return std::make_pair(0U, &X86::FR64RegClass);
16243       // Vector types.
16244       case MVT::v16i8:
16245       case MVT::v8i16:
16246       case MVT::v4i32:
16247       case MVT::v2i64:
16248       case MVT::v4f32:
16249       case MVT::v2f64:
16250         return std::make_pair(0U, &X86::VR128RegClass);
16251       // AVX types.
16252       case MVT::v32i8:
16253       case MVT::v16i16:
16254       case MVT::v8i32:
16255       case MVT::v4i64:
16256       case MVT::v8f32:
16257       case MVT::v4f64:
16258         return std::make_pair(0U, &X86::VR256RegClass);
16259       }
16260       break;
16261     }
16262   }
16263
16264   // Use the default implementation in TargetLowering to convert the register
16265   // constraint into a member of a register class.
16266   std::pair<unsigned, const TargetRegisterClass*> Res;
16267   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16268
16269   // Not found as a standard register?
16270   if (Res.second == 0) {
16271     // Map st(0) -> st(7) -> ST0
16272     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16273         tolower(Constraint[1]) == 's' &&
16274         tolower(Constraint[2]) == 't' &&
16275         Constraint[3] == '(' &&
16276         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16277         Constraint[5] == ')' &&
16278         Constraint[6] == '}') {
16279
16280       Res.first = X86::ST0+Constraint[4]-'0';
16281       Res.second = &X86::RFP80RegClass;
16282       return Res;
16283     }
16284
16285     // GCC allows "st(0)" to be called just plain "st".
16286     if (StringRef("{st}").equals_lower(Constraint)) {
16287       Res.first = X86::ST0;
16288       Res.second = &X86::RFP80RegClass;
16289       return Res;
16290     }
16291
16292     // flags -> EFLAGS
16293     if (StringRef("{flags}").equals_lower(Constraint)) {
16294       Res.first = X86::EFLAGS;
16295       Res.second = &X86::CCRRegClass;
16296       return Res;
16297     }
16298
16299     // 'A' means EAX + EDX.
16300     if (Constraint == "A") {
16301       Res.first = X86::EAX;
16302       Res.second = &X86::GR32_ADRegClass;
16303       return Res;
16304     }
16305     return Res;
16306   }
16307
16308   // Otherwise, check to see if this is a register class of the wrong value
16309   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16310   // turn into {ax},{dx}.
16311   if (Res.second->hasType(VT))
16312     return Res;   // Correct type already, nothing to do.
16313
16314   // All of the single-register GCC register classes map their values onto
16315   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16316   // really want an 8-bit or 32-bit register, map to the appropriate register
16317   // class and return the appropriate register.
16318   if (Res.second == &X86::GR16RegClass) {
16319     if (VT == MVT::i8) {
16320       unsigned DestReg = 0;
16321       switch (Res.first) {
16322       default: break;
16323       case X86::AX: DestReg = X86::AL; break;
16324       case X86::DX: DestReg = X86::DL; break;
16325       case X86::CX: DestReg = X86::CL; break;
16326       case X86::BX: DestReg = X86::BL; break;
16327       }
16328       if (DestReg) {
16329         Res.first = DestReg;
16330         Res.second = &X86::GR8RegClass;
16331       }
16332     } else if (VT == MVT::i32) {
16333       unsigned DestReg = 0;
16334       switch (Res.first) {
16335       default: break;
16336       case X86::AX: DestReg = X86::EAX; break;
16337       case X86::DX: DestReg = X86::EDX; break;
16338       case X86::CX: DestReg = X86::ECX; break;
16339       case X86::BX: DestReg = X86::EBX; break;
16340       case X86::SI: DestReg = X86::ESI; break;
16341       case X86::DI: DestReg = X86::EDI; break;
16342       case X86::BP: DestReg = X86::EBP; break;
16343       case X86::SP: DestReg = X86::ESP; break;
16344       }
16345       if (DestReg) {
16346         Res.first = DestReg;
16347         Res.second = &X86::GR32RegClass;
16348       }
16349     } else if (VT == MVT::i64) {
16350       unsigned DestReg = 0;
16351       switch (Res.first) {
16352       default: break;
16353       case X86::AX: DestReg = X86::RAX; break;
16354       case X86::DX: DestReg = X86::RDX; break;
16355       case X86::CX: DestReg = X86::RCX; break;
16356       case X86::BX: DestReg = X86::RBX; break;
16357       case X86::SI: DestReg = X86::RSI; break;
16358       case X86::DI: DestReg = X86::RDI; break;
16359       case X86::BP: DestReg = X86::RBP; break;
16360       case X86::SP: DestReg = X86::RSP; break;
16361       }
16362       if (DestReg) {
16363         Res.first = DestReg;
16364         Res.second = &X86::GR64RegClass;
16365       }
16366     }
16367   } else if (Res.second == &X86::FR32RegClass ||
16368              Res.second == &X86::FR64RegClass ||
16369              Res.second == &X86::VR128RegClass) {
16370     // Handle references to XMM physical registers that got mapped into the
16371     // wrong class.  This can happen with constraints like {xmm0} where the
16372     // target independent register mapper will just pick the first match it can
16373     // find, ignoring the required type.
16374
16375     if (VT == MVT::f32 || VT == MVT::i32)
16376       Res.second = &X86::FR32RegClass;
16377     else if (VT == MVT::f64 || VT == MVT::i64)
16378       Res.second = &X86::FR64RegClass;
16379     else if (X86::VR128RegClass.hasType(VT))
16380       Res.second = &X86::VR128RegClass;
16381     else if (X86::VR256RegClass.hasType(VT))
16382       Res.second = &X86::VR256RegClass;
16383   }
16384
16385   return Res;
16386 }