Fix typos found by http://github.com/lyda/misspell-check
[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 using namespace llvm;
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55
56 // Forward declarations.
57 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
58                        SDValue V2);
59
60 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
61 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
62 /// simple subregister reference.  Idx is an index in the 128 bits we
63 /// want.  It need not be aligned to a 128-bit bounday.  That makes
64 /// lowering EXTRACT_VECTOR_ELT operations easier.
65 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
66                                    SelectionDAG &DAG, DebugLoc dl) {
67   EVT VT = Vec.getValueType();
68   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
69   EVT ElVT = VT.getVectorElementType();
70   unsigned Factor = VT.getSizeInBits()/128;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
79   // we can match to VEXTRACTF128.
80   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
81
82   // This is the index of the first element of the 128-bit chunk
83   // we want.
84   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
85                                * ElemsPerChunk);
86
87   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
88   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
89                                VecIdx);
90
91   return Result;
92 }
93
94 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
95 /// sets things up to match to an AVX VINSERTF128 instruction or a
96 /// simple superregister reference.  Idx is an index in the 128 bits
97 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
98 /// lowering INSERT_VECTOR_ELT operations easier.
99 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
100                                   unsigned IdxVal, SelectionDAG &DAG,
101                                   DebugLoc dl) {
102   EVT VT = Vec.getValueType();
103   assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
104
105   EVT ElVT = VT.getVectorElementType();
106   EVT ResultVT = Result.getValueType();
107
108   // Insert the relevant 128 bits.
109   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
110
111   // This is the index of the first element of the 128-bit chunk
112   // we want.
113   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
114                                * ElemsPerChunk);
115
116   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
117   Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
118                        VecIdx);
119   return Result;
120 }
121
122 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
123 /// instructions. This is used because creating CONCAT_VECTOR nodes of
124 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
125 /// large BUILD_VECTORS.
126 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
127                                    unsigned NumElems, SelectionDAG &DAG,
128                                    DebugLoc dl) {
129   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
130   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
131 }
132
133 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
134   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
135   bool is64Bit = Subtarget->is64Bit();
136
137   if (Subtarget->isTargetEnvMacho()) {
138     if (is64Bit)
139       return new X8664_MachoTargetObjectFile();
140     return new TargetLoweringObjectFileMachO();
141   }
142
143   if (Subtarget->isTargetELF())
144     return new TargetLoweringObjectFileELF();
145   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
146     return new TargetLoweringObjectFileCOFF();
147   llvm_unreachable("unknown subtarget type");
148 }
149
150 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
151   : TargetLowering(TM, createTLOF(TM)) {
152   Subtarget = &TM.getSubtarget<X86Subtarget>();
153   X86ScalarSSEf64 = Subtarget->hasSSE2();
154   X86ScalarSSEf32 = Subtarget->hasSSE1();
155   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
156
157   RegInfo = TM.getRegisterInfo();
158   TD = getTargetData();
159
160   // Set up the TargetLowering object.
161   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
162
163   // X86 is weird, it always uses i8 for shift amounts and setcc results.
164   setBooleanContents(ZeroOrOneBooleanContent);
165   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
166   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
167
168   // For 64-bit since we have so many registers use the ILP scheduler, for
169   // 32-bit code use the register pressure specific scheduling.
170   // For Atom, always use ILP scheduling.
171   if (Subtarget->isAtom()) 
172     setSchedulingPreference(Sched::ILP);
173   else if (Subtarget->is64Bit())
174     setSchedulingPreference(Sched::ILP);
175   else
176     setSchedulingPreference(Sched::RegPressure);
177   setStackPointerRegisterToSaveRestore(X86StackPtr);
178
179   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
180     // Setup Windows compiler runtime calls.
181     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
182     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
183     setLibcallName(RTLIB::SREM_I64, "_allrem");
184     setLibcallName(RTLIB::UREM_I64, "_aullrem");
185     setLibcallName(RTLIB::MUL_I64, "_allmul");
186     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
187     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
188     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
189     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
190     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
191
192     // The _ftol2 runtime function has an unusual calling conv, which
193     // is modeled by a special pseudo-instruction.
194     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
195     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
196     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
197     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
198   }
199
200   if (Subtarget->isTargetDarwin()) {
201     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
202     setUseUnderscoreSetJmp(false);
203     setUseUnderscoreLongJmp(false);
204   } else if (Subtarget->isTargetMingw()) {
205     // MS runtime is weird: it exports _setjmp, but longjmp!
206     setUseUnderscoreSetJmp(true);
207     setUseUnderscoreLongJmp(false);
208   } else {
209     setUseUnderscoreSetJmp(true);
210     setUseUnderscoreLongJmp(true);
211   }
212
213   // Set up the register classes.
214   addRegisterClass(MVT::i8, &X86::GR8RegClass);
215   addRegisterClass(MVT::i16, &X86::GR16RegClass);
216   addRegisterClass(MVT::i32, &X86::GR32RegClass);
217   if (Subtarget->is64Bit())
218     addRegisterClass(MVT::i64, &X86::GR64RegClass);
219
220   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
221
222   // We don't accept any truncstore of integer registers.
223   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
224   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
225   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
226   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
227   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
228   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
229
230   // SETOEQ and SETUNE require checking two conditions.
231   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
232   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
233   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
234   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
235   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
236   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
237
238   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
239   // operation.
240   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
241   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
242   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
243
244   if (Subtarget->is64Bit()) {
245     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
246     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
247   } else if (!TM.Options.UseSoftFloat) {
248     // We have an algorithm for SSE2->double, and we turn this into a
249     // 64-bit FILD followed by conditional FADD for other targets.
250     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
251     // We have an algorithm for SSE2, and we turn this into a 64-bit
252     // FILD for other targets.
253     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
254   }
255
256   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
257   // this operation.
258   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
259   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
260
261   if (!TM.Options.UseSoftFloat) {
262     // SSE has no i16 to fp conversion, only i32
263     if (X86ScalarSSEf32) {
264       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
265       // f32 and f64 cases are Legal, f80 case is not
266       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
267     } else {
268       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
269       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
270     }
271   } else {
272     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
273     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
274   }
275
276   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
277   // are Legal, f80 is custom lowered.
278   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
279   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
280
281   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
282   // this operation.
283   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
284   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
285
286   if (X86ScalarSSEf32) {
287     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
288     // f32 and f64 cases are Legal, f80 case is not
289     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
290   } else {
291     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
292     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
293   }
294
295   // Handle FP_TO_UINT by promoting the destination to a larger signed
296   // conversion.
297   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
298   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
299   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
300
301   if (Subtarget->is64Bit()) {
302     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
303     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
304   } else if (!TM.Options.UseSoftFloat) {
305     // Since AVX is a superset of SSE3, only check for SSE here.
306     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
307       // Expand FP_TO_UINT into a select.
308       // FIXME: We would like to use a Custom expander here eventually to do
309       // the optimal thing for SSE vs. the default expansion in the legalizer.
310       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
311     else
312       // With SSE3 we can use fisttpll to convert to a signed i64; without
313       // SSE, we're stuck with a fistpll.
314       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
315   }
316
317   if (isTargetFTOL()) {
318     // Use the _ftol2 runtime function, which has a pseudo-instruction
319     // to handle its weird calling convention.
320     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
321   }
322
323   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
324   if (!X86ScalarSSEf64) {
325     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
326     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
327     if (Subtarget->is64Bit()) {
328       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
329       // Without SSE, i64->f64 goes through memory.
330       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
331     }
332   }
333
334   // Scalar integer divide and remainder are lowered to use operations that
335   // produce two results, to match the available instructions. This exposes
336   // the two-result form to trivial CSE, which is able to combine x/y and x%y
337   // into a single instruction.
338   //
339   // Scalar integer multiply-high is also lowered to use two-result
340   // operations, to match the available instructions. However, plain multiply
341   // (low) operations are left as Legal, as there are single-result
342   // instructions for this in x86. Using the two-result multiply instructions
343   // when both high and low results are needed must be arranged by dagcombine.
344   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
345     MVT VT = IntVTs[i];
346     setOperationAction(ISD::MULHS, VT, Expand);
347     setOperationAction(ISD::MULHU, VT, Expand);
348     setOperationAction(ISD::SDIV, VT, Expand);
349     setOperationAction(ISD::UDIV, VT, Expand);
350     setOperationAction(ISD::SREM, VT, Expand);
351     setOperationAction(ISD::UREM, VT, Expand);
352
353     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
354     setOperationAction(ISD::ADDC, VT, Custom);
355     setOperationAction(ISD::ADDE, VT, Custom);
356     setOperationAction(ISD::SUBC, VT, Custom);
357     setOperationAction(ISD::SUBE, VT, Custom);
358   }
359
360   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
361   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
362   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
363   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
364   if (Subtarget->is64Bit())
365     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
366   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
367   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
368   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
369   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
370   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
371   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
372   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
373   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
374
375   // Promote the i8 variants and force them on up to i32 which has a shorter
376   // encoding.
377   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
378   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
379   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
380   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
381   if (Subtarget->hasBMI()) {
382     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
383     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
384     if (Subtarget->is64Bit())
385       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
386   } else {
387     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
388     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
391   }
392
393   if (Subtarget->hasLZCNT()) {
394     // When promoting the i8 variants, force them to i32 for a shorter
395     // encoding.
396     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
397     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
398     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
399     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
400     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
401     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
402     if (Subtarget->is64Bit())
403       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
404   } else {
405     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
406     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
407     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
408     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
409     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
411     if (Subtarget->is64Bit()) {
412       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
413       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
414     }
415   }
416
417   if (Subtarget->hasPOPCNT()) {
418     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
419   } else {
420     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
421     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
422     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
423     if (Subtarget->is64Bit())
424       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
425   }
426
427   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
428   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
429
430   // These should be promoted to a larger select which is supported.
431   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
432   // X86 wants to expand cmov itself.
433   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
434   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
435   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
436   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
437   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
438   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
439   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
440   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
441   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
442   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
443   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
444   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
445   if (Subtarget->is64Bit()) {
446     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
447     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
448   }
449   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
450
451   // Darwin ABI issue.
452   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
453   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
454   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
455   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
456   if (Subtarget->is64Bit())
457     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
458   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
459   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
460   if (Subtarget->is64Bit()) {
461     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
462     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
463     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
464     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
465     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
466   }
467   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
468   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
469   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
470   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
471   if (Subtarget->is64Bit()) {
472     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
473     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
474     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
475   }
476
477   if (Subtarget->hasSSE1())
478     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
479
480   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
481   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
482
483   // On X86 and X86-64, atomic operations are lowered to locked instructions.
484   // Locked instructions, in turn, have implicit fence semantics (all memory
485   // operations are flushed before issuing the locked instruction, and they
486   // are not buffered), so we can fold away the common pattern of
487   // fence-atomic-fence.
488   setShouldFoldAtomicFences(true);
489
490   // Expand certain atomics
491   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
492     MVT VT = IntVTs[i];
493     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
494     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
495     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
496   }
497
498   if (!Subtarget->is64Bit()) {
499     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
500     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
501     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
503     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
505     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
507   }
508
509   if (Subtarget->hasCmpxchg16b()) {
510     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
511   }
512
513   // FIXME - use subtarget debug flags
514   if (!Subtarget->isTargetDarwin() &&
515       !Subtarget->isTargetELF() &&
516       !Subtarget->isTargetCygMing()) {
517     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
518   }
519
520   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
521   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
522   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
523   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
524   if (Subtarget->is64Bit()) {
525     setExceptionPointerRegister(X86::RAX);
526     setExceptionSelectorRegister(X86::RDX);
527   } else {
528     setExceptionPointerRegister(X86::EAX);
529     setExceptionSelectorRegister(X86::EDX);
530   }
531   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
532   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
533
534   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
535   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
536
537   setOperationAction(ISD::TRAP, MVT::Other, Legal);
538
539   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
540   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
541   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
542   if (Subtarget->is64Bit()) {
543     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
544     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
545   } else {
546     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
547     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
548   }
549
550   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
551   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
552
553   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
554     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
555                        MVT::i64 : MVT::i32, Custom);
556   else if (TM.Options.EnableSegmentedStacks)
557     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
558                        MVT::i64 : MVT::i32, Custom);
559   else
560     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
561                        MVT::i64 : MVT::i32, Expand);
562
563   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
564     // f32 and f64 use SSE.
565     // Set up the FP register classes.
566     addRegisterClass(MVT::f32, &X86::FR32RegClass);
567     addRegisterClass(MVT::f64, &X86::FR64RegClass);
568
569     // Use ANDPD to simulate FABS.
570     setOperationAction(ISD::FABS , MVT::f64, Custom);
571     setOperationAction(ISD::FABS , MVT::f32, Custom);
572
573     // Use XORP to simulate FNEG.
574     setOperationAction(ISD::FNEG , MVT::f64, Custom);
575     setOperationAction(ISD::FNEG , MVT::f32, Custom);
576
577     // Use ANDPD and ORPD to simulate FCOPYSIGN.
578     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
579     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
580
581     // Lower this to FGETSIGNx86 plus an AND.
582     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
583     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
584
585     // We don't support sin/cos/fmod
586     setOperationAction(ISD::FSIN , MVT::f64, Expand);
587     setOperationAction(ISD::FCOS , MVT::f64, Expand);
588     setOperationAction(ISD::FSIN , MVT::f32, Expand);
589     setOperationAction(ISD::FCOS , MVT::f32, Expand);
590
591     // Expand FP immediates into loads from the stack, except for the special
592     // cases we handle.
593     addLegalFPImmediate(APFloat(+0.0)); // xorpd
594     addLegalFPImmediate(APFloat(+0.0f)); // xorps
595   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
596     // Use SSE for f32, x87 for f64.
597     // Set up the FP register classes.
598     addRegisterClass(MVT::f32, &X86::FR32RegClass);
599     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
600
601     // Use ANDPS to simulate FABS.
602     setOperationAction(ISD::FABS , MVT::f32, Custom);
603
604     // Use XORP to simulate FNEG.
605     setOperationAction(ISD::FNEG , MVT::f32, Custom);
606
607     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
608
609     // Use ANDPS and ORPS to simulate FCOPYSIGN.
610     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
611     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
612
613     // We don't support sin/cos/fmod
614     setOperationAction(ISD::FSIN , MVT::f32, Expand);
615     setOperationAction(ISD::FCOS , MVT::f32, Expand);
616
617     // Special cases we handle for FP constants.
618     addLegalFPImmediate(APFloat(+0.0f)); // xorps
619     addLegalFPImmediate(APFloat(+0.0)); // FLD0
620     addLegalFPImmediate(APFloat(+1.0)); // FLD1
621     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
622     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
623
624     if (!TM.Options.UnsafeFPMath) {
625       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
626       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
627     }
628   } else if (!TM.Options.UseSoftFloat) {
629     // f32 and f64 in x87.
630     // Set up the FP register classes.
631     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
632     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
633
634     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
635     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
636     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
637     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
638
639     if (!TM.Options.UnsafeFPMath) {
640       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
641       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
642     }
643     addLegalFPImmediate(APFloat(+0.0)); // FLD0
644     addLegalFPImmediate(APFloat(+1.0)); // FLD1
645     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
646     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
647     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
648     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
649     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
650     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
651   }
652
653   // We don't support FMA.
654   setOperationAction(ISD::FMA, MVT::f64, Expand);
655   setOperationAction(ISD::FMA, MVT::f32, Expand);
656
657   // Long double always uses X87.
658   if (!TM.Options.UseSoftFloat) {
659     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
660     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
661     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
662     {
663       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
664       addLegalFPImmediate(TmpFlt);  // FLD0
665       TmpFlt.changeSign();
666       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
667
668       bool ignored;
669       APFloat TmpFlt2(+1.0);
670       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
671                       &ignored);
672       addLegalFPImmediate(TmpFlt2);  // FLD1
673       TmpFlt2.changeSign();
674       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
675     }
676
677     if (!TM.Options.UnsafeFPMath) {
678       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
679       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
680     }
681
682     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
683     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
684     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
685     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
686     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
687     setOperationAction(ISD::FMA, MVT::f80, Expand);
688   }
689
690   // Always use a library call for pow.
691   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
692   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
693   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
694
695   setOperationAction(ISD::FLOG, MVT::f80, Expand);
696   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
697   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
698   setOperationAction(ISD::FEXP, MVT::f80, Expand);
699   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
700
701   // First set operation action for all vector types to either promote
702   // (for widening) or expand (for scalarization). Then we will selectively
703   // turn on ones that can be effectively codegen'd.
704   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
705            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
706     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
721     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
723     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
724     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
758     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
763     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
764              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
765       setTruncStoreAction((MVT::SimpleValueType)VT,
766                           (MVT::SimpleValueType)InnerVT, Expand);
767     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
768     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
769     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
770   }
771
772   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
773   // with -msoft-float, disable use of MMX as well.
774   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
775     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
776     // No operations on x86mmx supported, everything uses intrinsics.
777   }
778
779   // MMX-sized vectors (other than x86mmx) are expected to be expanded
780   // into smaller operations.
781   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
782   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
783   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
784   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
785   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
786   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
787   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
788   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
789   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
790   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
791   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
792   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
793   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
794   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
795   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
796   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
797   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
798   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
799   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
800   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
801   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
802   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
803   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
804   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
805   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
806   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
807   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
808   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
809   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
810
811   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
812     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
813
814     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
815     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
816     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
817     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
818     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
819     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
820     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
821     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
822     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
823     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
824     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
825     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
826   }
827
828   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
829     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
830
831     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
832     // registers cannot be used even for integer operations.
833     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
834     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
835     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
836     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
837
838     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
839     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
840     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
841     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
842     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
843     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
844     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
845     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
846     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
847     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
848     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
849     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
850     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
851     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
852     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
853     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
854
855     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
856     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
857     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
858     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
859
860     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
861     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
862     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
863     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
864     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
865
866     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
867     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
868     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
869     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
870     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
871
872     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
873     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
874       EVT VT = (MVT::SimpleValueType)i;
875       // Do not attempt to custom lower non-power-of-2 vectors
876       if (!isPowerOf2_32(VT.getVectorNumElements()))
877         continue;
878       // Do not attempt to custom lower non-128-bit vectors
879       if (!VT.is128BitVector())
880         continue;
881       setOperationAction(ISD::BUILD_VECTOR,
882                          VT.getSimpleVT().SimpleTy, Custom);
883       setOperationAction(ISD::VECTOR_SHUFFLE,
884                          VT.getSimpleVT().SimpleTy, Custom);
885       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
886                          VT.getSimpleVT().SimpleTy, Custom);
887     }
888
889     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
890     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
891     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
892     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
893     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
894     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
895
896     if (Subtarget->is64Bit()) {
897       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
898       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
899     }
900
901     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
902     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
903       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
904       EVT VT = SVT;
905
906       // Do not attempt to promote non-128-bit vectors
907       if (!VT.is128BitVector())
908         continue;
909
910       setOperationAction(ISD::AND,    SVT, Promote);
911       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
912       setOperationAction(ISD::OR,     SVT, Promote);
913       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
914       setOperationAction(ISD::XOR,    SVT, Promote);
915       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
916       setOperationAction(ISD::LOAD,   SVT, Promote);
917       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
918       setOperationAction(ISD::SELECT, SVT, Promote);
919       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
920     }
921
922     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
923
924     // Custom lower v2i64 and v2f64 selects.
925     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
926     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
927     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
928     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
929
930     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
931     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
932   }
933
934   if (Subtarget->hasSSE41()) {
935     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
936     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
937     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
938     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
939     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
940     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
941     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
942     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
943     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
944     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
945
946     // FIXME: Do we need to handle scalar-to-vector here?
947     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
948
949     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
950     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
951     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
952     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
953     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
954
955     // i8 and i16 vectors are custom , because the source register and source
956     // source memory operand types are not the same width.  f32 vectors are
957     // custom since the immediate controlling the insert encodes additional
958     // information.
959     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
960     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
961     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
963
964     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
965     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
966     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
967     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
968
969     // FIXME: these should be Legal but thats only for the case where
970     // the index is constant.  For now custom expand to deal with that.
971     if (Subtarget->is64Bit()) {
972       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
973       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
974     }
975   }
976
977   if (Subtarget->hasSSE2()) {
978     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
979     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
980
981     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
982     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
983
984     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
985     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
986
987     if (Subtarget->hasAVX2()) {
988       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
989       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
990
991       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
992       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
993
994       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
995     } else {
996       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
997       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
998
999       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1000       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1001
1002       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1003     }
1004   }
1005
1006   if (Subtarget->hasSSE42())
1007     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
1008
1009   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1010     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1011     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1012     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1013     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1014     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1015     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1016
1017     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1018     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1019     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1020
1021     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1022     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1023     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1024     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1025     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1026     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1027
1028     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1029     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1030     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1031     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1032     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1033     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1034
1035     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1036     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1037     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1038
1039     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1040     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1041     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1042     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1043     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1044     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1045
1046     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1047     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1048
1049     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1050     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1051
1052     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1053     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1054
1055     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1056     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1057     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1058     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1059
1060     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1061     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1062     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1065     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1066     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1067     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1068
1069     if (Subtarget->hasAVX2()) {
1070       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1071       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1072       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1073       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1074
1075       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1076       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1077       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1078       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1079
1080       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1081       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1082       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1083       // Don't lower v32i8 because there is no 128-bit byte mul
1084
1085       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1086
1087       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1088       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1089
1090       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1091       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1092
1093       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1094     } else {
1095       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1096       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1097       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1098       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1099
1100       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1101       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1102       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1103       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1104
1105       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1106       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1107       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1108       // Don't lower v32i8 because there is no 128-bit byte mul
1109
1110       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1111       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1112
1113       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1114       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1115
1116       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1117     }
1118
1119     // Custom lower several nodes for 256-bit types.
1120     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1121              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1122       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1123       EVT VT = SVT;
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, SVT, 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,       SVT, Custom);
1135       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1136       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1137       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1138       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1139       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1140     }
1141
1142     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1143     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1144       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1145       EVT VT = SVT;
1146
1147       // Do not attempt to promote non-256-bit vectors
1148       if (!VT.is256BitVector())
1149         continue;
1150
1151       setOperationAction(ISD::AND,    SVT, Promote);
1152       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1153       setOperationAction(ISD::OR,     SVT, Promote);
1154       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1155       setOperationAction(ISD::XOR,    SVT, Promote);
1156       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1157       setOperationAction(ISD::LOAD,   SVT, Promote);
1158       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1159       setOperationAction(ISD::SELECT, SVT, Promote);
1160       AddPromotedToType (ISD::SELECT, SVT, 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
1175
1176   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1177   // handle type legalization for these operations here.
1178   //
1179   // FIXME: We really should do custom legalization for addition and
1180   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1181   // than generic legalization for 64-bit multiplication-with-overflow, though.
1182   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1183     // Add/Sub/Mul with overflow operations are custom lowered.
1184     MVT VT = IntVTs[i];
1185     setOperationAction(ISD::SADDO, VT, Custom);
1186     setOperationAction(ISD::UADDO, VT, Custom);
1187     setOperationAction(ISD::SSUBO, VT, Custom);
1188     setOperationAction(ISD::USUBO, VT, Custom);
1189     setOperationAction(ISD::SMULO, VT, Custom);
1190     setOperationAction(ISD::UMULO, VT, Custom);
1191   }
1192
1193   // There are no 8-bit 3-address imul/mul instructions
1194   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1195   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1196
1197   if (!Subtarget->is64Bit()) {
1198     // These libcalls are not available in 32-bit.
1199     setLibcallName(RTLIB::SHL_I128, 0);
1200     setLibcallName(RTLIB::SRL_I128, 0);
1201     setLibcallName(RTLIB::SRA_I128, 0);
1202   }
1203
1204   // We have target-specific dag combine patterns for the following nodes:
1205   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1206   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1207   setTargetDAGCombine(ISD::VSELECT);
1208   setTargetDAGCombine(ISD::SELECT);
1209   setTargetDAGCombine(ISD::SHL);
1210   setTargetDAGCombine(ISD::SRA);
1211   setTargetDAGCombine(ISD::SRL);
1212   setTargetDAGCombine(ISD::OR);
1213   setTargetDAGCombine(ISD::AND);
1214   setTargetDAGCombine(ISD::ADD);
1215   setTargetDAGCombine(ISD::FADD);
1216   setTargetDAGCombine(ISD::FSUB);
1217   setTargetDAGCombine(ISD::SUB);
1218   setTargetDAGCombine(ISD::LOAD);
1219   setTargetDAGCombine(ISD::STORE);
1220   setTargetDAGCombine(ISD::ZERO_EXTEND);
1221   setTargetDAGCombine(ISD::ANY_EXTEND);
1222   setTargetDAGCombine(ISD::SIGN_EXTEND);
1223   setTargetDAGCombine(ISD::TRUNCATE);
1224   setTargetDAGCombine(ISD::UINT_TO_FP);
1225   setTargetDAGCombine(ISD::SINT_TO_FP);
1226   setTargetDAGCombine(ISD::SETCC);
1227   setTargetDAGCombine(ISD::FP_TO_SINT);
1228   if (Subtarget->is64Bit())
1229     setTargetDAGCombine(ISD::MUL);
1230   if (Subtarget->hasBMI())
1231     setTargetDAGCombine(ISD::XOR);
1232
1233   computeRegisterProperties();
1234
1235   // On Darwin, -Os means optimize for size without hurting performance,
1236   // do not reduce the limit.
1237   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1238   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1239   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1240   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1241   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1242   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1243   setPrefLoopAlignment(4); // 2^4 bytes.
1244   benefitFromCodePlacementOpt = true;
1245
1246   // Predictable cmov don't hurt on atom because it's in-order.
1247   predictableSelectIsExpensive = !Subtarget->isAtom();
1248
1249   setPrefFunctionAlignment(4); // 2^4 bytes.
1250 }
1251
1252
1253 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1254   if (!VT.isVector()) return MVT::i8;
1255   return VT.changeVectorElementTypeToInteger();
1256 }
1257
1258
1259 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1260 /// the desired ByVal argument alignment.
1261 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1262   if (MaxAlign == 16)
1263     return;
1264   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1265     if (VTy->getBitWidth() == 128)
1266       MaxAlign = 16;
1267   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1268     unsigned EltAlign = 0;
1269     getMaxByValAlign(ATy->getElementType(), EltAlign);
1270     if (EltAlign > MaxAlign)
1271       MaxAlign = EltAlign;
1272   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1273     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1274       unsigned EltAlign = 0;
1275       getMaxByValAlign(STy->getElementType(i), EltAlign);
1276       if (EltAlign > MaxAlign)
1277         MaxAlign = EltAlign;
1278       if (MaxAlign == 16)
1279         break;
1280     }
1281   }
1282 }
1283
1284 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1285 /// function arguments in the caller parameter area. For X86, aggregates
1286 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1287 /// are at 4-byte boundaries.
1288 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1289   if (Subtarget->is64Bit()) {
1290     // Max of 8 and alignment of type.
1291     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1292     if (TyAlign > 8)
1293       return TyAlign;
1294     return 8;
1295   }
1296
1297   unsigned Align = 4;
1298   if (Subtarget->hasSSE1())
1299     getMaxByValAlign(Ty, Align);
1300   return Align;
1301 }
1302
1303 /// getOptimalMemOpType - Returns the target specific optimal type for load
1304 /// and store operations as a result of memset, memcpy, and memmove
1305 /// lowering. If DstAlign is zero that means it's safe to destination
1306 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1307 /// means there isn't a need to check it against alignment requirement,
1308 /// probably because the source does not need to be loaded. If
1309 /// 'IsZeroVal' is true, that means it's safe to return a
1310 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1311 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1312 /// constant so it does not need to be loaded.
1313 /// It returns EVT::Other if the type should be determined using generic
1314 /// target-independent logic.
1315 EVT
1316 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1317                                        unsigned DstAlign, unsigned SrcAlign,
1318                                        bool IsZeroVal,
1319                                        bool MemcpyStrSrc,
1320                                        MachineFunction &MF) const {
1321   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1322   // linux.  This is because the stack realignment code can't handle certain
1323   // cases like PR2962.  This should be removed when PR2962 is fixed.
1324   const Function *F = MF.getFunction();
1325   if (IsZeroVal &&
1326       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1327     if (Size >= 16 &&
1328         (Subtarget->isUnalignedMemAccessFast() ||
1329          ((DstAlign == 0 || DstAlign >= 16) &&
1330           (SrcAlign == 0 || SrcAlign >= 16))) &&
1331         Subtarget->getStackAlignment() >= 16) {
1332       if (Subtarget->getStackAlignment() >= 32) {
1333         if (Subtarget->hasAVX2())
1334           return MVT::v8i32;
1335         if (Subtarget->hasAVX())
1336           return MVT::v8f32;
1337       }
1338       if (Subtarget->hasSSE2())
1339         return MVT::v4i32;
1340       if (Subtarget->hasSSE1())
1341         return MVT::v4f32;
1342     } else if (!MemcpyStrSrc && Size >= 8 &&
1343                !Subtarget->is64Bit() &&
1344                Subtarget->getStackAlignment() >= 8 &&
1345                Subtarget->hasSSE2()) {
1346       // Do not use f64 to lower memcpy if source is string constant. It's
1347       // better to use i32 to avoid the loads.
1348       return MVT::f64;
1349     }
1350   }
1351   if (Subtarget->is64Bit() && Size >= 8)
1352     return MVT::i64;
1353   return MVT::i32;
1354 }
1355
1356 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1357 /// current function.  The returned value is a member of the
1358 /// MachineJumpTableInfo::JTEntryKind enum.
1359 unsigned X86TargetLowering::getJumpTableEncoding() const {
1360   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1361   // symbol.
1362   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1363       Subtarget->isPICStyleGOT())
1364     return MachineJumpTableInfo::EK_Custom32;
1365
1366   // Otherwise, use the normal jump table encoding heuristics.
1367   return TargetLowering::getJumpTableEncoding();
1368 }
1369
1370 const MCExpr *
1371 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1372                                              const MachineBasicBlock *MBB,
1373                                              unsigned uid,MCContext &Ctx) const{
1374   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1375          Subtarget->isPICStyleGOT());
1376   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1377   // entries.
1378   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1379                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1380 }
1381
1382 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1383 /// jumptable.
1384 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1385                                                     SelectionDAG &DAG) const {
1386   if (!Subtarget->is64Bit())
1387     // This doesn't have DebugLoc associated with it, but is not really the
1388     // same as a Register.
1389     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1390   return Table;
1391 }
1392
1393 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1394 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1395 /// MCExpr.
1396 const MCExpr *X86TargetLowering::
1397 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1398                              MCContext &Ctx) const {
1399   // X86-64 uses RIP relative addressing based on the jump table label.
1400   if (Subtarget->isPICStyleRIPRel())
1401     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1402
1403   // Otherwise, the reference is relative to the PIC base.
1404   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1405 }
1406
1407 // FIXME: Why this routine is here? Move to RegInfo!
1408 std::pair<const TargetRegisterClass*, uint8_t>
1409 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1410   const TargetRegisterClass *RRC = 0;
1411   uint8_t Cost = 1;
1412   switch (VT.getSimpleVT().SimpleTy) {
1413   default:
1414     return TargetLowering::findRepresentativeClass(VT);
1415   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1416     RRC = Subtarget->is64Bit() ?
1417       (const TargetRegisterClass*)&X86::GR64RegClass :
1418       (const TargetRegisterClass*)&X86::GR32RegClass;
1419     break;
1420   case MVT::x86mmx:
1421     RRC = &X86::VR64RegClass;
1422     break;
1423   case MVT::f32: case MVT::f64:
1424   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1425   case MVT::v4f32: case MVT::v2f64:
1426   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1427   case MVT::v4f64:
1428     RRC = &X86::VR128RegClass;
1429     break;
1430   }
1431   return std::make_pair(RRC, Cost);
1432 }
1433
1434 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1435                                                unsigned &Offset) const {
1436   if (!Subtarget->isTargetLinux())
1437     return false;
1438
1439   if (Subtarget->is64Bit()) {
1440     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1441     Offset = 0x28;
1442     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1443       AddressSpace = 256;
1444     else
1445       AddressSpace = 257;
1446   } else {
1447     // %gs:0x14 on i386
1448     Offset = 0x14;
1449     AddressSpace = 256;
1450   }
1451   return true;
1452 }
1453
1454
1455 //===----------------------------------------------------------------------===//
1456 //               Return Value Calling Convention Implementation
1457 //===----------------------------------------------------------------------===//
1458
1459 #include "X86GenCallingConv.inc"
1460
1461 bool
1462 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1463                                   MachineFunction &MF, bool isVarArg,
1464                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1465                         LLVMContext &Context) const {
1466   SmallVector<CCValAssign, 16> RVLocs;
1467   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1468                  RVLocs, Context);
1469   return CCInfo.CheckReturn(Outs, RetCC_X86);
1470 }
1471
1472 SDValue
1473 X86TargetLowering::LowerReturn(SDValue Chain,
1474                                CallingConv::ID CallConv, bool isVarArg,
1475                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1476                                const SmallVectorImpl<SDValue> &OutVals,
1477                                DebugLoc dl, SelectionDAG &DAG) const {
1478   MachineFunction &MF = DAG.getMachineFunction();
1479   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1480
1481   SmallVector<CCValAssign, 16> RVLocs;
1482   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1483                  RVLocs, *DAG.getContext());
1484   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1485
1486   // Add the regs to the liveout set for the function.
1487   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1488   for (unsigned i = 0; i != RVLocs.size(); ++i)
1489     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1490       MRI.addLiveOut(RVLocs[i].getLocReg());
1491
1492   SDValue Flag;
1493
1494   SmallVector<SDValue, 6> RetOps;
1495   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1496   // Operand #1 = Bytes To Pop
1497   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1498                    MVT::i16));
1499
1500   // Copy the result values into the output registers.
1501   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1502     CCValAssign &VA = RVLocs[i];
1503     assert(VA.isRegLoc() && "Can only return in registers!");
1504     SDValue ValToCopy = OutVals[i];
1505     EVT ValVT = ValToCopy.getValueType();
1506
1507     // Promote values to the appropriate types
1508     if (VA.getLocInfo() == CCValAssign::SExt)
1509       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1510     else if (VA.getLocInfo() == CCValAssign::ZExt)
1511       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1512     else if (VA.getLocInfo() == CCValAssign::AExt)
1513       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1514     else if (VA.getLocInfo() == CCValAssign::BCvt)
1515       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1516
1517     // If this is x86-64, and we disabled SSE, we can't return FP values,
1518     // or SSE or MMX vectors.
1519     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1520          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1521           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1522       report_fatal_error("SSE register return with SSE disabled");
1523     }
1524     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1525     // llvm-gcc has never done it right and no one has noticed, so this
1526     // should be OK for now.
1527     if (ValVT == MVT::f64 &&
1528         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1529       report_fatal_error("SSE2 register return with SSE2 disabled");
1530
1531     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1532     // the RET instruction and handled by the FP Stackifier.
1533     if (VA.getLocReg() == X86::ST0 ||
1534         VA.getLocReg() == X86::ST1) {
1535       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1536       // change the value to the FP stack register class.
1537       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1538         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1539       RetOps.push_back(ValToCopy);
1540       // Don't emit a copytoreg.
1541       continue;
1542     }
1543
1544     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1545     // which is returned in RAX / RDX.
1546     if (Subtarget->is64Bit()) {
1547       if (ValVT == MVT::x86mmx) {
1548         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1549           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1550           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1551                                   ValToCopy);
1552           // If we don't have SSE2 available, convert to v4f32 so the generated
1553           // register is legal.
1554           if (!Subtarget->hasSSE2())
1555             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1556         }
1557       }
1558     }
1559
1560     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1561     Flag = Chain.getValue(1);
1562   }
1563
1564   // The x86-64 ABI for returning structs by value requires that we copy
1565   // the sret argument into %rax for the return. We saved the argument into
1566   // a virtual register in the entry block, so now we copy the value out
1567   // and into %rax.
1568   if (Subtarget->is64Bit() &&
1569       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1570     MachineFunction &MF = DAG.getMachineFunction();
1571     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1572     unsigned Reg = FuncInfo->getSRetReturnReg();
1573     assert(Reg &&
1574            "SRetReturnReg should have been set in LowerFormalArguments().");
1575     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1576
1577     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1578     Flag = Chain.getValue(1);
1579
1580     // RAX now acts like a return value.
1581     MRI.addLiveOut(X86::RAX);
1582   }
1583
1584   RetOps[0] = Chain;  // Update chain.
1585
1586   // Add the flag if we have it.
1587   if (Flag.getNode())
1588     RetOps.push_back(Flag);
1589
1590   return DAG.getNode(X86ISD::RET_FLAG, dl,
1591                      MVT::Other, &RetOps[0], RetOps.size());
1592 }
1593
1594 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1595   if (N->getNumValues() != 1)
1596     return false;
1597   if (!N->hasNUsesOfValue(1, 0))
1598     return false;
1599
1600   SDValue TCChain = Chain;
1601   SDNode *Copy = *N->use_begin();
1602   if (Copy->getOpcode() == ISD::CopyToReg) {
1603     // If the copy has a glue operand, we conservatively assume it isn't safe to
1604     // perform a tail call.
1605     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1606       return false;
1607     TCChain = Copy->getOperand(0);
1608   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1609     return false;
1610
1611   bool HasRet = false;
1612   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1613        UI != UE; ++UI) {
1614     if (UI->getOpcode() != X86ISD::RET_FLAG)
1615       return false;
1616     HasRet = true;
1617   }
1618
1619   if (!HasRet)
1620     return false;
1621
1622   Chain = TCChain;
1623   return true;
1624 }
1625
1626 EVT
1627 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1628                                             ISD::NodeType ExtendKind) const {
1629   MVT ReturnMVT;
1630   // TODO: Is this also valid on 32-bit?
1631   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1632     ReturnMVT = MVT::i8;
1633   else
1634     ReturnMVT = MVT::i32;
1635
1636   EVT MinVT = getRegisterType(Context, ReturnMVT);
1637   return VT.bitsLT(MinVT) ? MinVT : VT;
1638 }
1639
1640 /// LowerCallResult - Lower the result values of a call into the
1641 /// appropriate copies out of appropriate physical registers.
1642 ///
1643 SDValue
1644 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1645                                    CallingConv::ID CallConv, bool isVarArg,
1646                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1647                                    DebugLoc dl, SelectionDAG &DAG,
1648                                    SmallVectorImpl<SDValue> &InVals) const {
1649
1650   // Assign locations to each value returned by this call.
1651   SmallVector<CCValAssign, 16> RVLocs;
1652   bool Is64Bit = Subtarget->is64Bit();
1653   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1654                  getTargetMachine(), RVLocs, *DAG.getContext());
1655   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1656
1657   // Copy all of the result registers out of their specified physreg.
1658   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1659     CCValAssign &VA = RVLocs[i];
1660     EVT CopyVT = VA.getValVT();
1661
1662     // If this is x86-64, and we disabled SSE, we can't return FP values
1663     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1664         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1665       report_fatal_error("SSE register return with SSE disabled");
1666     }
1667
1668     SDValue Val;
1669
1670     // If this is a call to a function that returns an fp value on the floating
1671     // point stack, we must guarantee the the value is popped from the stack, so
1672     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1673     // if the return value is not used. We use the FpPOP_RETVAL instruction
1674     // instead.
1675     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1676       // If we prefer to use the value in xmm registers, copy it out as f80 and
1677       // use a truncate to move it from fp stack reg to xmm reg.
1678       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1679       SDValue Ops[] = { Chain, InFlag };
1680       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1681                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1682       Val = Chain.getValue(0);
1683
1684       // Round the f80 to the right size, which also moves it to the appropriate
1685       // xmm register.
1686       if (CopyVT != VA.getValVT())
1687         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1688                           // This truncation won't change the value.
1689                           DAG.getIntPtrConstant(1));
1690     } else {
1691       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1692                                  CopyVT, InFlag).getValue(1);
1693       Val = Chain.getValue(0);
1694     }
1695     InFlag = Chain.getValue(2);
1696     InVals.push_back(Val);
1697   }
1698
1699   return Chain;
1700 }
1701
1702
1703 //===----------------------------------------------------------------------===//
1704 //                C & StdCall & Fast Calling Convention implementation
1705 //===----------------------------------------------------------------------===//
1706 //  StdCall calling convention seems to be standard for many Windows' API
1707 //  routines and around. It differs from C calling convention just a little:
1708 //  callee should clean up the stack, not caller. Symbols should be also
1709 //  decorated in some fancy way :) It doesn't support any vector arguments.
1710 //  For info on fast calling convention see Fast Calling Convention (tail call)
1711 //  implementation LowerX86_32FastCCCallTo.
1712
1713 /// CallIsStructReturn - Determines whether a call uses struct return
1714 /// semantics.
1715 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1716   if (Outs.empty())
1717     return false;
1718
1719   return Outs[0].Flags.isSRet();
1720 }
1721
1722 /// ArgsAreStructReturn - Determines whether a function uses struct
1723 /// return semantics.
1724 static bool
1725 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1726   if (Ins.empty())
1727     return false;
1728
1729   return Ins[0].Flags.isSRet();
1730 }
1731
1732 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1733 /// by "Src" to address "Dst" with size and alignment information specified by
1734 /// the specific parameter attribute. The copy will be passed as a byval
1735 /// function parameter.
1736 static SDValue
1737 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1738                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1739                           DebugLoc dl) {
1740   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1741
1742   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1743                        /*isVolatile*/false, /*AlwaysInline=*/true,
1744                        MachinePointerInfo(), MachinePointerInfo());
1745 }
1746
1747 /// IsTailCallConvention - Return true if the calling convention is one that
1748 /// supports tail call optimization.
1749 static bool IsTailCallConvention(CallingConv::ID CC) {
1750   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1751 }
1752
1753 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1754   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1755     return false;
1756
1757   CallSite CS(CI);
1758   CallingConv::ID CalleeCC = CS.getCallingConv();
1759   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1760     return false;
1761
1762   return true;
1763 }
1764
1765 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1766 /// a tailcall target by changing its ABI.
1767 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1768                                    bool GuaranteedTailCallOpt) {
1769   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1770 }
1771
1772 SDValue
1773 X86TargetLowering::LowerMemArgument(SDValue Chain,
1774                                     CallingConv::ID CallConv,
1775                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1776                                     DebugLoc dl, SelectionDAG &DAG,
1777                                     const CCValAssign &VA,
1778                                     MachineFrameInfo *MFI,
1779                                     unsigned i) const {
1780   // Create the nodes corresponding to a load from this parameter slot.
1781   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1782   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1783                               getTargetMachine().Options.GuaranteedTailCallOpt);
1784   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1785   EVT ValVT;
1786
1787   // If value is passed by pointer we have address passed instead of the value
1788   // itself.
1789   if (VA.getLocInfo() == CCValAssign::Indirect)
1790     ValVT = VA.getLocVT();
1791   else
1792     ValVT = VA.getValVT();
1793
1794   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1795   // changed with more analysis.
1796   // In case of tail call optimization mark all arguments mutable. Since they
1797   // could be overwritten by lowering of arguments in case of a tail call.
1798   if (Flags.isByVal()) {
1799     unsigned Bytes = Flags.getByValSize();
1800     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1801     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1802     return DAG.getFrameIndex(FI, getPointerTy());
1803   } else {
1804     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1805                                     VA.getLocMemOffset(), isImmutable);
1806     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1807     return DAG.getLoad(ValVT, dl, Chain, FIN,
1808                        MachinePointerInfo::getFixedStack(FI),
1809                        false, false, false, 0);
1810   }
1811 }
1812
1813 SDValue
1814 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1815                                         CallingConv::ID CallConv,
1816                                         bool isVarArg,
1817                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1818                                         DebugLoc dl,
1819                                         SelectionDAG &DAG,
1820                                         SmallVectorImpl<SDValue> &InVals)
1821                                           const {
1822   MachineFunction &MF = DAG.getMachineFunction();
1823   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1824
1825   const Function* Fn = MF.getFunction();
1826   if (Fn->hasExternalLinkage() &&
1827       Subtarget->isTargetCygMing() &&
1828       Fn->getName() == "main")
1829     FuncInfo->setForceFramePointer(true);
1830
1831   MachineFrameInfo *MFI = MF.getFrameInfo();
1832   bool Is64Bit = Subtarget->is64Bit();
1833   bool IsWindows = Subtarget->isTargetWindows();
1834   bool IsWin64 = Subtarget->isTargetWin64();
1835
1836   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1837          "Var args not supported with calling convention fastcc or ghc");
1838
1839   // Assign locations to all of the incoming arguments.
1840   SmallVector<CCValAssign, 16> ArgLocs;
1841   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1842                  ArgLocs, *DAG.getContext());
1843
1844   // Allocate shadow area for Win64
1845   if (IsWin64) {
1846     CCInfo.AllocateStack(32, 8);
1847   }
1848
1849   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1850
1851   unsigned LastVal = ~0U;
1852   SDValue ArgValue;
1853   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1854     CCValAssign &VA = ArgLocs[i];
1855     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1856     // places.
1857     assert(VA.getValNo() != LastVal &&
1858            "Don't support value assigned to multiple locs yet");
1859     (void)LastVal;
1860     LastVal = VA.getValNo();
1861
1862     if (VA.isRegLoc()) {
1863       EVT RegVT = VA.getLocVT();
1864       const TargetRegisterClass *RC;
1865       if (RegVT == MVT::i32)
1866         RC = &X86::GR32RegClass;
1867       else if (Is64Bit && RegVT == MVT::i64)
1868         RC = &X86::GR64RegClass;
1869       else if (RegVT == MVT::f32)
1870         RC = &X86::FR32RegClass;
1871       else if (RegVT == MVT::f64)
1872         RC = &X86::FR64RegClass;
1873       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1874         RC = &X86::VR256RegClass;
1875       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1876         RC = &X86::VR128RegClass;
1877       else if (RegVT == MVT::x86mmx)
1878         RC = &X86::VR64RegClass;
1879       else
1880         llvm_unreachable("Unknown argument type!");
1881
1882       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1883       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1884
1885       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1886       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1887       // right size.
1888       if (VA.getLocInfo() == CCValAssign::SExt)
1889         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1890                                DAG.getValueType(VA.getValVT()));
1891       else if (VA.getLocInfo() == CCValAssign::ZExt)
1892         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1893                                DAG.getValueType(VA.getValVT()));
1894       else if (VA.getLocInfo() == CCValAssign::BCvt)
1895         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1896
1897       if (VA.isExtInLoc()) {
1898         // Handle MMX values passed in XMM regs.
1899         if (RegVT.isVector()) {
1900           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1901                                  ArgValue);
1902         } else
1903           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1904       }
1905     } else {
1906       assert(VA.isMemLoc());
1907       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1908     }
1909
1910     // If value is passed via pointer - do a load.
1911     if (VA.getLocInfo() == CCValAssign::Indirect)
1912       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1913                              MachinePointerInfo(), false, false, false, 0);
1914
1915     InVals.push_back(ArgValue);
1916   }
1917
1918   // The x86-64 ABI for returning structs by value requires that we copy
1919   // the sret argument into %rax for the return. Save the argument into
1920   // a virtual register so that we can access it from the return points.
1921   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1922     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1923     unsigned Reg = FuncInfo->getSRetReturnReg();
1924     if (!Reg) {
1925       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1926       FuncInfo->setSRetReturnReg(Reg);
1927     }
1928     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1929     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1930   }
1931
1932   unsigned StackSize = CCInfo.getNextStackOffset();
1933   // Align stack specially for tail calls.
1934   if (FuncIsMadeTailCallSafe(CallConv,
1935                              MF.getTarget().Options.GuaranteedTailCallOpt))
1936     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1937
1938   // If the function takes variable number of arguments, make a frame index for
1939   // the start of the first vararg value... for expansion of llvm.va_start.
1940   if (isVarArg) {
1941     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1942                     CallConv != CallingConv::X86_ThisCall)) {
1943       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1944     }
1945     if (Is64Bit) {
1946       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1947
1948       // FIXME: We should really autogenerate these arrays
1949       static const uint16_t GPR64ArgRegsWin64[] = {
1950         X86::RCX, X86::RDX, X86::R8,  X86::R9
1951       };
1952       static const uint16_t GPR64ArgRegs64Bit[] = {
1953         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1954       };
1955       static const uint16_t XMMArgRegs64Bit[] = {
1956         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1957         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1958       };
1959       const uint16_t *GPR64ArgRegs;
1960       unsigned NumXMMRegs = 0;
1961
1962       if (IsWin64) {
1963         // The XMM registers which might contain var arg parameters are shadowed
1964         // in their paired GPR.  So we only need to save the GPR to their home
1965         // slots.
1966         TotalNumIntRegs = 4;
1967         GPR64ArgRegs = GPR64ArgRegsWin64;
1968       } else {
1969         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1970         GPR64ArgRegs = GPR64ArgRegs64Bit;
1971
1972         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1973                                                 TotalNumXMMRegs);
1974       }
1975       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1976                                                        TotalNumIntRegs);
1977
1978       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1979       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1980              "SSE register cannot be used when SSE is disabled!");
1981       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1982                NoImplicitFloatOps) &&
1983              "SSE register cannot be used when SSE is disabled!");
1984       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1985           !Subtarget->hasSSE1())
1986         // Kernel mode asks for SSE to be disabled, so don't push them
1987         // on the stack.
1988         TotalNumXMMRegs = 0;
1989
1990       if (IsWin64) {
1991         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1992         // Get to the caller-allocated home save location.  Add 8 to account
1993         // for the return address.
1994         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1995         FuncInfo->setRegSaveFrameIndex(
1996           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1997         // Fixup to set vararg frame on shadow area (4 x i64).
1998         if (NumIntRegs < 4)
1999           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2000       } else {
2001         // For X86-64, if there are vararg parameters that are passed via
2002         // registers, then we must store them to their spots on the stack so
2003         // they may be loaded by deferencing the result of va_next.
2004         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2005         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2006         FuncInfo->setRegSaveFrameIndex(
2007           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2008                                false));
2009       }
2010
2011       // Store the integer parameter registers.
2012       SmallVector<SDValue, 8> MemOps;
2013       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2014                                         getPointerTy());
2015       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2016       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2017         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2018                                   DAG.getIntPtrConstant(Offset));
2019         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2020                                      &X86::GR64RegClass);
2021         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2022         SDValue Store =
2023           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2024                        MachinePointerInfo::getFixedStack(
2025                          FuncInfo->getRegSaveFrameIndex(), Offset),
2026                        false, false, 0);
2027         MemOps.push_back(Store);
2028         Offset += 8;
2029       }
2030
2031       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2032         // Now store the XMM (fp + vector) parameter registers.
2033         SmallVector<SDValue, 11> SaveXMMOps;
2034         SaveXMMOps.push_back(Chain);
2035
2036         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2037         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2038         SaveXMMOps.push_back(ALVal);
2039
2040         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2041                                FuncInfo->getRegSaveFrameIndex()));
2042         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2043                                FuncInfo->getVarArgsFPOffset()));
2044
2045         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2046           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2047                                        &X86::VR128RegClass);
2048           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2049           SaveXMMOps.push_back(Val);
2050         }
2051         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2052                                      MVT::Other,
2053                                      &SaveXMMOps[0], SaveXMMOps.size()));
2054       }
2055
2056       if (!MemOps.empty())
2057         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2058                             &MemOps[0], MemOps.size());
2059     }
2060   }
2061
2062   // Some CCs need callee pop.
2063   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2064                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2065     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2066   } else {
2067     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2068     // If this is an sret function, the return should pop the hidden pointer.
2069     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2070         ArgsAreStructReturn(Ins))
2071       FuncInfo->setBytesToPopOnReturn(4);
2072   }
2073
2074   if (!Is64Bit) {
2075     // RegSaveFrameIndex is X86-64 only.
2076     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2077     if (CallConv == CallingConv::X86_FastCall ||
2078         CallConv == CallingConv::X86_ThisCall)
2079       // fastcc functions can't have varargs.
2080       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2081   }
2082
2083   FuncInfo->setArgumentStackSize(StackSize);
2084
2085   return Chain;
2086 }
2087
2088 SDValue
2089 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2090                                     SDValue StackPtr, SDValue Arg,
2091                                     DebugLoc dl, SelectionDAG &DAG,
2092                                     const CCValAssign &VA,
2093                                     ISD::ArgFlagsTy Flags) const {
2094   unsigned LocMemOffset = VA.getLocMemOffset();
2095   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2096   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2097   if (Flags.isByVal())
2098     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2099
2100   return DAG.getStore(Chain, dl, Arg, PtrOff,
2101                       MachinePointerInfo::getStack(LocMemOffset),
2102                       false, false, 0);
2103 }
2104
2105 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2106 /// optimization is performed and it is required.
2107 SDValue
2108 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2109                                            SDValue &OutRetAddr, SDValue Chain,
2110                                            bool IsTailCall, bool Is64Bit,
2111                                            int FPDiff, DebugLoc dl) const {
2112   // Adjust the Return address stack slot.
2113   EVT VT = getPointerTy();
2114   OutRetAddr = getReturnAddressFrameIndex(DAG);
2115
2116   // Load the "old" Return address.
2117   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2118                            false, false, false, 0);
2119   return SDValue(OutRetAddr.getNode(), 1);
2120 }
2121
2122 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2123 /// optimization is performed and it is required (FPDiff!=0).
2124 static SDValue
2125 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2126                          SDValue Chain, SDValue RetAddrFrIdx,
2127                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2128   // Store the return address to the appropriate stack slot.
2129   if (!FPDiff) return Chain;
2130   // Calculate the new stack slot for the return address.
2131   int SlotSize = Is64Bit ? 8 : 4;
2132   int NewReturnAddrFI =
2133     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2134   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2135   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2136   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2137                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2138                        false, false, 0);
2139   return Chain;
2140 }
2141
2142 SDValue
2143 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2144                              SmallVectorImpl<SDValue> &InVals) const {
2145   SelectionDAG &DAG                     = CLI.DAG;
2146   DebugLoc &dl                          = CLI.DL;
2147   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2148   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2149   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2150   SDValue Chain                         = CLI.Chain;
2151   SDValue Callee                        = CLI.Callee;
2152   CallingConv::ID CallConv              = CLI.CallConv;
2153   bool &isTailCall                      = CLI.IsTailCall;
2154   bool isVarArg                         = CLI.IsVarArg;
2155
2156   MachineFunction &MF = DAG.getMachineFunction();
2157   bool Is64Bit        = Subtarget->is64Bit();
2158   bool IsWin64        = Subtarget->isTargetWin64();
2159   bool IsWindows      = Subtarget->isTargetWindows();
2160   bool IsStructRet    = CallIsStructReturn(Outs);
2161   bool IsSibcall      = false;
2162
2163   if (MF.getTarget().Options.DisableTailCalls)
2164     isTailCall = false;
2165
2166   if (isTailCall) {
2167     // Check if it's really possible to do a tail call.
2168     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2169                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2170                                                    Outs, OutVals, Ins, DAG);
2171
2172     // Sibcalls are automatically detected tailcalls which do not require
2173     // ABI changes.
2174     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2175       IsSibcall = true;
2176
2177     if (isTailCall)
2178       ++NumTailCalls;
2179   }
2180
2181   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2182          "Var args not supported with calling convention fastcc or ghc");
2183
2184   // Analyze operands of the call, assigning locations to each operand.
2185   SmallVector<CCValAssign, 16> ArgLocs;
2186   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2187                  ArgLocs, *DAG.getContext());
2188
2189   // Allocate shadow area for Win64
2190   if (IsWin64) {
2191     CCInfo.AllocateStack(32, 8);
2192   }
2193
2194   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2195
2196   // Get a count of how many bytes are to be pushed on the stack.
2197   unsigned NumBytes = CCInfo.getNextStackOffset();
2198   if (IsSibcall)
2199     // This is a sibcall. The memory operands are available in caller's
2200     // own caller's stack.
2201     NumBytes = 0;
2202   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2203            IsTailCallConvention(CallConv))
2204     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2205
2206   int FPDiff = 0;
2207   if (isTailCall && !IsSibcall) {
2208     // Lower arguments at fp - stackoffset + fpdiff.
2209     unsigned NumBytesCallerPushed =
2210       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2211     FPDiff = NumBytesCallerPushed - NumBytes;
2212
2213     // Set the delta of movement of the returnaddr stackslot.
2214     // But only set if delta is greater than previous delta.
2215     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2216       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2217   }
2218
2219   if (!IsSibcall)
2220     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2221
2222   SDValue RetAddrFrIdx;
2223   // Load return address for tail calls.
2224   if (isTailCall && FPDiff)
2225     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2226                                     Is64Bit, FPDiff, dl);
2227
2228   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2229   SmallVector<SDValue, 8> MemOpChains;
2230   SDValue StackPtr;
2231
2232   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2233   // of tail call optimization arguments are handle later.
2234   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2235     CCValAssign &VA = ArgLocs[i];
2236     EVT RegVT = VA.getLocVT();
2237     SDValue Arg = OutVals[i];
2238     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2239     bool isByVal = Flags.isByVal();
2240
2241     // Promote the value if needed.
2242     switch (VA.getLocInfo()) {
2243     default: llvm_unreachable("Unknown loc info!");
2244     case CCValAssign::Full: break;
2245     case CCValAssign::SExt:
2246       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2247       break;
2248     case CCValAssign::ZExt:
2249       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2250       break;
2251     case CCValAssign::AExt:
2252       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2253         // Special case: passing MMX values in XMM registers.
2254         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2255         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2256         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2257       } else
2258         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2259       break;
2260     case CCValAssign::BCvt:
2261       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2262       break;
2263     case CCValAssign::Indirect: {
2264       // Store the argument.
2265       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2266       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2267       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2268                            MachinePointerInfo::getFixedStack(FI),
2269                            false, false, 0);
2270       Arg = SpillSlot;
2271       break;
2272     }
2273     }
2274
2275     if (VA.isRegLoc()) {
2276       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2277       if (isVarArg && IsWin64) {
2278         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2279         // shadow reg if callee is a varargs function.
2280         unsigned ShadowReg = 0;
2281         switch (VA.getLocReg()) {
2282         case X86::XMM0: ShadowReg = X86::RCX; break;
2283         case X86::XMM1: ShadowReg = X86::RDX; break;
2284         case X86::XMM2: ShadowReg = X86::R8; break;
2285         case X86::XMM3: ShadowReg = X86::R9; break;
2286         }
2287         if (ShadowReg)
2288           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2289       }
2290     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2291       assert(VA.isMemLoc());
2292       if (StackPtr.getNode() == 0)
2293         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2294       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2295                                              dl, DAG, VA, Flags));
2296     }
2297   }
2298
2299   if (!MemOpChains.empty())
2300     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2301                         &MemOpChains[0], MemOpChains.size());
2302
2303   // Build a sequence of copy-to-reg nodes chained together with token chain
2304   // and flag operands which copy the outgoing args into registers.
2305   SDValue InFlag;
2306   // Tail call byval lowering might overwrite argument registers so in case of
2307   // tail call optimization the copies to registers are lowered later.
2308   if (!isTailCall)
2309     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2310       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2311                                RegsToPass[i].second, InFlag);
2312       InFlag = Chain.getValue(1);
2313     }
2314
2315   if (Subtarget->isPICStyleGOT()) {
2316     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2317     // GOT pointer.
2318     if (!isTailCall) {
2319       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2320                                DAG.getNode(X86ISD::GlobalBaseReg,
2321                                            DebugLoc(), getPointerTy()),
2322                                InFlag);
2323       InFlag = Chain.getValue(1);
2324     } else {
2325       // If we are tail calling and generating PIC/GOT style code load the
2326       // address of the callee into ECX. The value in ecx is used as target of
2327       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2328       // for tail calls on PIC/GOT architectures. Normally we would just put the
2329       // address of GOT into ebx and then call target@PLT. But for tail calls
2330       // ebx would be restored (since ebx is callee saved) before jumping to the
2331       // target@PLT.
2332
2333       // Note: The actual moving to ECX is done further down.
2334       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2335       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2336           !G->getGlobal()->hasProtectedVisibility())
2337         Callee = LowerGlobalAddress(Callee, DAG);
2338       else if (isa<ExternalSymbolSDNode>(Callee))
2339         Callee = LowerExternalSymbol(Callee, DAG);
2340     }
2341   }
2342
2343   if (Is64Bit && isVarArg && !IsWin64) {
2344     // From AMD64 ABI document:
2345     // For calls that may call functions that use varargs or stdargs
2346     // (prototype-less calls or calls to functions containing ellipsis (...) in
2347     // the declaration) %al is used as hidden argument to specify the number
2348     // of SSE registers used. The contents of %al do not need to match exactly
2349     // the number of registers, but must be an ubound on the number of SSE
2350     // registers used and is in the range 0 - 8 inclusive.
2351
2352     // Count the number of XMM registers allocated.
2353     static const uint16_t XMMArgRegs[] = {
2354       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2355       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2356     };
2357     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2358     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2359            && "SSE registers cannot be used when SSE is disabled");
2360
2361     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2362                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2363     InFlag = Chain.getValue(1);
2364   }
2365
2366
2367   // For tail calls lower the arguments to the 'real' stack slot.
2368   if (isTailCall) {
2369     // Force all the incoming stack arguments to be loaded from the stack
2370     // before any new outgoing arguments are stored to the stack, because the
2371     // outgoing stack slots may alias the incoming argument stack slots, and
2372     // the alias isn't otherwise explicit. This is slightly more conservative
2373     // than necessary, because it means that each store effectively depends
2374     // on every argument instead of just those arguments it would clobber.
2375     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2376
2377     SmallVector<SDValue, 8> MemOpChains2;
2378     SDValue FIN;
2379     int FI = 0;
2380     // Do not flag preceding copytoreg stuff together with the following stuff.
2381     InFlag = SDValue();
2382     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2383       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2384         CCValAssign &VA = ArgLocs[i];
2385         if (VA.isRegLoc())
2386           continue;
2387         assert(VA.isMemLoc());
2388         SDValue Arg = OutVals[i];
2389         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2390         // Create frame index.
2391         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2392         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2393         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2394         FIN = DAG.getFrameIndex(FI, getPointerTy());
2395
2396         if (Flags.isByVal()) {
2397           // Copy relative to framepointer.
2398           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2399           if (StackPtr.getNode() == 0)
2400             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2401                                           getPointerTy());
2402           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2403
2404           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2405                                                            ArgChain,
2406                                                            Flags, DAG, dl));
2407         } else {
2408           // Store relative to framepointer.
2409           MemOpChains2.push_back(
2410             DAG.getStore(ArgChain, dl, Arg, FIN,
2411                          MachinePointerInfo::getFixedStack(FI),
2412                          false, false, 0));
2413         }
2414       }
2415     }
2416
2417     if (!MemOpChains2.empty())
2418       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2419                           &MemOpChains2[0], MemOpChains2.size());
2420
2421     // Copy arguments to their registers.
2422     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2423       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2424                                RegsToPass[i].second, InFlag);
2425       InFlag = Chain.getValue(1);
2426     }
2427     InFlag =SDValue();
2428
2429     // Store the return address to the appropriate stack slot.
2430     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2431                                      FPDiff, dl);
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 an implicit use GOT pointer in EBX.
2536   if (!isTailCall && Subtarget->isPICStyleGOT())
2537     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2538
2539   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2540   if (Is64Bit && isVarArg && !IsWin64)
2541     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2542
2543   // Add a register mask operand representing the call-preserved registers.
2544   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2545   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2546   assert(Mask && "Missing call preserved mask for calling convention");
2547   Ops.push_back(DAG.getRegisterMask(Mask));
2548
2549   if (InFlag.getNode())
2550     Ops.push_back(InFlag);
2551
2552   if (isTailCall) {
2553     // We used to do:
2554     //// If this is the first return lowered for this function, add the regs
2555     //// to the liveout set for the function.
2556     // This isn't right, although it's probably harmless on x86; liveouts
2557     // should be computed from returns not tail calls.  Consider a void
2558     // function making a tail call to a function returning int.
2559     return DAG.getNode(X86ISD::TC_RETURN, dl,
2560                        NodeTys, &Ops[0], Ops.size());
2561   }
2562
2563   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2564   InFlag = Chain.getValue(1);
2565
2566   // Create the CALLSEQ_END node.
2567   unsigned NumBytesForCalleeToPush;
2568   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2569                        getTargetMachine().Options.GuaranteedTailCallOpt))
2570     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2571   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2572            IsStructRet)
2573     // If this is a call to a struct-return function, the callee
2574     // pops the hidden struct pointer, so we have to push it back.
2575     // This is common for Darwin/X86, Linux & Mingw32 targets.
2576     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2577     NumBytesForCalleeToPush = 4;
2578   else
2579     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2580
2581   // Returns a flag for retval copy to use.
2582   if (!IsSibcall) {
2583     Chain = DAG.getCALLSEQ_END(Chain,
2584                                DAG.getIntPtrConstant(NumBytes, true),
2585                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2586                                                      true),
2587                                InFlag);
2588     InFlag = Chain.getValue(1);
2589   }
2590
2591   // Handle result values, copying them out of physregs into vregs that we
2592   // return.
2593   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2594                          Ins, dl, DAG, InVals);
2595 }
2596
2597
2598 //===----------------------------------------------------------------------===//
2599 //                Fast Calling Convention (tail call) implementation
2600 //===----------------------------------------------------------------------===//
2601
2602 //  Like std call, callee cleans arguments, convention except that ECX is
2603 //  reserved for storing the tail called function address. Only 2 registers are
2604 //  free for argument passing (inreg). Tail call optimization is performed
2605 //  provided:
2606 //                * tailcallopt is enabled
2607 //                * caller/callee are fastcc
2608 //  On X86_64 architecture with GOT-style position independent code only local
2609 //  (within module) calls are supported at the moment.
2610 //  To keep the stack aligned according to platform abi the function
2611 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2612 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2613 //  If a tail called function callee has more arguments than the caller the
2614 //  caller needs to make sure that there is room to move the RETADDR to. This is
2615 //  achieved by reserving an area the size of the argument delta right after the
2616 //  original REtADDR, but before the saved framepointer or the spilled registers
2617 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2618 //  stack layout:
2619 //    arg1
2620 //    arg2
2621 //    RETADDR
2622 //    [ new RETADDR
2623 //      move area ]
2624 //    (possible EBP)
2625 //    ESI
2626 //    EDI
2627 //    local1 ..
2628
2629 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2630 /// for a 16 byte align requirement.
2631 unsigned
2632 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2633                                                SelectionDAG& DAG) const {
2634   MachineFunction &MF = DAG.getMachineFunction();
2635   const TargetMachine &TM = MF.getTarget();
2636   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2637   unsigned StackAlignment = TFI.getStackAlignment();
2638   uint64_t AlignMask = StackAlignment - 1;
2639   int64_t Offset = StackSize;
2640   uint64_t SlotSize = TD->getPointerSize();
2641   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2642     // Number smaller than 12 so just add the difference.
2643     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2644   } else {
2645     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2646     Offset = ((~AlignMask) & Offset) + StackAlignment +
2647       (StackAlignment-SlotSize);
2648   }
2649   return Offset;
2650 }
2651
2652 /// MatchingStackOffset - Return true if the given stack call argument is
2653 /// already available in the same position (relatively) of the caller's
2654 /// incoming argument stack.
2655 static
2656 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2657                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2658                          const X86InstrInfo *TII) {
2659   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2660   int FI = INT_MAX;
2661   if (Arg.getOpcode() == ISD::CopyFromReg) {
2662     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2663     if (!TargetRegisterInfo::isVirtualRegister(VR))
2664       return false;
2665     MachineInstr *Def = MRI->getVRegDef(VR);
2666     if (!Def)
2667       return false;
2668     if (!Flags.isByVal()) {
2669       if (!TII->isLoadFromStackSlot(Def, FI))
2670         return false;
2671     } else {
2672       unsigned Opcode = Def->getOpcode();
2673       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2674           Def->getOperand(1).isFI()) {
2675         FI = Def->getOperand(1).getIndex();
2676         Bytes = Flags.getByValSize();
2677       } else
2678         return false;
2679     }
2680   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2681     if (Flags.isByVal())
2682       // ByVal argument is passed in as a pointer but it's now being
2683       // dereferenced. e.g.
2684       // define @foo(%struct.X* %A) {
2685       //   tail call @bar(%struct.X* byval %A)
2686       // }
2687       return false;
2688     SDValue Ptr = Ld->getBasePtr();
2689     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2690     if (!FINode)
2691       return false;
2692     FI = FINode->getIndex();
2693   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2694     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2695     FI = FINode->getIndex();
2696     Bytes = Flags.getByValSize();
2697   } else
2698     return false;
2699
2700   assert(FI != INT_MAX);
2701   if (!MFI->isFixedObjectIndex(FI))
2702     return false;
2703   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2704 }
2705
2706 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2707 /// for tail call optimization. Targets which want to do tail call
2708 /// optimization should implement this function.
2709 bool
2710 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2711                                                      CallingConv::ID CalleeCC,
2712                                                      bool isVarArg,
2713                                                      bool isCalleeStructRet,
2714                                                      bool isCallerStructRet,
2715                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2716                                     const SmallVectorImpl<SDValue> &OutVals,
2717                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2718                                                      SelectionDAG& DAG) const {
2719   if (!IsTailCallConvention(CalleeCC) &&
2720       CalleeCC != CallingConv::C)
2721     return false;
2722
2723   // If -tailcallopt is specified, make fastcc functions tail-callable.
2724   const MachineFunction &MF = DAG.getMachineFunction();
2725   const Function *CallerF = DAG.getMachineFunction().getFunction();
2726   CallingConv::ID CallerCC = CallerF->getCallingConv();
2727   bool CCMatch = CallerCC == CalleeCC;
2728
2729   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2730     if (IsTailCallConvention(CalleeCC) && CCMatch)
2731       return true;
2732     return false;
2733   }
2734
2735   // Look for obvious safe cases to perform tail call optimization that do not
2736   // require ABI changes. This is what gcc calls sibcall.
2737
2738   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2739   // emit a special epilogue.
2740   if (RegInfo->needsStackRealignment(MF))
2741     return false;
2742
2743   // Also avoid sibcall optimization if either caller or callee uses struct
2744   // return semantics.
2745   if (isCalleeStructRet || isCallerStructRet)
2746     return false;
2747
2748   // An stdcall caller is expected to clean up its arguments; the callee
2749   // isn't going to do that.
2750   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2751     return false;
2752
2753   // Do not sibcall optimize vararg calls unless all arguments are passed via
2754   // registers.
2755   if (isVarArg && !Outs.empty()) {
2756
2757     // Optimizing for varargs on Win64 is unlikely to be safe without
2758     // additional testing.
2759     if (Subtarget->isTargetWin64())
2760       return false;
2761
2762     SmallVector<CCValAssign, 16> ArgLocs;
2763     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2764                    getTargetMachine(), ArgLocs, *DAG.getContext());
2765
2766     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2767     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2768       if (!ArgLocs[i].isRegLoc())
2769         return false;
2770   }
2771
2772   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2773   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2774   // this into a sibcall.
2775   bool Unused = false;
2776   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2777     if (!Ins[i].Used) {
2778       Unused = true;
2779       break;
2780     }
2781   }
2782   if (Unused) {
2783     SmallVector<CCValAssign, 16> RVLocs;
2784     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2785                    getTargetMachine(), RVLocs, *DAG.getContext());
2786     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2787     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2788       CCValAssign &VA = RVLocs[i];
2789       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2790         return false;
2791     }
2792   }
2793
2794   // If the calling conventions do not match, then we'd better make sure the
2795   // results are returned in the same way as what the caller expects.
2796   if (!CCMatch) {
2797     SmallVector<CCValAssign, 16> RVLocs1;
2798     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2799                     getTargetMachine(), RVLocs1, *DAG.getContext());
2800     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2801
2802     SmallVector<CCValAssign, 16> RVLocs2;
2803     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2804                     getTargetMachine(), RVLocs2, *DAG.getContext());
2805     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2806
2807     if (RVLocs1.size() != RVLocs2.size())
2808       return false;
2809     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2810       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2811         return false;
2812       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2813         return false;
2814       if (RVLocs1[i].isRegLoc()) {
2815         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2816           return false;
2817       } else {
2818         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2819           return false;
2820       }
2821     }
2822   }
2823
2824   // If the callee takes no arguments then go on to check the results of the
2825   // call.
2826   if (!Outs.empty()) {
2827     // Check if stack adjustment is needed. For now, do not do this if any
2828     // argument is passed on the stack.
2829     SmallVector<CCValAssign, 16> ArgLocs;
2830     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2831                    getTargetMachine(), ArgLocs, *DAG.getContext());
2832
2833     // Allocate shadow area for Win64
2834     if (Subtarget->isTargetWin64()) {
2835       CCInfo.AllocateStack(32, 8);
2836     }
2837
2838     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2839     if (CCInfo.getNextStackOffset()) {
2840       MachineFunction &MF = DAG.getMachineFunction();
2841       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2842         return false;
2843
2844       // Check if the arguments are already laid out in the right way as
2845       // the caller's fixed stack objects.
2846       MachineFrameInfo *MFI = MF.getFrameInfo();
2847       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2848       const X86InstrInfo *TII =
2849         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2850       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2851         CCValAssign &VA = ArgLocs[i];
2852         SDValue Arg = OutVals[i];
2853         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2854         if (VA.getLocInfo() == CCValAssign::Indirect)
2855           return false;
2856         if (!VA.isRegLoc()) {
2857           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2858                                    MFI, MRI, TII))
2859             return false;
2860         }
2861       }
2862     }
2863
2864     // If the tailcall address may be in a register, then make sure it's
2865     // possible to register allocate for it. In 32-bit, the call address can
2866     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2867     // callee-saved registers are restored. These happen to be the same
2868     // registers used to pass 'inreg' arguments so watch out for those.
2869     if (!Subtarget->is64Bit() &&
2870         !isa<GlobalAddressSDNode>(Callee) &&
2871         !isa<ExternalSymbolSDNode>(Callee)) {
2872       unsigned NumInRegs = 0;
2873       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2874         CCValAssign &VA = ArgLocs[i];
2875         if (!VA.isRegLoc())
2876           continue;
2877         unsigned Reg = VA.getLocReg();
2878         switch (Reg) {
2879         default: break;
2880         case X86::EAX: case X86::EDX: case X86::ECX:
2881           if (++NumInRegs == 3)
2882             return false;
2883           break;
2884         }
2885       }
2886     }
2887   }
2888
2889   return true;
2890 }
2891
2892 FastISel *
2893 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2894   return X86::createFastISel(funcInfo);
2895 }
2896
2897
2898 //===----------------------------------------------------------------------===//
2899 //                           Other Lowering Hooks
2900 //===----------------------------------------------------------------------===//
2901
2902 static bool MayFoldLoad(SDValue Op) {
2903   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2904 }
2905
2906 static bool MayFoldIntoStore(SDValue Op) {
2907   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2908 }
2909
2910 static bool isTargetShuffle(unsigned Opcode) {
2911   switch(Opcode) {
2912   default: return false;
2913   case X86ISD::PSHUFD:
2914   case X86ISD::PSHUFHW:
2915   case X86ISD::PSHUFLW:
2916   case X86ISD::SHUFP:
2917   case X86ISD::PALIGN:
2918   case X86ISD::MOVLHPS:
2919   case X86ISD::MOVLHPD:
2920   case X86ISD::MOVHLPS:
2921   case X86ISD::MOVLPS:
2922   case X86ISD::MOVLPD:
2923   case X86ISD::MOVSHDUP:
2924   case X86ISD::MOVSLDUP:
2925   case X86ISD::MOVDDUP:
2926   case X86ISD::MOVSS:
2927   case X86ISD::MOVSD:
2928   case X86ISD::UNPCKL:
2929   case X86ISD::UNPCKH:
2930   case X86ISD::VPERMILP:
2931   case X86ISD::VPERM2X128:
2932   case X86ISD::VPERMI:
2933     return true;
2934   }
2935 }
2936
2937 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2938                                     SDValue V1, SelectionDAG &DAG) {
2939   switch(Opc) {
2940   default: llvm_unreachable("Unknown x86 shuffle node");
2941   case X86ISD::MOVSHDUP:
2942   case X86ISD::MOVSLDUP:
2943   case X86ISD::MOVDDUP:
2944     return DAG.getNode(Opc, dl, VT, V1);
2945   }
2946 }
2947
2948 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2949                                     SDValue V1, unsigned TargetMask,
2950                                     SelectionDAG &DAG) {
2951   switch(Opc) {
2952   default: llvm_unreachable("Unknown x86 shuffle node");
2953   case X86ISD::PSHUFD:
2954   case X86ISD::PSHUFHW:
2955   case X86ISD::PSHUFLW:
2956   case X86ISD::VPERMILP:
2957   case X86ISD::VPERMI:
2958     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2959   }
2960 }
2961
2962 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2963                                     SDValue V1, SDValue V2, unsigned TargetMask,
2964                                     SelectionDAG &DAG) {
2965   switch(Opc) {
2966   default: llvm_unreachable("Unknown x86 shuffle node");
2967   case X86ISD::PALIGN:
2968   case X86ISD::SHUFP:
2969   case X86ISD::VPERM2X128:
2970     return DAG.getNode(Opc, dl, VT, V1, V2,
2971                        DAG.getConstant(TargetMask, MVT::i8));
2972   }
2973 }
2974
2975 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2976                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2977   switch(Opc) {
2978   default: llvm_unreachable("Unknown x86 shuffle node");
2979   case X86ISD::MOVLHPS:
2980   case X86ISD::MOVLHPD:
2981   case X86ISD::MOVHLPS:
2982   case X86ISD::MOVLPS:
2983   case X86ISD::MOVLPD:
2984   case X86ISD::MOVSS:
2985   case X86ISD::MOVSD:
2986   case X86ISD::UNPCKL:
2987   case X86ISD::UNPCKH:
2988     return DAG.getNode(Opc, dl, VT, V1, V2);
2989   }
2990 }
2991
2992 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2993   MachineFunction &MF = DAG.getMachineFunction();
2994   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2995   int ReturnAddrIndex = FuncInfo->getRAIndex();
2996
2997   if (ReturnAddrIndex == 0) {
2998     // Set up a frame object for the return address.
2999     uint64_t SlotSize = TD->getPointerSize();
3000     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3001                                                            false);
3002     FuncInfo->setRAIndex(ReturnAddrIndex);
3003   }
3004
3005   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3006 }
3007
3008
3009 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3010                                        bool hasSymbolicDisplacement) {
3011   // Offset should fit into 32 bit immediate field.
3012   if (!isInt<32>(Offset))
3013     return false;
3014
3015   // If we don't have a symbolic displacement - we don't have any extra
3016   // restrictions.
3017   if (!hasSymbolicDisplacement)
3018     return true;
3019
3020   // FIXME: Some tweaks might be needed for medium code model.
3021   if (M != CodeModel::Small && M != CodeModel::Kernel)
3022     return false;
3023
3024   // For small code model we assume that latest object is 16MB before end of 31
3025   // bits boundary. We may also accept pretty large negative constants knowing
3026   // that all objects are in the positive half of address space.
3027   if (M == CodeModel::Small && Offset < 16*1024*1024)
3028     return true;
3029
3030   // For kernel code model we know that all object resist in the negative half
3031   // of 32bits address space. We may not accept negative offsets, since they may
3032   // be just off and we may accept pretty large positive ones.
3033   if (M == CodeModel::Kernel && Offset > 0)
3034     return true;
3035
3036   return false;
3037 }
3038
3039 /// isCalleePop - Determines whether the callee is required to pop its
3040 /// own arguments. Callee pop is necessary to support tail calls.
3041 bool X86::isCalleePop(CallingConv::ID CallingConv,
3042                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3043   if (IsVarArg)
3044     return false;
3045
3046   switch (CallingConv) {
3047   default:
3048     return false;
3049   case CallingConv::X86_StdCall:
3050     return !is64Bit;
3051   case CallingConv::X86_FastCall:
3052     return !is64Bit;
3053   case CallingConv::X86_ThisCall:
3054     return !is64Bit;
3055   case CallingConv::Fast:
3056     return TailCallOpt;
3057   case CallingConv::GHC:
3058     return TailCallOpt;
3059   }
3060 }
3061
3062 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3063 /// specific condition code, returning the condition code and the LHS/RHS of the
3064 /// comparison to make.
3065 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3066                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3067   if (!isFP) {
3068     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3069       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3070         // X > -1   -> X == 0, jump !sign.
3071         RHS = DAG.getConstant(0, RHS.getValueType());
3072         return X86::COND_NS;
3073       }
3074       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3075         // X < 0   -> X == 0, jump on sign.
3076         return X86::COND_S;
3077       }
3078       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3079         // X < 1   -> X <= 0
3080         RHS = DAG.getConstant(0, RHS.getValueType());
3081         return X86::COND_LE;
3082       }
3083     }
3084
3085     switch (SetCCOpcode) {
3086     default: llvm_unreachable("Invalid integer condition!");
3087     case ISD::SETEQ:  return X86::COND_E;
3088     case ISD::SETGT:  return X86::COND_G;
3089     case ISD::SETGE:  return X86::COND_GE;
3090     case ISD::SETLT:  return X86::COND_L;
3091     case ISD::SETLE:  return X86::COND_LE;
3092     case ISD::SETNE:  return X86::COND_NE;
3093     case ISD::SETULT: return X86::COND_B;
3094     case ISD::SETUGT: return X86::COND_A;
3095     case ISD::SETULE: return X86::COND_BE;
3096     case ISD::SETUGE: return X86::COND_AE;
3097     }
3098   }
3099
3100   // First determine if it is required or is profitable to flip the operands.
3101
3102   // If LHS is a foldable load, but RHS is not, flip the condition.
3103   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3104       !ISD::isNON_EXTLoad(RHS.getNode())) {
3105     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3106     std::swap(LHS, RHS);
3107   }
3108
3109   switch (SetCCOpcode) {
3110   default: break;
3111   case ISD::SETOLT:
3112   case ISD::SETOLE:
3113   case ISD::SETUGT:
3114   case ISD::SETUGE:
3115     std::swap(LHS, RHS);
3116     break;
3117   }
3118
3119   // On a floating point condition, the flags are set as follows:
3120   // ZF  PF  CF   op
3121   //  0 | 0 | 0 | X > Y
3122   //  0 | 0 | 1 | X < Y
3123   //  1 | 0 | 0 | X == Y
3124   //  1 | 1 | 1 | unordered
3125   switch (SetCCOpcode) {
3126   default: llvm_unreachable("Condcode should be pre-legalized away");
3127   case ISD::SETUEQ:
3128   case ISD::SETEQ:   return X86::COND_E;
3129   case ISD::SETOLT:              // flipped
3130   case ISD::SETOGT:
3131   case ISD::SETGT:   return X86::COND_A;
3132   case ISD::SETOLE:              // flipped
3133   case ISD::SETOGE:
3134   case ISD::SETGE:   return X86::COND_AE;
3135   case ISD::SETUGT:              // flipped
3136   case ISD::SETULT:
3137   case ISD::SETLT:   return X86::COND_B;
3138   case ISD::SETUGE:              // flipped
3139   case ISD::SETULE:
3140   case ISD::SETLE:   return X86::COND_BE;
3141   case ISD::SETONE:
3142   case ISD::SETNE:   return X86::COND_NE;
3143   case ISD::SETUO:   return X86::COND_P;
3144   case ISD::SETO:    return X86::COND_NP;
3145   case ISD::SETOEQ:
3146   case ISD::SETUNE:  return X86::COND_INVALID;
3147   }
3148 }
3149
3150 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3151 /// code. Current x86 isa includes the following FP cmov instructions:
3152 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3153 static bool hasFPCMov(unsigned X86CC) {
3154   switch (X86CC) {
3155   default:
3156     return false;
3157   case X86::COND_B:
3158   case X86::COND_BE:
3159   case X86::COND_E:
3160   case X86::COND_P:
3161   case X86::COND_A:
3162   case X86::COND_AE:
3163   case X86::COND_NE:
3164   case X86::COND_NP:
3165     return true;
3166   }
3167 }
3168
3169 /// isFPImmLegal - Returns true if the target can instruction select the
3170 /// specified FP immediate natively. If false, the legalizer will
3171 /// materialize the FP immediate as a load from a constant pool.
3172 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3173   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3174     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3175       return true;
3176   }
3177   return false;
3178 }
3179
3180 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3181 /// the specified range (L, H].
3182 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3183   return (Val < 0) || (Val >= Low && Val < Hi);
3184 }
3185
3186 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3187 /// specified value.
3188 static bool isUndefOrEqual(int Val, int CmpVal) {
3189   if (Val < 0 || Val == CmpVal)
3190     return true;
3191   return false;
3192 }
3193
3194 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3195 /// from position Pos and ending in Pos+Size, falls within the specified
3196 /// sequential range (L, L+Pos]. or is undef.
3197 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3198                                        unsigned Pos, unsigned Size, int Low) {
3199   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3200     if (!isUndefOrEqual(Mask[i], Low))
3201       return false;
3202   return true;
3203 }
3204
3205 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3206 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3207 /// the second operand.
3208 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3209   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3210     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3211   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3212     return (Mask[0] < 2 && Mask[1] < 2);
3213   return false;
3214 }
3215
3216 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3217 /// is suitable for input to PSHUFHW.
3218 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3219   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3220     return false;
3221
3222   // Lower quadword copied in order or undef.
3223   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3224     return false;
3225
3226   // Upper quadword shuffled.
3227   for (unsigned i = 4; i != 8; ++i)
3228     if (!isUndefOrInRange(Mask[i], 4, 8))
3229       return false;
3230
3231   if (VT == MVT::v16i16) {
3232     // Lower quadword copied in order or undef.
3233     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3234       return false;
3235
3236     // Upper quadword shuffled.
3237     for (unsigned i = 12; i != 16; ++i)
3238       if (!isUndefOrInRange(Mask[i], 12, 16))
3239         return false;
3240   }
3241
3242   return true;
3243 }
3244
3245 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3246 /// is suitable for input to PSHUFLW.
3247 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3248   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3249     return false;
3250
3251   // Upper quadword copied in order.
3252   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3253     return false;
3254
3255   // Lower quadword shuffled.
3256   for (unsigned i = 0; i != 4; ++i)
3257     if (!isUndefOrInRange(Mask[i], 0, 4))
3258       return false;
3259
3260   if (VT == MVT::v16i16) {
3261     // Upper quadword copied in order.
3262     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3263       return false;
3264
3265     // Lower quadword shuffled.
3266     for (unsigned i = 8; i != 12; ++i)
3267       if (!isUndefOrInRange(Mask[i], 8, 12))
3268         return false;
3269   }
3270
3271   return true;
3272 }
3273
3274 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3275 /// is suitable for input to PALIGNR.
3276 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3277                           const X86Subtarget *Subtarget) {
3278   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3279       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3280     return false;
3281
3282   unsigned NumElts = VT.getVectorNumElements();
3283   unsigned NumLanes = VT.getSizeInBits()/128;
3284   unsigned NumLaneElts = NumElts/NumLanes;
3285
3286   // Do not handle 64-bit element shuffles with palignr.
3287   if (NumLaneElts == 2)
3288     return false;
3289
3290   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3291     unsigned i;
3292     for (i = 0; i != NumLaneElts; ++i) {
3293       if (Mask[i+l] >= 0)
3294         break;
3295     }
3296
3297     // Lane is all undef, go to next lane
3298     if (i == NumLaneElts)
3299       continue;
3300
3301     int Start = Mask[i+l];
3302
3303     // Make sure its in this lane in one of the sources
3304     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3305         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3306       return false;
3307
3308     // If not lane 0, then we must match lane 0
3309     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3310       return false;
3311
3312     // Correct second source to be contiguous with first source
3313     if (Start >= (int)NumElts)
3314       Start -= NumElts - NumLaneElts;
3315
3316     // Make sure we're shifting in the right direction.
3317     if (Start <= (int)(i+l))
3318       return false;
3319
3320     Start -= i;
3321
3322     // Check the rest of the elements to see if they are consecutive.
3323     for (++i; i != NumLaneElts; ++i) {
3324       int Idx = Mask[i+l];
3325
3326       // Make sure its in this lane
3327       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3328           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3329         return false;
3330
3331       // If not lane 0, then we must match lane 0
3332       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3333         return false;
3334
3335       if (Idx >= (int)NumElts)
3336         Idx -= NumElts - NumLaneElts;
3337
3338       if (!isUndefOrEqual(Idx, Start+i))
3339         return false;
3340
3341     }
3342   }
3343
3344   return true;
3345 }
3346
3347 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3348 /// the two vector operands have swapped position.
3349 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3350                                      unsigned NumElems) {
3351   for (unsigned i = 0; i != NumElems; ++i) {
3352     int idx = Mask[i];
3353     if (idx < 0)
3354       continue;
3355     else if (idx < (int)NumElems)
3356       Mask[i] = idx + NumElems;
3357     else
3358       Mask[i] = idx - NumElems;
3359   }
3360 }
3361
3362 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3363 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3364 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3365 /// reverse of what x86 shuffles want.
3366 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3367                         bool Commuted = false) {
3368   if (!HasAVX && VT.getSizeInBits() == 256)
3369     return false;
3370
3371   unsigned NumElems = VT.getVectorNumElements();
3372   unsigned NumLanes = VT.getSizeInBits()/128;
3373   unsigned NumLaneElems = NumElems/NumLanes;
3374
3375   if (NumLaneElems != 2 && NumLaneElems != 4)
3376     return false;
3377
3378   // VSHUFPSY divides the resulting vector into 4 chunks.
3379   // The sources are also splitted into 4 chunks, and each destination
3380   // chunk must come from a different source chunk.
3381   //
3382   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3383   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3384   //
3385   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3386   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3387   //
3388   // VSHUFPDY divides the resulting vector into 4 chunks.
3389   // The sources are also splitted into 4 chunks, and each destination
3390   // chunk must come from a different source chunk.
3391   //
3392   //  SRC1 =>      X3       X2       X1       X0
3393   //  SRC2 =>      Y3       Y2       Y1       Y0
3394   //
3395   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3396   //
3397   unsigned HalfLaneElems = NumLaneElems/2;
3398   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3399     for (unsigned i = 0; i != NumLaneElems; ++i) {
3400       int Idx = Mask[i+l];
3401       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3402       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3403         return false;
3404       // For VSHUFPSY, the mask of the second half must be the same as the
3405       // first but with the appropriate offsets. This works in the same way as
3406       // VPERMILPS works with masks.
3407       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3408         continue;
3409       if (!isUndefOrEqual(Idx, Mask[i]+l))
3410         return false;
3411     }
3412   }
3413
3414   return true;
3415 }
3416
3417 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3418 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3419 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3420   unsigned NumElems = VT.getVectorNumElements();
3421
3422   if (VT.getSizeInBits() != 128)
3423     return false;
3424
3425   if (NumElems != 4)
3426     return false;
3427
3428   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3429   return isUndefOrEqual(Mask[0], 6) &&
3430          isUndefOrEqual(Mask[1], 7) &&
3431          isUndefOrEqual(Mask[2], 2) &&
3432          isUndefOrEqual(Mask[3], 3);
3433 }
3434
3435 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3436 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3437 /// <2, 3, 2, 3>
3438 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3439   unsigned NumElems = VT.getVectorNumElements();
3440
3441   if (VT.getSizeInBits() != 128)
3442     return false;
3443
3444   if (NumElems != 4)
3445     return false;
3446
3447   return isUndefOrEqual(Mask[0], 2) &&
3448          isUndefOrEqual(Mask[1], 3) &&
3449          isUndefOrEqual(Mask[2], 2) &&
3450          isUndefOrEqual(Mask[3], 3);
3451 }
3452
3453 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3454 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3455 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3456   if (VT.getSizeInBits() != 128)
3457     return false;
3458
3459   unsigned NumElems = VT.getVectorNumElements();
3460
3461   if (NumElems != 2 && NumElems != 4)
3462     return false;
3463
3464   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3465     if (!isUndefOrEqual(Mask[i], i + NumElems))
3466       return false;
3467
3468   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3469     if (!isUndefOrEqual(Mask[i], i))
3470       return false;
3471
3472   return true;
3473 }
3474
3475 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3476 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3477 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3478   unsigned NumElems = VT.getVectorNumElements();
3479
3480   if ((NumElems != 2 && NumElems != 4)
3481       || VT.getSizeInBits() > 128)
3482     return false;
3483
3484   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3485     if (!isUndefOrEqual(Mask[i], i))
3486       return false;
3487
3488   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3489     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3490       return false;
3491
3492   return true;
3493 }
3494
3495 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3496 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3497 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3498                          bool HasAVX2, bool V2IsSplat = false) {
3499   unsigned NumElts = VT.getVectorNumElements();
3500
3501   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3502          "Unsupported vector type for unpckh");
3503
3504   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3505       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3506     return false;
3507
3508   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3509   // independently on 128-bit lanes.
3510   unsigned NumLanes = VT.getSizeInBits()/128;
3511   unsigned NumLaneElts = NumElts/NumLanes;
3512
3513   for (unsigned l = 0; l != NumLanes; ++l) {
3514     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3515          i != (l+1)*NumLaneElts;
3516          i += 2, ++j) {
3517       int BitI  = Mask[i];
3518       int BitI1 = Mask[i+1];
3519       if (!isUndefOrEqual(BitI, j))
3520         return false;
3521       if (V2IsSplat) {
3522         if (!isUndefOrEqual(BitI1, NumElts))
3523           return false;
3524       } else {
3525         if (!isUndefOrEqual(BitI1, j + NumElts))
3526           return false;
3527       }
3528     }
3529   }
3530
3531   return true;
3532 }
3533
3534 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3535 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3536 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3537                          bool HasAVX2, bool V2IsSplat = false) {
3538   unsigned NumElts = VT.getVectorNumElements();
3539
3540   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3541          "Unsupported vector type for unpckh");
3542
3543   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3544       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3545     return false;
3546
3547   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3548   // independently on 128-bit lanes.
3549   unsigned NumLanes = VT.getSizeInBits()/128;
3550   unsigned NumLaneElts = NumElts/NumLanes;
3551
3552   for (unsigned l = 0; l != NumLanes; ++l) {
3553     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3554          i != (l+1)*NumLaneElts; i += 2, ++j) {
3555       int BitI  = Mask[i];
3556       int BitI1 = Mask[i+1];
3557       if (!isUndefOrEqual(BitI, j))
3558         return false;
3559       if (V2IsSplat) {
3560         if (isUndefOrEqual(BitI1, NumElts))
3561           return false;
3562       } else {
3563         if (!isUndefOrEqual(BitI1, j+NumElts))
3564           return false;
3565       }
3566     }
3567   }
3568   return true;
3569 }
3570
3571 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3572 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3573 /// <0, 0, 1, 1>
3574 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3575                                   bool HasAVX2) {
3576   unsigned NumElts = VT.getVectorNumElements();
3577
3578   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3579          "Unsupported vector type for unpckh");
3580
3581   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3582       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3583     return false;
3584
3585   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3586   // FIXME: Need a better way to get rid of this, there's no latency difference
3587   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3588   // the former later. We should also remove the "_undef" special mask.
3589   if (NumElts == 4 && VT.getSizeInBits() == 256)
3590     return false;
3591
3592   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3593   // independently on 128-bit lanes.
3594   unsigned NumLanes = VT.getSizeInBits()/128;
3595   unsigned NumLaneElts = NumElts/NumLanes;
3596
3597   for (unsigned l = 0; l != NumLanes; ++l) {
3598     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3599          i != (l+1)*NumLaneElts;
3600          i += 2, ++j) {
3601       int BitI  = Mask[i];
3602       int BitI1 = Mask[i+1];
3603
3604       if (!isUndefOrEqual(BitI, j))
3605         return false;
3606       if (!isUndefOrEqual(BitI1, j))
3607         return false;
3608     }
3609   }
3610
3611   return true;
3612 }
3613
3614 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3615 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3616 /// <2, 2, 3, 3>
3617 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3618   unsigned NumElts = VT.getVectorNumElements();
3619
3620   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3621          "Unsupported vector type for unpckh");
3622
3623   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3624       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3625     return false;
3626
3627   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3628   // independently on 128-bit lanes.
3629   unsigned NumLanes = VT.getSizeInBits()/128;
3630   unsigned NumLaneElts = NumElts/NumLanes;
3631
3632   for (unsigned l = 0; l != NumLanes; ++l) {
3633     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3634          i != (l+1)*NumLaneElts; i += 2, ++j) {
3635       int BitI  = Mask[i];
3636       int BitI1 = Mask[i+1];
3637       if (!isUndefOrEqual(BitI, j))
3638         return false;
3639       if (!isUndefOrEqual(BitI1, j))
3640         return false;
3641     }
3642   }
3643   return true;
3644 }
3645
3646 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3647 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3648 /// MOVSD, and MOVD, i.e. setting the lowest element.
3649 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3650   if (VT.getVectorElementType().getSizeInBits() < 32)
3651     return false;
3652   if (VT.getSizeInBits() == 256)
3653     return false;
3654
3655   unsigned NumElts = VT.getVectorNumElements();
3656
3657   if (!isUndefOrEqual(Mask[0], NumElts))
3658     return false;
3659
3660   for (unsigned i = 1; i != NumElts; ++i)
3661     if (!isUndefOrEqual(Mask[i], i))
3662       return false;
3663
3664   return true;
3665 }
3666
3667 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3668 /// as permutations between 128-bit chunks or halves. As an example: this
3669 /// shuffle bellow:
3670 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3671 /// The first half comes from the second half of V1 and the second half from the
3672 /// the second half of V2.
3673 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3674   if (!HasAVX || VT.getSizeInBits() != 256)
3675     return false;
3676
3677   // The shuffle result is divided into half A and half B. In total the two
3678   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3679   // B must come from C, D, E or F.
3680   unsigned HalfSize = VT.getVectorNumElements()/2;
3681   bool MatchA = false, MatchB = false;
3682
3683   // Check if A comes from one of C, D, E, F.
3684   for (unsigned Half = 0; Half != 4; ++Half) {
3685     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3686       MatchA = true;
3687       break;
3688     }
3689   }
3690
3691   // Check if B comes from one of C, D, E, F.
3692   for (unsigned Half = 0; Half != 4; ++Half) {
3693     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3694       MatchB = true;
3695       break;
3696     }
3697   }
3698
3699   return MatchA && MatchB;
3700 }
3701
3702 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3703 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3704 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3705   EVT VT = SVOp->getValueType(0);
3706
3707   unsigned HalfSize = VT.getVectorNumElements()/2;
3708
3709   unsigned FstHalf = 0, SndHalf = 0;
3710   for (unsigned i = 0; i < HalfSize; ++i) {
3711     if (SVOp->getMaskElt(i) > 0) {
3712       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3713       break;
3714     }
3715   }
3716   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3717     if (SVOp->getMaskElt(i) > 0) {
3718       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3719       break;
3720     }
3721   }
3722
3723   return (FstHalf | (SndHalf << 4));
3724 }
3725
3726 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3727 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3728 /// Note that VPERMIL mask matching is different depending whether theunderlying
3729 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3730 /// to the same elements of the low, but to the higher half of the source.
3731 /// In VPERMILPD the two lanes could be shuffled independently of each other
3732 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3733 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3734   if (!HasAVX)
3735     return false;
3736
3737   unsigned NumElts = VT.getVectorNumElements();
3738   // Only match 256-bit with 32/64-bit types
3739   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3740     return false;
3741
3742   unsigned NumLanes = VT.getSizeInBits()/128;
3743   unsigned LaneSize = NumElts/NumLanes;
3744   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3745     for (unsigned i = 0; i != LaneSize; ++i) {
3746       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3747         return false;
3748       if (NumElts != 8 || l == 0)
3749         continue;
3750       // VPERMILPS handling
3751       if (Mask[i] < 0)
3752         continue;
3753       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3754         return false;
3755     }
3756   }
3757
3758   return true;
3759 }
3760
3761 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3762 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3763 /// element of vector 2 and the other elements to come from vector 1 in order.
3764 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3765                                bool V2IsSplat = false, bool V2IsUndef = false) {
3766   unsigned NumOps = VT.getVectorNumElements();
3767   if (VT.getSizeInBits() == 256)
3768     return false;
3769   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3770     return false;
3771
3772   if (!isUndefOrEqual(Mask[0], 0))
3773     return false;
3774
3775   for (unsigned i = 1; i != NumOps; ++i)
3776     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3777           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3778           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3779       return false;
3780
3781   return true;
3782 }
3783
3784 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3785 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3786 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3787 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3788                            const X86Subtarget *Subtarget) {
3789   if (!Subtarget->hasSSE3())
3790     return false;
3791
3792   unsigned NumElems = VT.getVectorNumElements();
3793
3794   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3795       (VT.getSizeInBits() == 256 && NumElems != 8))
3796     return false;
3797
3798   // "i+1" is the value the indexed mask element must have
3799   for (unsigned i = 0; i != NumElems; i += 2)
3800     if (!isUndefOrEqual(Mask[i], i+1) ||
3801         !isUndefOrEqual(Mask[i+1], i+1))
3802       return false;
3803
3804   return true;
3805 }
3806
3807 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3808 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3809 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3810 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3811                            const X86Subtarget *Subtarget) {
3812   if (!Subtarget->hasSSE3())
3813     return false;
3814
3815   unsigned NumElems = VT.getVectorNumElements();
3816
3817   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3818       (VT.getSizeInBits() == 256 && NumElems != 8))
3819     return false;
3820
3821   // "i" is the value the indexed mask element must have
3822   for (unsigned i = 0; i != NumElems; i += 2)
3823     if (!isUndefOrEqual(Mask[i], i) ||
3824         !isUndefOrEqual(Mask[i+1], i))
3825       return false;
3826
3827   return true;
3828 }
3829
3830 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3831 /// specifies a shuffle of elements that is suitable for input to 256-bit
3832 /// version of MOVDDUP.
3833 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3834   unsigned NumElts = VT.getVectorNumElements();
3835
3836   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3837     return false;
3838
3839   for (unsigned i = 0; i != NumElts/2; ++i)
3840     if (!isUndefOrEqual(Mask[i], 0))
3841       return false;
3842   for (unsigned i = NumElts/2; i != NumElts; ++i)
3843     if (!isUndefOrEqual(Mask[i], NumElts/2))
3844       return false;
3845   return true;
3846 }
3847
3848 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3849 /// specifies a shuffle of elements that is suitable for input to 128-bit
3850 /// version of MOVDDUP.
3851 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3852   if (VT.getSizeInBits() != 128)
3853     return false;
3854
3855   unsigned e = VT.getVectorNumElements() / 2;
3856   for (unsigned i = 0; i != e; ++i)
3857     if (!isUndefOrEqual(Mask[i], i))
3858       return false;
3859   for (unsigned i = 0; i != e; ++i)
3860     if (!isUndefOrEqual(Mask[e+i], i))
3861       return false;
3862   return true;
3863 }
3864
3865 /// isVEXTRACTF128Index - Return true if the specified
3866 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3867 /// suitable for input to VEXTRACTF128.
3868 bool X86::isVEXTRACTF128Index(SDNode *N) {
3869   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3870     return false;
3871
3872   // The index should be aligned on a 128-bit boundary.
3873   uint64_t Index =
3874     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3875
3876   unsigned VL = N->getValueType(0).getVectorNumElements();
3877   unsigned VBits = N->getValueType(0).getSizeInBits();
3878   unsigned ElSize = VBits / VL;
3879   bool Result = (Index * ElSize) % 128 == 0;
3880
3881   return Result;
3882 }
3883
3884 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3885 /// operand specifies a subvector insert that is suitable for input to
3886 /// VINSERTF128.
3887 bool X86::isVINSERTF128Index(SDNode *N) {
3888   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3889     return false;
3890
3891   // The index should be aligned on a 128-bit boundary.
3892   uint64_t Index =
3893     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3894
3895   unsigned VL = N->getValueType(0).getVectorNumElements();
3896   unsigned VBits = N->getValueType(0).getSizeInBits();
3897   unsigned ElSize = VBits / VL;
3898   bool Result = (Index * ElSize) % 128 == 0;
3899
3900   return Result;
3901 }
3902
3903 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3904 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3905 /// Handles 128-bit and 256-bit.
3906 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3907   EVT VT = N->getValueType(0);
3908
3909   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3910          "Unsupported vector type for PSHUF/SHUFP");
3911
3912   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3913   // independently on 128-bit lanes.
3914   unsigned NumElts = VT.getVectorNumElements();
3915   unsigned NumLanes = VT.getSizeInBits()/128;
3916   unsigned NumLaneElts = NumElts/NumLanes;
3917
3918   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3919          "Only supports 2 or 4 elements per lane");
3920
3921   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3922   unsigned Mask = 0;
3923   for (unsigned i = 0; i != NumElts; ++i) {
3924     int Elt = N->getMaskElt(i);
3925     if (Elt < 0) continue;
3926     Elt &= NumLaneElts - 1;
3927     unsigned ShAmt = (i << Shift) % 8;
3928     Mask |= Elt << ShAmt;
3929   }
3930
3931   return Mask;
3932 }
3933
3934 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3935 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3936 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3937   EVT VT = N->getValueType(0);
3938
3939   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3940          "Unsupported vector type for PSHUFHW");
3941
3942   unsigned NumElts = VT.getVectorNumElements();
3943
3944   unsigned Mask = 0;
3945   for (unsigned l = 0; l != NumElts; l += 8) {
3946     // 8 nodes per lane, but we only care about the last 4.
3947     for (unsigned i = 0; i < 4; ++i) {
3948       int Elt = N->getMaskElt(l+i+4);
3949       if (Elt < 0) continue;
3950       Elt &= 0x3; // only 2-bits.
3951       Mask |= Elt << (i * 2);
3952     }
3953   }
3954
3955   return Mask;
3956 }
3957
3958 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3959 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3960 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
3961   EVT VT = N->getValueType(0);
3962
3963   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3964          "Unsupported vector type for PSHUFHW");
3965
3966   unsigned NumElts = VT.getVectorNumElements();
3967
3968   unsigned Mask = 0;
3969   for (unsigned l = 0; l != NumElts; l += 8) {
3970     // 8 nodes per lane, but we only care about the first 4.
3971     for (unsigned i = 0; i < 4; ++i) {
3972       int Elt = N->getMaskElt(l+i);
3973       if (Elt < 0) continue;
3974       Elt &= 0x3; // only 2-bits
3975       Mask |= Elt << (i * 2);
3976     }
3977   }
3978
3979   return Mask;
3980 }
3981
3982 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3983 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3984 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
3985   EVT VT = SVOp->getValueType(0);
3986   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
3987
3988   unsigned NumElts = VT.getVectorNumElements();
3989   unsigned NumLanes = VT.getSizeInBits()/128;
3990   unsigned NumLaneElts = NumElts/NumLanes;
3991
3992   int Val = 0;
3993   unsigned i;
3994   for (i = 0; i != NumElts; ++i) {
3995     Val = SVOp->getMaskElt(i);
3996     if (Val >= 0)
3997       break;
3998   }
3999   if (Val >= (int)NumElts)
4000     Val -= NumElts - NumLaneElts;
4001
4002   assert(Val - i > 0 && "PALIGNR imm should be positive");
4003   return (Val - i) * EltSize;
4004 }
4005
4006 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4007 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4008 /// instructions.
4009 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4010   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4011     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4012
4013   uint64_t Index =
4014     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4015
4016   EVT VecVT = N->getOperand(0).getValueType();
4017   EVT ElVT = VecVT.getVectorElementType();
4018
4019   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4020   return Index / NumElemsPerChunk;
4021 }
4022
4023 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4024 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4025 /// instructions.
4026 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4027   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4028     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4029
4030   uint64_t Index =
4031     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4032
4033   EVT VecVT = N->getValueType(0);
4034   EVT ElVT = VecVT.getVectorElementType();
4035
4036   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4037   return Index / NumElemsPerChunk;
4038 }
4039
4040 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4041 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4042 /// Handles 256-bit.
4043 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4044   EVT VT = N->getValueType(0);
4045
4046   unsigned NumElts = VT.getVectorNumElements();
4047
4048   assert((VT.is256BitVector() && NumElts == 4) &&
4049          "Unsupported vector type for VPERMQ/VPERMPD");
4050
4051   unsigned Mask = 0;
4052   for (unsigned i = 0; i != NumElts; ++i) {
4053     int Elt = N->getMaskElt(i);
4054     if (Elt < 0)
4055       continue;
4056     Mask |= Elt << (i*2);
4057   }
4058
4059   return Mask;
4060 }
4061 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4062 /// constant +0.0.
4063 bool X86::isZeroNode(SDValue Elt) {
4064   return ((isa<ConstantSDNode>(Elt) &&
4065            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4066           (isa<ConstantFPSDNode>(Elt) &&
4067            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4068 }
4069
4070 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4071 /// their permute mask.
4072 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4073                                     SelectionDAG &DAG) {
4074   EVT VT = SVOp->getValueType(0);
4075   unsigned NumElems = VT.getVectorNumElements();
4076   SmallVector<int, 8> MaskVec;
4077
4078   for (unsigned i = 0; i != NumElems; ++i) {
4079     int Idx = SVOp->getMaskElt(i);
4080     if (Idx >= 0) {
4081       if (Idx < (int)NumElems)
4082         Idx += NumElems;
4083       else
4084         Idx -= NumElems;
4085     }
4086     MaskVec.push_back(Idx);
4087   }
4088   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4089                               SVOp->getOperand(0), &MaskVec[0]);
4090 }
4091
4092 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4093 /// match movhlps. The lower half elements should come from upper half of
4094 /// V1 (and in order), and the upper half elements should come from the upper
4095 /// half of V2 (and in order).
4096 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4097   if (VT.getSizeInBits() != 128)
4098     return false;
4099   if (VT.getVectorNumElements() != 4)
4100     return false;
4101   for (unsigned i = 0, e = 2; i != e; ++i)
4102     if (!isUndefOrEqual(Mask[i], i+2))
4103       return false;
4104   for (unsigned i = 2; i != 4; ++i)
4105     if (!isUndefOrEqual(Mask[i], i+4))
4106       return false;
4107   return true;
4108 }
4109
4110 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4111 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4112 /// required.
4113 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4114   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4115     return false;
4116   N = N->getOperand(0).getNode();
4117   if (!ISD::isNON_EXTLoad(N))
4118     return false;
4119   if (LD)
4120     *LD = cast<LoadSDNode>(N);
4121   return true;
4122 }
4123
4124 // Test whether the given value is a vector value which will be legalized
4125 // into a load.
4126 static bool WillBeConstantPoolLoad(SDNode *N) {
4127   if (N->getOpcode() != ISD::BUILD_VECTOR)
4128     return false;
4129
4130   // Check for any non-constant elements.
4131   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4132     switch (N->getOperand(i).getNode()->getOpcode()) {
4133     case ISD::UNDEF:
4134     case ISD::ConstantFP:
4135     case ISD::Constant:
4136       break;
4137     default:
4138       return false;
4139     }
4140
4141   // Vectors of all-zeros and all-ones are materialized with special
4142   // instructions rather than being loaded.
4143   return !ISD::isBuildVectorAllZeros(N) &&
4144          !ISD::isBuildVectorAllOnes(N);
4145 }
4146
4147 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4148 /// match movlp{s|d}. The lower half elements should come from lower half of
4149 /// V1 (and in order), and the upper half elements should come from the upper
4150 /// half of V2 (and in order). And since V1 will become the source of the
4151 /// MOVLP, it must be either a vector load or a scalar load to vector.
4152 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4153                                ArrayRef<int> Mask, EVT VT) {
4154   if (VT.getSizeInBits() != 128)
4155     return false;
4156
4157   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4158     return false;
4159   // Is V2 is a vector load, don't do this transformation. We will try to use
4160   // load folding shufps op.
4161   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4162     return false;
4163
4164   unsigned NumElems = VT.getVectorNumElements();
4165
4166   if (NumElems != 2 && NumElems != 4)
4167     return false;
4168   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4169     if (!isUndefOrEqual(Mask[i], i))
4170       return false;
4171   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4172     if (!isUndefOrEqual(Mask[i], i+NumElems))
4173       return false;
4174   return true;
4175 }
4176
4177 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4178 /// all the same.
4179 static bool isSplatVector(SDNode *N) {
4180   if (N->getOpcode() != ISD::BUILD_VECTOR)
4181     return false;
4182
4183   SDValue SplatValue = N->getOperand(0);
4184   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4185     if (N->getOperand(i) != SplatValue)
4186       return false;
4187   return true;
4188 }
4189
4190 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4191 /// to an zero vector.
4192 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4193 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4194   SDValue V1 = N->getOperand(0);
4195   SDValue V2 = N->getOperand(1);
4196   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4197   for (unsigned i = 0; i != NumElems; ++i) {
4198     int Idx = N->getMaskElt(i);
4199     if (Idx >= (int)NumElems) {
4200       unsigned Opc = V2.getOpcode();
4201       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4202         continue;
4203       if (Opc != ISD::BUILD_VECTOR ||
4204           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4205         return false;
4206     } else if (Idx >= 0) {
4207       unsigned Opc = V1.getOpcode();
4208       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4209         continue;
4210       if (Opc != ISD::BUILD_VECTOR ||
4211           !X86::isZeroNode(V1.getOperand(Idx)))
4212         return false;
4213     }
4214   }
4215   return true;
4216 }
4217
4218 /// getZeroVector - Returns a vector of specified type with all zero elements.
4219 ///
4220 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4221                              SelectionDAG &DAG, DebugLoc dl) {
4222   assert(VT.isVector() && "Expected a vector type");
4223   unsigned Size = VT.getSizeInBits();
4224
4225   // Always build SSE zero vectors as <4 x i32> bitcasted
4226   // to their dest type. This ensures they get CSE'd.
4227   SDValue Vec;
4228   if (Size == 128) {  // SSE
4229     if (Subtarget->hasSSE2()) {  // SSE2
4230       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4231       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4232     } else { // SSE1
4233       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4234       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4235     }
4236   } else if (Size == 256) { // AVX
4237     if (Subtarget->hasAVX2()) { // AVX2
4238       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4239       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4240       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4241     } else {
4242       // 256-bit logic and arithmetic instructions in AVX are all
4243       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4244       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4245       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4246       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4247     }
4248   } else
4249     llvm_unreachable("Unexpected vector type");
4250
4251   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4252 }
4253
4254 /// getOnesVector - Returns a vector of specified type with all bits set.
4255 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4256 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4257 /// Then bitcast to their original type, ensuring they get CSE'd.
4258 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4259                              DebugLoc dl) {
4260   assert(VT.isVector() && "Expected a vector type");
4261   unsigned Size = VT.getSizeInBits();
4262
4263   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4264   SDValue Vec;
4265   if (Size == 256) {
4266     if (HasAVX2) { // AVX2
4267       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4268       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4269     } else { // AVX
4270       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4271       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4272     }
4273   } else if (Size == 128) {
4274     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4275   } else
4276     llvm_unreachable("Unexpected vector type");
4277
4278   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4279 }
4280
4281 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4282 /// that point to V2 points to its first element.
4283 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4284   for (unsigned i = 0; i != NumElems; ++i) {
4285     if (Mask[i] > (int)NumElems) {
4286       Mask[i] = NumElems;
4287     }
4288   }
4289 }
4290
4291 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4292 /// operation of specified width.
4293 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4294                        SDValue V2) {
4295   unsigned NumElems = VT.getVectorNumElements();
4296   SmallVector<int, 8> Mask;
4297   Mask.push_back(NumElems);
4298   for (unsigned i = 1; i != NumElems; ++i)
4299     Mask.push_back(i);
4300   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4301 }
4302
4303 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4304 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4305                           SDValue V2) {
4306   unsigned NumElems = VT.getVectorNumElements();
4307   SmallVector<int, 8> Mask;
4308   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4309     Mask.push_back(i);
4310     Mask.push_back(i + NumElems);
4311   }
4312   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4313 }
4314
4315 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4316 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4317                           SDValue V2) {
4318   unsigned NumElems = VT.getVectorNumElements();
4319   SmallVector<int, 8> Mask;
4320   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4321     Mask.push_back(i + Half);
4322     Mask.push_back(i + NumElems + Half);
4323   }
4324   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4325 }
4326
4327 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4328 // a generic shuffle instruction because the target has no such instructions.
4329 // Generate shuffles which repeat i16 and i8 several times until they can be
4330 // represented by v4f32 and then be manipulated by target suported shuffles.
4331 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4332   EVT VT = V.getValueType();
4333   int NumElems = VT.getVectorNumElements();
4334   DebugLoc dl = V.getDebugLoc();
4335
4336   while (NumElems > 4) {
4337     if (EltNo < NumElems/2) {
4338       V = getUnpackl(DAG, dl, VT, V, V);
4339     } else {
4340       V = getUnpackh(DAG, dl, VT, V, V);
4341       EltNo -= NumElems/2;
4342     }
4343     NumElems >>= 1;
4344   }
4345   return V;
4346 }
4347
4348 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4349 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4350   EVT VT = V.getValueType();
4351   DebugLoc dl = V.getDebugLoc();
4352   unsigned Size = VT.getSizeInBits();
4353
4354   if (Size == 128) {
4355     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4356     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4357     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4358                              &SplatMask[0]);
4359   } else if (Size == 256) {
4360     // To use VPERMILPS to splat scalars, the second half of indicies must
4361     // refer to the higher part, which is a duplication of the lower one,
4362     // because VPERMILPS can only handle in-lane permutations.
4363     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4364                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4365
4366     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4367     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4368                              &SplatMask[0]);
4369   } else
4370     llvm_unreachable("Vector size not supported");
4371
4372   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4373 }
4374
4375 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4376 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4377   EVT SrcVT = SV->getValueType(0);
4378   SDValue V1 = SV->getOperand(0);
4379   DebugLoc dl = SV->getDebugLoc();
4380
4381   int EltNo = SV->getSplatIndex();
4382   int NumElems = SrcVT.getVectorNumElements();
4383   unsigned Size = SrcVT.getSizeInBits();
4384
4385   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4386           "Unknown how to promote splat for type");
4387
4388   // Extract the 128-bit part containing the splat element and update
4389   // the splat element index when it refers to the higher register.
4390   if (Size == 256) {
4391     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4392     if (EltNo >= NumElems/2)
4393       EltNo -= NumElems/2;
4394   }
4395
4396   // All i16 and i8 vector types can't be used directly by a generic shuffle
4397   // instruction because the target has no such instruction. Generate shuffles
4398   // which repeat i16 and i8 several times until they fit in i32, and then can
4399   // be manipulated by target suported shuffles.
4400   EVT EltVT = SrcVT.getVectorElementType();
4401   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4402     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4403
4404   // Recreate the 256-bit vector and place the same 128-bit vector
4405   // into the low and high part. This is necessary because we want
4406   // to use VPERM* to shuffle the vectors
4407   if (Size == 256) {
4408     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4409   }
4410
4411   return getLegalSplat(DAG, V1, EltNo);
4412 }
4413
4414 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4415 /// vector of zero or undef vector.  This produces a shuffle where the low
4416 /// element of V2 is swizzled into the zero/undef vector, landing at element
4417 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4418 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4419                                            bool IsZero,
4420                                            const X86Subtarget *Subtarget,
4421                                            SelectionDAG &DAG) {
4422   EVT VT = V2.getValueType();
4423   SDValue V1 = IsZero
4424     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4425   unsigned NumElems = VT.getVectorNumElements();
4426   SmallVector<int, 16> MaskVec;
4427   for (unsigned i = 0; i != NumElems; ++i)
4428     // If this is the insertion idx, put the low elt of V2 here.
4429     MaskVec.push_back(i == Idx ? NumElems : i);
4430   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4431 }
4432
4433 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4434 /// target specific opcode. Returns true if the Mask could be calculated.
4435 /// Sets IsUnary to true if only uses one source.
4436 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4437                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4438   unsigned NumElems = VT.getVectorNumElements();
4439   SDValue ImmN;
4440
4441   IsUnary = false;
4442   switch(N->getOpcode()) {
4443   case X86ISD::SHUFP:
4444     ImmN = N->getOperand(N->getNumOperands()-1);
4445     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4446     break;
4447   case X86ISD::UNPCKH:
4448     DecodeUNPCKHMask(VT, Mask);
4449     break;
4450   case X86ISD::UNPCKL:
4451     DecodeUNPCKLMask(VT, Mask);
4452     break;
4453   case X86ISD::MOVHLPS:
4454     DecodeMOVHLPSMask(NumElems, Mask);
4455     break;
4456   case X86ISD::MOVLHPS:
4457     DecodeMOVLHPSMask(NumElems, Mask);
4458     break;
4459   case X86ISD::PSHUFD:
4460   case X86ISD::VPERMILP:
4461     ImmN = N->getOperand(N->getNumOperands()-1);
4462     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4463     IsUnary = true;
4464     break;
4465   case X86ISD::PSHUFHW:
4466     ImmN = N->getOperand(N->getNumOperands()-1);
4467     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4468     IsUnary = true;
4469     break;
4470   case X86ISD::PSHUFLW:
4471     ImmN = N->getOperand(N->getNumOperands()-1);
4472     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4473     IsUnary = true;
4474     break;
4475   case X86ISD::VPERMI:
4476     ImmN = N->getOperand(N->getNumOperands()-1);
4477     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4478     IsUnary = true;
4479     break;
4480   case X86ISD::MOVSS:
4481   case X86ISD::MOVSD: {
4482     // The index 0 always comes from the first element of the second source,
4483     // this is why MOVSS and MOVSD are used in the first place. The other
4484     // elements come from the other positions of the first source vector
4485     Mask.push_back(NumElems);
4486     for (unsigned i = 1; i != NumElems; ++i) {
4487       Mask.push_back(i);
4488     }
4489     break;
4490   }
4491   case X86ISD::VPERM2X128:
4492     ImmN = N->getOperand(N->getNumOperands()-1);
4493     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4494     if (Mask.empty()) return false;
4495     break;
4496   case X86ISD::MOVDDUP:
4497   case X86ISD::MOVLHPD:
4498   case X86ISD::MOVLPD:
4499   case X86ISD::MOVLPS:
4500   case X86ISD::MOVSHDUP:
4501   case X86ISD::MOVSLDUP:
4502   case X86ISD::PALIGN:
4503     // Not yet implemented
4504     return false;
4505   default: llvm_unreachable("unknown target shuffle node");
4506   }
4507
4508   return true;
4509 }
4510
4511 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4512 /// element of the result of the vector shuffle.
4513 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4514                                    unsigned Depth) {
4515   if (Depth == 6)
4516     return SDValue();  // Limit search depth.
4517
4518   SDValue V = SDValue(N, 0);
4519   EVT VT = V.getValueType();
4520   unsigned Opcode = V.getOpcode();
4521
4522   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4523   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4524     int Elt = SV->getMaskElt(Index);
4525
4526     if (Elt < 0)
4527       return DAG.getUNDEF(VT.getVectorElementType());
4528
4529     unsigned NumElems = VT.getVectorNumElements();
4530     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4531                                          : SV->getOperand(1);
4532     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4533   }
4534
4535   // Recurse into target specific vector shuffles to find scalars.
4536   if (isTargetShuffle(Opcode)) {
4537     MVT ShufVT = V.getValueType().getSimpleVT();
4538     unsigned NumElems = ShufVT.getVectorNumElements();
4539     SmallVector<int, 16> ShuffleMask;
4540     SDValue ImmN;
4541     bool IsUnary;
4542
4543     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4544       return SDValue();
4545
4546     int Elt = ShuffleMask[Index];
4547     if (Elt < 0)
4548       return DAG.getUNDEF(ShufVT.getVectorElementType());
4549
4550     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4551                                          : N->getOperand(1);
4552     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4553                                Depth+1);
4554   }
4555
4556   // Actual nodes that may contain scalar elements
4557   if (Opcode == ISD::BITCAST) {
4558     V = V.getOperand(0);
4559     EVT SrcVT = V.getValueType();
4560     unsigned NumElems = VT.getVectorNumElements();
4561
4562     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4563       return SDValue();
4564   }
4565
4566   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4567     return (Index == 0) ? V.getOperand(0)
4568                         : DAG.getUNDEF(VT.getVectorElementType());
4569
4570   if (V.getOpcode() == ISD::BUILD_VECTOR)
4571     return V.getOperand(Index);
4572
4573   return SDValue();
4574 }
4575
4576 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4577 /// shuffle operation which come from a consecutively from a zero. The
4578 /// search can start in two different directions, from left or right.
4579 static
4580 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4581                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4582   unsigned i;
4583   for (i = 0; i != NumElems; ++i) {
4584     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4585     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4586     if (!(Elt.getNode() &&
4587          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4588       break;
4589   }
4590
4591   return i;
4592 }
4593
4594 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4595 /// correspond consecutively to elements from one of the vector operands,
4596 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4597 static
4598 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4599                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4600                               unsigned NumElems, unsigned &OpNum) {
4601   bool SeenV1 = false;
4602   bool SeenV2 = false;
4603
4604   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4605     int Idx = SVOp->getMaskElt(i);
4606     // Ignore undef indicies
4607     if (Idx < 0)
4608       continue;
4609
4610     if (Idx < (int)NumElems)
4611       SeenV1 = true;
4612     else
4613       SeenV2 = true;
4614
4615     // Only accept consecutive elements from the same vector
4616     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4617       return false;
4618   }
4619
4620   OpNum = SeenV1 ? 0 : 1;
4621   return true;
4622 }
4623
4624 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4625 /// logical left shift of a vector.
4626 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4627                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4628   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4629   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4630               false /* check zeros from right */, DAG);
4631   unsigned OpSrc;
4632
4633   if (!NumZeros)
4634     return false;
4635
4636   // Considering the elements in the mask that are not consecutive zeros,
4637   // check if they consecutively come from only one of the source vectors.
4638   //
4639   //               V1 = {X, A, B, C}     0
4640   //                         \  \  \    /
4641   //   vector_shuffle V1, V2 <1, 2, 3, X>
4642   //
4643   if (!isShuffleMaskConsecutive(SVOp,
4644             0,                   // Mask Start Index
4645             NumElems-NumZeros,   // Mask End Index(exclusive)
4646             NumZeros,            // Where to start looking in the src vector
4647             NumElems,            // Number of elements in vector
4648             OpSrc))              // Which source operand ?
4649     return false;
4650
4651   isLeft = false;
4652   ShAmt = NumZeros;
4653   ShVal = SVOp->getOperand(OpSrc);
4654   return true;
4655 }
4656
4657 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4658 /// logical left shift of a vector.
4659 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4660                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4661   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4662   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4663               true /* check zeros from left */, DAG);
4664   unsigned OpSrc;
4665
4666   if (!NumZeros)
4667     return false;
4668
4669   // Considering the elements in the mask that are not consecutive zeros,
4670   // check if they consecutively come from only one of the source vectors.
4671   //
4672   //                           0    { A, B, X, X } = V2
4673   //                          / \    /  /
4674   //   vector_shuffle V1, V2 <X, X, 4, 5>
4675   //
4676   if (!isShuffleMaskConsecutive(SVOp,
4677             NumZeros,     // Mask Start Index
4678             NumElems,     // Mask End Index(exclusive)
4679             0,            // Where to start looking in the src vector
4680             NumElems,     // Number of elements in vector
4681             OpSrc))       // Which source operand ?
4682     return false;
4683
4684   isLeft = true;
4685   ShAmt = NumZeros;
4686   ShVal = SVOp->getOperand(OpSrc);
4687   return true;
4688 }
4689
4690 /// isVectorShift - Returns true if the shuffle can be implemented as a
4691 /// logical left or right shift of a vector.
4692 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4693                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4694   // Although the logic below support any bitwidth size, there are no
4695   // shift instructions which handle more than 128-bit vectors.
4696   if (SVOp->getValueType(0).getSizeInBits() > 128)
4697     return false;
4698
4699   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4700       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4701     return true;
4702
4703   return false;
4704 }
4705
4706 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4707 ///
4708 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4709                                        unsigned NumNonZero, unsigned NumZero,
4710                                        SelectionDAG &DAG,
4711                                        const X86Subtarget* Subtarget,
4712                                        const TargetLowering &TLI) {
4713   if (NumNonZero > 8)
4714     return SDValue();
4715
4716   DebugLoc dl = Op.getDebugLoc();
4717   SDValue V(0, 0);
4718   bool First = true;
4719   for (unsigned i = 0; i < 16; ++i) {
4720     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4721     if (ThisIsNonZero && First) {
4722       if (NumZero)
4723         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4724       else
4725         V = DAG.getUNDEF(MVT::v8i16);
4726       First = false;
4727     }
4728
4729     if ((i & 1) != 0) {
4730       SDValue ThisElt(0, 0), LastElt(0, 0);
4731       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4732       if (LastIsNonZero) {
4733         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4734                               MVT::i16, Op.getOperand(i-1));
4735       }
4736       if (ThisIsNonZero) {
4737         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4738         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4739                               ThisElt, DAG.getConstant(8, MVT::i8));
4740         if (LastIsNonZero)
4741           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4742       } else
4743         ThisElt = LastElt;
4744
4745       if (ThisElt.getNode())
4746         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4747                         DAG.getIntPtrConstant(i/2));
4748     }
4749   }
4750
4751   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4752 }
4753
4754 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4755 ///
4756 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4757                                      unsigned NumNonZero, unsigned NumZero,
4758                                      SelectionDAG &DAG,
4759                                      const X86Subtarget* Subtarget,
4760                                      const TargetLowering &TLI) {
4761   if (NumNonZero > 4)
4762     return SDValue();
4763
4764   DebugLoc dl = Op.getDebugLoc();
4765   SDValue V(0, 0);
4766   bool First = true;
4767   for (unsigned i = 0; i < 8; ++i) {
4768     bool isNonZero = (NonZeros & (1 << i)) != 0;
4769     if (isNonZero) {
4770       if (First) {
4771         if (NumZero)
4772           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4773         else
4774           V = DAG.getUNDEF(MVT::v8i16);
4775         First = false;
4776       }
4777       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4778                       MVT::v8i16, V, Op.getOperand(i),
4779                       DAG.getIntPtrConstant(i));
4780     }
4781   }
4782
4783   return V;
4784 }
4785
4786 /// getVShift - Return a vector logical shift node.
4787 ///
4788 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4789                          unsigned NumBits, SelectionDAG &DAG,
4790                          const TargetLowering &TLI, DebugLoc dl) {
4791   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4792   EVT ShVT = MVT::v2i64;
4793   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4794   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4795   return DAG.getNode(ISD::BITCAST, dl, VT,
4796                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4797                              DAG.getConstant(NumBits,
4798                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4799 }
4800
4801 SDValue
4802 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4803                                           SelectionDAG &DAG) const {
4804
4805   // Check if the scalar load can be widened into a vector load. And if
4806   // the address is "base + cst" see if the cst can be "absorbed" into
4807   // the shuffle mask.
4808   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4809     SDValue Ptr = LD->getBasePtr();
4810     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4811       return SDValue();
4812     EVT PVT = LD->getValueType(0);
4813     if (PVT != MVT::i32 && PVT != MVT::f32)
4814       return SDValue();
4815
4816     int FI = -1;
4817     int64_t Offset = 0;
4818     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4819       FI = FINode->getIndex();
4820       Offset = 0;
4821     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4822                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4823       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4824       Offset = Ptr.getConstantOperandVal(1);
4825       Ptr = Ptr.getOperand(0);
4826     } else {
4827       return SDValue();
4828     }
4829
4830     // FIXME: 256-bit vector instructions don't require a strict alignment,
4831     // improve this code to support it better.
4832     unsigned RequiredAlign = VT.getSizeInBits()/8;
4833     SDValue Chain = LD->getChain();
4834     // Make sure the stack object alignment is at least 16 or 32.
4835     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4836     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4837       if (MFI->isFixedObjectIndex(FI)) {
4838         // Can't change the alignment. FIXME: It's possible to compute
4839         // the exact stack offset and reference FI + adjust offset instead.
4840         // If someone *really* cares about this. That's the way to implement it.
4841         return SDValue();
4842       } else {
4843         MFI->setObjectAlignment(FI, RequiredAlign);
4844       }
4845     }
4846
4847     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4848     // Ptr + (Offset & ~15).
4849     if (Offset < 0)
4850       return SDValue();
4851     if ((Offset % RequiredAlign) & 3)
4852       return SDValue();
4853     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4854     if (StartOffset)
4855       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4856                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4857
4858     int EltNo = (Offset - StartOffset) >> 2;
4859     unsigned NumElems = VT.getVectorNumElements();
4860
4861     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4862     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4863                              LD->getPointerInfo().getWithOffset(StartOffset),
4864                              false, false, false, 0);
4865
4866     SmallVector<int, 8> Mask;
4867     for (unsigned i = 0; i != NumElems; ++i)
4868       Mask.push_back(EltNo);
4869
4870     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4871   }
4872
4873   return SDValue();
4874 }
4875
4876 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4877 /// vector of type 'VT', see if the elements can be replaced by a single large
4878 /// load which has the same value as a build_vector whose operands are 'elts'.
4879 ///
4880 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4881 ///
4882 /// FIXME: we'd also like to handle the case where the last elements are zero
4883 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4884 /// There's even a handy isZeroNode for that purpose.
4885 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4886                                         DebugLoc &DL, SelectionDAG &DAG) {
4887   EVT EltVT = VT.getVectorElementType();
4888   unsigned NumElems = Elts.size();
4889
4890   LoadSDNode *LDBase = NULL;
4891   unsigned LastLoadedElt = -1U;
4892
4893   // For each element in the initializer, see if we've found a load or an undef.
4894   // If we don't find an initial load element, or later load elements are
4895   // non-consecutive, bail out.
4896   for (unsigned i = 0; i < NumElems; ++i) {
4897     SDValue Elt = Elts[i];
4898
4899     if (!Elt.getNode() ||
4900         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4901       return SDValue();
4902     if (!LDBase) {
4903       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4904         return SDValue();
4905       LDBase = cast<LoadSDNode>(Elt.getNode());
4906       LastLoadedElt = i;
4907       continue;
4908     }
4909     if (Elt.getOpcode() == ISD::UNDEF)
4910       continue;
4911
4912     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4913     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4914       return SDValue();
4915     LastLoadedElt = i;
4916   }
4917
4918   // If we have found an entire vector of loads and undefs, then return a large
4919   // load of the entire vector width starting at the base pointer.  If we found
4920   // consecutive loads for the low half, generate a vzext_load node.
4921   if (LastLoadedElt == NumElems - 1) {
4922     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4923       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4924                          LDBase->getPointerInfo(),
4925                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4926                          LDBase->isInvariant(), 0);
4927     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4928                        LDBase->getPointerInfo(),
4929                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4930                        LDBase->isInvariant(), LDBase->getAlignment());
4931   }
4932   if (NumElems == 4 && LastLoadedElt == 1 &&
4933       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4934     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4935     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4936     SDValue ResNode =
4937         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4938                                 LDBase->getPointerInfo(),
4939                                 LDBase->getAlignment(),
4940                                 false/*isVolatile*/, true/*ReadMem*/,
4941                                 false/*WriteMem*/);
4942     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4943   }
4944   return SDValue();
4945 }
4946
4947 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4948 /// to generate a splat value for the following cases:
4949 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4950 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4951 /// a scalar load, or a constant.
4952 /// The VBROADCAST node is returned when a pattern is found,
4953 /// or SDValue() otherwise.
4954 SDValue
4955 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
4956   if (!Subtarget->hasAVX())
4957     return SDValue();
4958
4959   EVT VT = Op.getValueType();
4960   DebugLoc dl = Op.getDebugLoc();
4961
4962   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4963          "Unsupported vector type for broadcast.");
4964
4965   SDValue Ld;
4966   bool ConstSplatVal;
4967
4968   switch (Op.getOpcode()) {
4969     default:
4970       // Unknown pattern found.
4971       return SDValue();
4972
4973     case ISD::BUILD_VECTOR: {
4974       // The BUILD_VECTOR node must be a splat.
4975       if (!isSplatVector(Op.getNode()))
4976         return SDValue();
4977
4978       Ld = Op.getOperand(0);
4979       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4980                      Ld.getOpcode() == ISD::ConstantFP);
4981
4982       // The suspected load node has several users. Make sure that all
4983       // of its users are from the BUILD_VECTOR node.
4984       // Constants may have multiple users.
4985       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4986         return SDValue();
4987       break;
4988     }
4989
4990     case ISD::VECTOR_SHUFFLE: {
4991       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4992
4993       // Shuffles must have a splat mask where the first element is
4994       // broadcasted.
4995       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4996         return SDValue();
4997
4998       SDValue Sc = Op.getOperand(0);
4999       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5000           Sc.getOpcode() != ISD::BUILD_VECTOR)
5001         return SDValue();
5002
5003       Ld = Sc.getOperand(0);
5004       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5005                        Ld.getOpcode() == ISD::ConstantFP);
5006
5007       // The scalar_to_vector node and the suspected
5008       // load node must have exactly one user.
5009       // Constants may have multiple users.
5010       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5011         return SDValue();
5012       break;
5013     }
5014   }
5015
5016   bool Is256 = VT.getSizeInBits() == 256;
5017
5018   // Handle the broadcasting a single constant scalar from the constant pool
5019   // into a vector. On Sandybridge it is still better to load a constant vector
5020   // from the constant pool and not to broadcast it from a scalar.
5021   if (ConstSplatVal && Subtarget->hasAVX2()) {
5022     EVT CVT = Ld.getValueType();
5023     assert(!CVT.isVector() && "Must not broadcast a vector type");
5024     unsigned ScalarSize = CVT.getSizeInBits();
5025
5026     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5027       const Constant *C = 0;
5028       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5029         C = CI->getConstantIntValue();
5030       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5031         C = CF->getConstantFPValue();
5032
5033       assert(C && "Invalid constant type");
5034
5035       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5036       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5037       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5038                        MachinePointerInfo::getConstantPool(),
5039                        false, false, false, Alignment);
5040
5041       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5042     }
5043   }
5044
5045   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5046   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5047
5048   // Handle AVX2 in-register broadcasts.
5049   if (!IsLoad && Subtarget->hasAVX2() &&
5050       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5051     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5052
5053   // The scalar source must be a normal load.
5054   if (!IsLoad)
5055     return SDValue();
5056
5057   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5058     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5059
5060   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5061   // double since there is no vbroadcastsd xmm
5062   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5063     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5064       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5065   }
5066
5067   // Unsupported broadcast.
5068   return SDValue();
5069 }
5070
5071 SDValue
5072 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5073   DebugLoc dl = Op.getDebugLoc();
5074
5075   EVT VT = Op.getValueType();
5076   EVT ExtVT = VT.getVectorElementType();
5077   unsigned NumElems = Op.getNumOperands();
5078
5079   // Vectors containing all zeros can be matched by pxor and xorps later
5080   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5081     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5082     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5083     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5084       return Op;
5085
5086     return getZeroVector(VT, Subtarget, DAG, dl);
5087   }
5088
5089   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5090   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5091   // vpcmpeqd on 256-bit vectors.
5092   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5093     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5094       return Op;
5095
5096     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5097   }
5098
5099   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5100   if (Broadcast.getNode())
5101     return Broadcast;
5102
5103   unsigned EVTBits = ExtVT.getSizeInBits();
5104
5105   unsigned NumZero  = 0;
5106   unsigned NumNonZero = 0;
5107   unsigned NonZeros = 0;
5108   bool IsAllConstants = true;
5109   SmallSet<SDValue, 8> Values;
5110   for (unsigned i = 0; i < NumElems; ++i) {
5111     SDValue Elt = Op.getOperand(i);
5112     if (Elt.getOpcode() == ISD::UNDEF)
5113       continue;
5114     Values.insert(Elt);
5115     if (Elt.getOpcode() != ISD::Constant &&
5116         Elt.getOpcode() != ISD::ConstantFP)
5117       IsAllConstants = false;
5118     if (X86::isZeroNode(Elt))
5119       NumZero++;
5120     else {
5121       NonZeros |= (1 << i);
5122       NumNonZero++;
5123     }
5124   }
5125
5126   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5127   if (NumNonZero == 0)
5128     return DAG.getUNDEF(VT);
5129
5130   // Special case for single non-zero, non-undef, element.
5131   if (NumNonZero == 1) {
5132     unsigned Idx = CountTrailingZeros_32(NonZeros);
5133     SDValue Item = Op.getOperand(Idx);
5134
5135     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5136     // the value are obviously zero, truncate the value to i32 and do the
5137     // insertion that way.  Only do this if the value is non-constant or if the
5138     // value is a constant being inserted into element 0.  It is cheaper to do
5139     // a constant pool load than it is to do a movd + shuffle.
5140     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5141         (!IsAllConstants || Idx == 0)) {
5142       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5143         // Handle SSE only.
5144         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5145         EVT VecVT = MVT::v4i32;
5146         unsigned VecElts = 4;
5147
5148         // Truncate the value (which may itself be a constant) to i32, and
5149         // convert it to a vector with movd (S2V+shuffle to zero extend).
5150         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5151         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5152         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5153
5154         // Now we have our 32-bit value zero extended in the low element of
5155         // a vector.  If Idx != 0, swizzle it into place.
5156         if (Idx != 0) {
5157           SmallVector<int, 4> Mask;
5158           Mask.push_back(Idx);
5159           for (unsigned i = 1; i != VecElts; ++i)
5160             Mask.push_back(i);
5161           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5162                                       &Mask[0]);
5163         }
5164         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5165       }
5166     }
5167
5168     // If we have a constant or non-constant insertion into the low element of
5169     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5170     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5171     // depending on what the source datatype is.
5172     if (Idx == 0) {
5173       if (NumZero == 0)
5174         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5175
5176       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5177           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5178         if (VT.getSizeInBits() == 256) {
5179           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5180           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5181                              Item, DAG.getIntPtrConstant(0));
5182         }
5183         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5184         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5185         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5186         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5187       }
5188
5189       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5190         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5191         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5192         if (VT.getSizeInBits() == 256) {
5193           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5194           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5195         } else {
5196           assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5197           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5198         }
5199         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5200       }
5201     }
5202
5203     // Is it a vector logical left shift?
5204     if (NumElems == 2 && Idx == 1 &&
5205         X86::isZeroNode(Op.getOperand(0)) &&
5206         !X86::isZeroNode(Op.getOperand(1))) {
5207       unsigned NumBits = VT.getSizeInBits();
5208       return getVShift(true, VT,
5209                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5210                                    VT, Op.getOperand(1)),
5211                        NumBits/2, DAG, *this, dl);
5212     }
5213
5214     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5215       return SDValue();
5216
5217     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5218     // is a non-constant being inserted into an element other than the low one,
5219     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5220     // movd/movss) to move this into the low element, then shuffle it into
5221     // place.
5222     if (EVTBits == 32) {
5223       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5224
5225       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5226       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5227       SmallVector<int, 8> MaskVec;
5228       for (unsigned i = 0; i != NumElems; ++i)
5229         MaskVec.push_back(i == Idx ? 0 : 1);
5230       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5231     }
5232   }
5233
5234   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5235   if (Values.size() == 1) {
5236     if (EVTBits == 32) {
5237       // Instead of a shuffle like this:
5238       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5239       // Check if it's possible to issue this instead.
5240       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5241       unsigned Idx = CountTrailingZeros_32(NonZeros);
5242       SDValue Item = Op.getOperand(Idx);
5243       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5244         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5245     }
5246     return SDValue();
5247   }
5248
5249   // A vector full of immediates; various special cases are already
5250   // handled, so this is best done with a single constant-pool load.
5251   if (IsAllConstants)
5252     return SDValue();
5253
5254   // For AVX-length vectors, build the individual 128-bit pieces and use
5255   // shuffles to put them in place.
5256   if (VT.getSizeInBits() == 256) {
5257     SmallVector<SDValue, 32> V;
5258     for (unsigned i = 0; i != NumElems; ++i)
5259       V.push_back(Op.getOperand(i));
5260
5261     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5262
5263     // Build both the lower and upper subvector.
5264     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5265     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5266                                 NumElems/2);
5267
5268     // Recreate the wider vector with the lower and upper part.
5269     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5270   }
5271
5272   // Let legalizer expand 2-wide build_vectors.
5273   if (EVTBits == 64) {
5274     if (NumNonZero == 1) {
5275       // One half is zero or undef.
5276       unsigned Idx = CountTrailingZeros_32(NonZeros);
5277       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5278                                  Op.getOperand(Idx));
5279       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5280     }
5281     return SDValue();
5282   }
5283
5284   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5285   if (EVTBits == 8 && NumElems == 16) {
5286     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5287                                         Subtarget, *this);
5288     if (V.getNode()) return V;
5289   }
5290
5291   if (EVTBits == 16 && NumElems == 8) {
5292     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5293                                       Subtarget, *this);
5294     if (V.getNode()) return V;
5295   }
5296
5297   // If element VT is == 32 bits, turn it into a number of shuffles.
5298   SmallVector<SDValue, 8> V(NumElems);
5299   if (NumElems == 4 && NumZero > 0) {
5300     for (unsigned i = 0; i < 4; ++i) {
5301       bool isZero = !(NonZeros & (1 << i));
5302       if (isZero)
5303         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5304       else
5305         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5306     }
5307
5308     for (unsigned i = 0; i < 2; ++i) {
5309       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5310         default: break;
5311         case 0:
5312           V[i] = V[i*2];  // Must be a zero vector.
5313           break;
5314         case 1:
5315           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5316           break;
5317         case 2:
5318           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5319           break;
5320         case 3:
5321           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5322           break;
5323       }
5324     }
5325
5326     bool Reverse1 = (NonZeros & 0x3) == 2;
5327     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5328     int MaskVec[] = {
5329       Reverse1 ? 1 : 0,
5330       Reverse1 ? 0 : 1,
5331       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5332       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5333     };
5334     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5335   }
5336
5337   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5338     // Check for a build vector of consecutive loads.
5339     for (unsigned i = 0; i < NumElems; ++i)
5340       V[i] = Op.getOperand(i);
5341
5342     // Check for elements which are consecutive loads.
5343     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5344     if (LD.getNode())
5345       return LD;
5346
5347     // For SSE 4.1, use insertps to put the high elements into the low element.
5348     if (getSubtarget()->hasSSE41()) {
5349       SDValue Result;
5350       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5351         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5352       else
5353         Result = DAG.getUNDEF(VT);
5354
5355       for (unsigned i = 1; i < NumElems; ++i) {
5356         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5357         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5358                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5359       }
5360       return Result;
5361     }
5362
5363     // Otherwise, expand into a number of unpckl*, start by extending each of
5364     // our (non-undef) elements to the full vector width with the element in the
5365     // bottom slot of the vector (which generates no code for SSE).
5366     for (unsigned i = 0; i < NumElems; ++i) {
5367       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5368         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5369       else
5370         V[i] = DAG.getUNDEF(VT);
5371     }
5372
5373     // Next, we iteratively mix elements, e.g. for v4f32:
5374     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5375     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5376     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5377     unsigned EltStride = NumElems >> 1;
5378     while (EltStride != 0) {
5379       for (unsigned i = 0; i < EltStride; ++i) {
5380         // If V[i+EltStride] is undef and this is the first round of mixing,
5381         // then it is safe to just drop this shuffle: V[i] is already in the
5382         // right place, the one element (since it's the first round) being
5383         // inserted as undef can be dropped.  This isn't safe for successive
5384         // rounds because they will permute elements within both vectors.
5385         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5386             EltStride == NumElems/2)
5387           continue;
5388
5389         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5390       }
5391       EltStride >>= 1;
5392     }
5393     return V[0];
5394   }
5395   return SDValue();
5396 }
5397
5398 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5399 // them in a MMX register.  This is better than doing a stack convert.
5400 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5401   DebugLoc dl = Op.getDebugLoc();
5402   EVT ResVT = Op.getValueType();
5403
5404   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5405          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5406   int Mask[2];
5407   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5408   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5409   InVec = Op.getOperand(1);
5410   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5411     unsigned NumElts = ResVT.getVectorNumElements();
5412     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5413     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5414                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5415   } else {
5416     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5417     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5418     Mask[0] = 0; Mask[1] = 2;
5419     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5420   }
5421   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5422 }
5423
5424 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5425 // to create 256-bit vectors from two other 128-bit ones.
5426 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5427   DebugLoc dl = Op.getDebugLoc();
5428   EVT ResVT = Op.getValueType();
5429
5430   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5431
5432   SDValue V1 = Op.getOperand(0);
5433   SDValue V2 = Op.getOperand(1);
5434   unsigned NumElems = ResVT.getVectorNumElements();
5435
5436   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5437 }
5438
5439 SDValue
5440 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5441   EVT ResVT = Op.getValueType();
5442
5443   assert(Op.getNumOperands() == 2);
5444   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5445          "Unsupported CONCAT_VECTORS for value type");
5446
5447   // We support concatenate two MMX registers and place them in a MMX register.
5448   // This is better than doing a stack convert.
5449   if (ResVT.is128BitVector())
5450     return LowerMMXCONCAT_VECTORS(Op, DAG);
5451
5452   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5453   // from two other 128-bit ones.
5454   return LowerAVXCONCAT_VECTORS(Op, DAG);
5455 }
5456
5457 // Try to lower a shuffle node into a simple blend instruction.
5458 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5459                                           const X86Subtarget *Subtarget,
5460                                           SelectionDAG &DAG) {
5461   SDValue V1 = SVOp->getOperand(0);
5462   SDValue V2 = SVOp->getOperand(1);
5463   DebugLoc dl = SVOp->getDebugLoc();
5464   MVT VT = SVOp->getValueType(0).getSimpleVT();
5465   unsigned NumElems = VT.getVectorNumElements();
5466
5467   if (!Subtarget->hasSSE41())
5468     return SDValue();
5469
5470   unsigned ISDNo = 0;
5471   MVT OpTy;
5472
5473   switch (VT.SimpleTy) {
5474   default: return SDValue();
5475   case MVT::v8i16:
5476     ISDNo = X86ISD::BLENDPW;
5477     OpTy = MVT::v8i16;
5478     break;
5479   case MVT::v4i32:
5480   case MVT::v4f32:
5481     ISDNo = X86ISD::BLENDPS;
5482     OpTy = MVT::v4f32;
5483     break;
5484   case MVT::v2i64:
5485   case MVT::v2f64:
5486     ISDNo = X86ISD::BLENDPD;
5487     OpTy = MVT::v2f64;
5488     break;
5489   case MVT::v8i32:
5490   case MVT::v8f32:
5491     if (!Subtarget->hasAVX())
5492       return SDValue();
5493     ISDNo = X86ISD::BLENDPS;
5494     OpTy = MVT::v8f32;
5495     break;
5496   case MVT::v4i64:
5497   case MVT::v4f64:
5498     if (!Subtarget->hasAVX())
5499       return SDValue();
5500     ISDNo = X86ISD::BLENDPD;
5501     OpTy = MVT::v4f64;
5502     break;
5503   }
5504   assert(ISDNo && "Invalid Op Number");
5505
5506   unsigned MaskVals = 0;
5507
5508   for (unsigned i = 0; i != NumElems; ++i) {
5509     int EltIdx = SVOp->getMaskElt(i);
5510     if (EltIdx == (int)i || EltIdx < 0)
5511       MaskVals |= (1<<i);
5512     else if (EltIdx == (int)(i + NumElems))
5513       continue; // Bit is set to zero;
5514     else
5515       return SDValue();
5516   }
5517
5518   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5519   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5520   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5521                              DAG.getConstant(MaskVals, MVT::i32));
5522   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5523 }
5524
5525 // v8i16 shuffles - Prefer shuffles in the following order:
5526 // 1. [all]   pshuflw, pshufhw, optional move
5527 // 2. [ssse3] 1 x pshufb
5528 // 3. [ssse3] 2 x pshufb + 1 x por
5529 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5530 SDValue
5531 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5532                                             SelectionDAG &DAG) const {
5533   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5534   SDValue V1 = SVOp->getOperand(0);
5535   SDValue V2 = SVOp->getOperand(1);
5536   DebugLoc dl = SVOp->getDebugLoc();
5537   SmallVector<int, 8> MaskVals;
5538
5539   // Determine if more than 1 of the words in each of the low and high quadwords
5540   // of the result come from the same quadword of one of the two inputs.  Undef
5541   // mask values count as coming from any quadword, for better codegen.
5542   unsigned LoQuad[] = { 0, 0, 0, 0 };
5543   unsigned HiQuad[] = { 0, 0, 0, 0 };
5544   std::bitset<4> InputQuads;
5545   for (unsigned i = 0; i < 8; ++i) {
5546     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5547     int EltIdx = SVOp->getMaskElt(i);
5548     MaskVals.push_back(EltIdx);
5549     if (EltIdx < 0) {
5550       ++Quad[0];
5551       ++Quad[1];
5552       ++Quad[2];
5553       ++Quad[3];
5554       continue;
5555     }
5556     ++Quad[EltIdx / 4];
5557     InputQuads.set(EltIdx / 4);
5558   }
5559
5560   int BestLoQuad = -1;
5561   unsigned MaxQuad = 1;
5562   for (unsigned i = 0; i < 4; ++i) {
5563     if (LoQuad[i] > MaxQuad) {
5564       BestLoQuad = i;
5565       MaxQuad = LoQuad[i];
5566     }
5567   }
5568
5569   int BestHiQuad = -1;
5570   MaxQuad = 1;
5571   for (unsigned i = 0; i < 4; ++i) {
5572     if (HiQuad[i] > MaxQuad) {
5573       BestHiQuad = i;
5574       MaxQuad = HiQuad[i];
5575     }
5576   }
5577
5578   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5579   // of the two input vectors, shuffle them into one input vector so only a
5580   // single pshufb instruction is necessary. If There are more than 2 input
5581   // quads, disable the next transformation since it does not help SSSE3.
5582   bool V1Used = InputQuads[0] || InputQuads[1];
5583   bool V2Used = InputQuads[2] || InputQuads[3];
5584   if (Subtarget->hasSSSE3()) {
5585     if (InputQuads.count() == 2 && V1Used && V2Used) {
5586       BestLoQuad = InputQuads[0] ? 0 : 1;
5587       BestHiQuad = InputQuads[2] ? 2 : 3;
5588     }
5589     if (InputQuads.count() > 2) {
5590       BestLoQuad = -1;
5591       BestHiQuad = -1;
5592     }
5593   }
5594
5595   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5596   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5597   // words from all 4 input quadwords.
5598   SDValue NewV;
5599   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5600     int MaskV[] = {
5601       BestLoQuad < 0 ? 0 : BestLoQuad,
5602       BestHiQuad < 0 ? 1 : BestHiQuad
5603     };
5604     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5605                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5606                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5607     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5608
5609     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5610     // source words for the shuffle, to aid later transformations.
5611     bool AllWordsInNewV = true;
5612     bool InOrder[2] = { true, true };
5613     for (unsigned i = 0; i != 8; ++i) {
5614       int idx = MaskVals[i];
5615       if (idx != (int)i)
5616         InOrder[i/4] = false;
5617       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5618         continue;
5619       AllWordsInNewV = false;
5620       break;
5621     }
5622
5623     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5624     if (AllWordsInNewV) {
5625       for (int i = 0; i != 8; ++i) {
5626         int idx = MaskVals[i];
5627         if (idx < 0)
5628           continue;
5629         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5630         if ((idx != i) && idx < 4)
5631           pshufhw = false;
5632         if ((idx != i) && idx > 3)
5633           pshuflw = false;
5634       }
5635       V1 = NewV;
5636       V2Used = false;
5637       BestLoQuad = 0;
5638       BestHiQuad = 1;
5639     }
5640
5641     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5642     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5643     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5644       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5645       unsigned TargetMask = 0;
5646       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5647                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5648       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5649       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5650                              getShufflePSHUFLWImmediate(SVOp);
5651       V1 = NewV.getOperand(0);
5652       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5653     }
5654   }
5655
5656   // If we have SSSE3, and all words of the result are from 1 input vector,
5657   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5658   // is present, fall back to case 4.
5659   if (Subtarget->hasSSSE3()) {
5660     SmallVector<SDValue,16> pshufbMask;
5661
5662     // If we have elements from both input vectors, set the high bit of the
5663     // shuffle mask element to zero out elements that come from V2 in the V1
5664     // mask, and elements that come from V1 in the V2 mask, so that the two
5665     // results can be OR'd together.
5666     bool TwoInputs = V1Used && V2Used;
5667     for (unsigned i = 0; i != 8; ++i) {
5668       int EltIdx = MaskVals[i] * 2;
5669       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5670       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5671       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5672       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5673     }
5674     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5675     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5676                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5677                                  MVT::v16i8, &pshufbMask[0], 16));
5678     if (!TwoInputs)
5679       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5680
5681     // Calculate the shuffle mask for the second input, shuffle it, and
5682     // OR it with the first shuffled input.
5683     pshufbMask.clear();
5684     for (unsigned i = 0; i != 8; ++i) {
5685       int EltIdx = MaskVals[i] * 2;
5686       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5687       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5688       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5689       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5690     }
5691     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5692     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5693                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5694                                  MVT::v16i8, &pshufbMask[0], 16));
5695     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5696     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5697   }
5698
5699   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5700   // and update MaskVals with new element order.
5701   std::bitset<8> InOrder;
5702   if (BestLoQuad >= 0) {
5703     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5704     for (int i = 0; i != 4; ++i) {
5705       int idx = MaskVals[i];
5706       if (idx < 0) {
5707         InOrder.set(i);
5708       } else if ((idx / 4) == BestLoQuad) {
5709         MaskV[i] = idx & 3;
5710         InOrder.set(i);
5711       }
5712     }
5713     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5714                                 &MaskV[0]);
5715
5716     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5717       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5718       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5719                                   NewV.getOperand(0),
5720                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5721     }
5722   }
5723
5724   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5725   // and update MaskVals with the new element order.
5726   if (BestHiQuad >= 0) {
5727     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5728     for (unsigned i = 4; i != 8; ++i) {
5729       int idx = MaskVals[i];
5730       if (idx < 0) {
5731         InOrder.set(i);
5732       } else if ((idx / 4) == BestHiQuad) {
5733         MaskV[i] = (idx & 3) + 4;
5734         InOrder.set(i);
5735       }
5736     }
5737     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5738                                 &MaskV[0]);
5739
5740     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5741       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5742       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5743                                   NewV.getOperand(0),
5744                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5745     }
5746   }
5747
5748   // In case BestHi & BestLo were both -1, which means each quadword has a word
5749   // from each of the four input quadwords, calculate the InOrder bitvector now
5750   // before falling through to the insert/extract cleanup.
5751   if (BestLoQuad == -1 && BestHiQuad == -1) {
5752     NewV = V1;
5753     for (int i = 0; i != 8; ++i)
5754       if (MaskVals[i] < 0 || MaskVals[i] == i)
5755         InOrder.set(i);
5756   }
5757
5758   // The other elements are put in the right place using pextrw and pinsrw.
5759   for (unsigned i = 0; i != 8; ++i) {
5760     if (InOrder[i])
5761       continue;
5762     int EltIdx = MaskVals[i];
5763     if (EltIdx < 0)
5764       continue;
5765     SDValue ExtOp = (EltIdx < 8) ?
5766       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5767                   DAG.getIntPtrConstant(EltIdx)) :
5768       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5769                   DAG.getIntPtrConstant(EltIdx - 8));
5770     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5771                        DAG.getIntPtrConstant(i));
5772   }
5773   return NewV;
5774 }
5775
5776 // v16i8 shuffles - Prefer shuffles in the following order:
5777 // 1. [ssse3] 1 x pshufb
5778 // 2. [ssse3] 2 x pshufb + 1 x por
5779 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5780 static
5781 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5782                                  SelectionDAG &DAG,
5783                                  const X86TargetLowering &TLI) {
5784   SDValue V1 = SVOp->getOperand(0);
5785   SDValue V2 = SVOp->getOperand(1);
5786   DebugLoc dl = SVOp->getDebugLoc();
5787   ArrayRef<int> MaskVals = SVOp->getMask();
5788
5789   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5790
5791   // If we have SSSE3, case 1 is generated when all result bytes come from
5792   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5793   // present, fall back to case 3.
5794
5795   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5796   if (TLI.getSubtarget()->hasSSSE3()) {
5797     SmallVector<SDValue,16> pshufbMask;
5798
5799     // If all result elements are from one input vector, then only translate
5800     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5801     //
5802     // Otherwise, we have elements from both input vectors, and must zero out
5803     // elements that come from V2 in the first mask, and V1 in the second mask
5804     // so that we can OR them together.
5805     for (unsigned i = 0; i != 16; ++i) {
5806       int EltIdx = MaskVals[i];
5807       if (EltIdx < 0 || EltIdx >= 16)
5808         EltIdx = 0x80;
5809       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5810     }
5811     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5812                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5813                                  MVT::v16i8, &pshufbMask[0], 16));
5814     if (V2IsUndef)
5815       return V1;
5816
5817     // Calculate the shuffle mask for the second input, shuffle it, and
5818     // OR it with the first shuffled input.
5819     pshufbMask.clear();
5820     for (unsigned i = 0; i != 16; ++i) {
5821       int EltIdx = MaskVals[i];
5822       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5823       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5824     }
5825     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5826                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5827                                  MVT::v16i8, &pshufbMask[0], 16));
5828     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5829   }
5830
5831   // No SSSE3 - Calculate in place words and then fix all out of place words
5832   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5833   // the 16 different words that comprise the two doublequadword input vectors.
5834   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5835   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5836   SDValue NewV = V1;
5837   for (int i = 0; i != 8; ++i) {
5838     int Elt0 = MaskVals[i*2];
5839     int Elt1 = MaskVals[i*2+1];
5840
5841     // This word of the result is all undef, skip it.
5842     if (Elt0 < 0 && Elt1 < 0)
5843       continue;
5844
5845     // This word of the result is already in the correct place, skip it.
5846     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5847       continue;
5848
5849     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5850     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5851     SDValue InsElt;
5852
5853     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5854     // using a single extract together, load it and store it.
5855     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5856       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5857                            DAG.getIntPtrConstant(Elt1 / 2));
5858       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5859                         DAG.getIntPtrConstant(i));
5860       continue;
5861     }
5862
5863     // If Elt1 is defined, extract it from the appropriate source.  If the
5864     // source byte is not also odd, shift the extracted word left 8 bits
5865     // otherwise clear the bottom 8 bits if we need to do an or.
5866     if (Elt1 >= 0) {
5867       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5868                            DAG.getIntPtrConstant(Elt1 / 2));
5869       if ((Elt1 & 1) == 0)
5870         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5871                              DAG.getConstant(8,
5872                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5873       else if (Elt0 >= 0)
5874         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5875                              DAG.getConstant(0xFF00, MVT::i16));
5876     }
5877     // If Elt0 is defined, extract it from the appropriate source.  If the
5878     // source byte is not also even, shift the extracted word right 8 bits. If
5879     // Elt1 was also defined, OR the extracted values together before
5880     // inserting them in the result.
5881     if (Elt0 >= 0) {
5882       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5883                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5884       if ((Elt0 & 1) != 0)
5885         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5886                               DAG.getConstant(8,
5887                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5888       else if (Elt1 >= 0)
5889         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5890                              DAG.getConstant(0x00FF, MVT::i16));
5891       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5892                          : InsElt0;
5893     }
5894     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5895                        DAG.getIntPtrConstant(i));
5896   }
5897   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5898 }
5899
5900 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5901 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5902 /// done when every pair / quad of shuffle mask elements point to elements in
5903 /// the right sequence. e.g.
5904 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5905 static
5906 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5907                                  SelectionDAG &DAG, DebugLoc dl) {
5908   MVT VT = SVOp->getValueType(0).getSimpleVT();
5909   unsigned NumElems = VT.getVectorNumElements();
5910   MVT NewVT;
5911   unsigned Scale;
5912   switch (VT.SimpleTy) {
5913   default: llvm_unreachable("Unexpected!");
5914   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
5915   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
5916   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
5917   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
5918   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5919   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
5920   }
5921
5922   SmallVector<int, 8> MaskVec;
5923   for (unsigned i = 0; i != NumElems; i += Scale) {
5924     int StartIdx = -1;
5925     for (unsigned j = 0; j != Scale; ++j) {
5926       int EltIdx = SVOp->getMaskElt(i+j);
5927       if (EltIdx < 0)
5928         continue;
5929       if (StartIdx < 0)
5930         StartIdx = (EltIdx / Scale);
5931       if (EltIdx != (int)(StartIdx*Scale + j))
5932         return SDValue();
5933     }
5934     MaskVec.push_back(StartIdx);
5935   }
5936
5937   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
5938   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
5939   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5940 }
5941
5942 /// getVZextMovL - Return a zero-extending vector move low node.
5943 ///
5944 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5945                             SDValue SrcOp, SelectionDAG &DAG,
5946                             const X86Subtarget *Subtarget, DebugLoc dl) {
5947   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5948     LoadSDNode *LD = NULL;
5949     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5950       LD = dyn_cast<LoadSDNode>(SrcOp);
5951     if (!LD) {
5952       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5953       // instead.
5954       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5955       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5956           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5957           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5958           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5959         // PR2108
5960         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5961         return DAG.getNode(ISD::BITCAST, dl, VT,
5962                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5963                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5964                                                    OpVT,
5965                                                    SrcOp.getOperand(0)
5966                                                           .getOperand(0))));
5967       }
5968     }
5969   }
5970
5971   return DAG.getNode(ISD::BITCAST, dl, VT,
5972                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5973                                  DAG.getNode(ISD::BITCAST, dl,
5974                                              OpVT, SrcOp)));
5975 }
5976
5977 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5978 /// which could not be matched by any known target speficic shuffle
5979 static SDValue
5980 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5981   EVT VT = SVOp->getValueType(0);
5982
5983   unsigned NumElems = VT.getVectorNumElements();
5984   unsigned NumLaneElems = NumElems / 2;
5985
5986   DebugLoc dl = SVOp->getDebugLoc();
5987   MVT EltVT = VT.getVectorElementType().getSimpleVT();
5988   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
5989   SDValue Output[2];
5990
5991   SmallVector<int, 16> Mask;
5992   for (unsigned l = 0; l < 2; ++l) {
5993     // Build a shuffle mask for the output, discovering on the fly which
5994     // input vectors to use as shuffle operands (recorded in InputUsed).
5995     // If building a suitable shuffle vector proves too hard, then bail
5996     // out with UseBuildVector set.
5997     bool UseBuildVector = false;
5998     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
5999     unsigned LaneStart = l * NumLaneElems;
6000     for (unsigned i = 0; i != NumLaneElems; ++i) {
6001       // The mask element.  This indexes into the input.
6002       int Idx = SVOp->getMaskElt(i+LaneStart);
6003       if (Idx < 0) {
6004         // the mask element does not index into any input vector.
6005         Mask.push_back(-1);
6006         continue;
6007       }
6008
6009       // The input vector this mask element indexes into.
6010       int Input = Idx / NumLaneElems;
6011
6012       // Turn the index into an offset from the start of the input vector.
6013       Idx -= Input * NumLaneElems;
6014
6015       // Find or create a shuffle vector operand to hold this input.
6016       unsigned OpNo;
6017       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6018         if (InputUsed[OpNo] == Input)
6019           // This input vector is already an operand.
6020           break;
6021         if (InputUsed[OpNo] < 0) {
6022           // Create a new operand for this input vector.
6023           InputUsed[OpNo] = Input;
6024           break;
6025         }
6026       }
6027
6028       if (OpNo >= array_lengthof(InputUsed)) {
6029         // More than two input vectors used!  Give up on trying to create a
6030         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6031         UseBuildVector = true;
6032         break;
6033       }
6034
6035       // Add the mask index for the new shuffle vector.
6036       Mask.push_back(Idx + OpNo * NumLaneElems);
6037     }
6038
6039     if (UseBuildVector) {
6040       SmallVector<SDValue, 16> SVOps;
6041       for (unsigned i = 0; i != NumLaneElems; ++i) {
6042         // The mask element.  This indexes into the input.
6043         int Idx = SVOp->getMaskElt(i+LaneStart);
6044         if (Idx < 0) {
6045           SVOps.push_back(DAG.getUNDEF(EltVT));
6046           continue;
6047         }
6048
6049         // The input vector this mask element indexes into.
6050         int Input = Idx / NumElems;
6051
6052         // Turn the index into an offset from the start of the input vector.
6053         Idx -= Input * NumElems;
6054
6055         // Extract the vector element by hand.
6056         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6057                                     SVOp->getOperand(Input),
6058                                     DAG.getIntPtrConstant(Idx)));
6059       }
6060
6061       // Construct the output using a BUILD_VECTOR.
6062       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6063                               SVOps.size());
6064     } else if (InputUsed[0] < 0) {
6065       // No input vectors were used! The result is undefined.
6066       Output[l] = DAG.getUNDEF(NVT);
6067     } else {
6068       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6069                                         (InputUsed[0] % 2) * NumLaneElems,
6070                                         DAG, dl);
6071       // If only one input was used, use an undefined vector for the other.
6072       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6073         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6074                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6075       // At least one input vector was used. Create a new shuffle vector.
6076       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6077     }
6078
6079     Mask.clear();
6080   }
6081
6082   // Concatenate the result back
6083   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6084 }
6085
6086 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6087 /// 4 elements, and match them with several different shuffle types.
6088 static SDValue
6089 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6090   SDValue V1 = SVOp->getOperand(0);
6091   SDValue V2 = SVOp->getOperand(1);
6092   DebugLoc dl = SVOp->getDebugLoc();
6093   EVT VT = SVOp->getValueType(0);
6094
6095   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6096
6097   std::pair<int, int> Locs[4];
6098   int Mask1[] = { -1, -1, -1, -1 };
6099   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6100
6101   unsigned NumHi = 0;
6102   unsigned NumLo = 0;
6103   for (unsigned i = 0; i != 4; ++i) {
6104     int Idx = PermMask[i];
6105     if (Idx < 0) {
6106       Locs[i] = std::make_pair(-1, -1);
6107     } else {
6108       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6109       if (Idx < 4) {
6110         Locs[i] = std::make_pair(0, NumLo);
6111         Mask1[NumLo] = Idx;
6112         NumLo++;
6113       } else {
6114         Locs[i] = std::make_pair(1, NumHi);
6115         if (2+NumHi < 4)
6116           Mask1[2+NumHi] = Idx;
6117         NumHi++;
6118       }
6119     }
6120   }
6121
6122   if (NumLo <= 2 && NumHi <= 2) {
6123     // If no more than two elements come from either vector. This can be
6124     // implemented with two shuffles. First shuffle gather the elements.
6125     // The second shuffle, which takes the first shuffle as both of its
6126     // vector operands, put the elements into the right order.
6127     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6128
6129     int Mask2[] = { -1, -1, -1, -1 };
6130
6131     for (unsigned i = 0; i != 4; ++i)
6132       if (Locs[i].first != -1) {
6133         unsigned Idx = (i < 2) ? 0 : 4;
6134         Idx += Locs[i].first * 2 + Locs[i].second;
6135         Mask2[i] = Idx;
6136       }
6137
6138     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6139   }
6140
6141   if (NumLo == 3 || NumHi == 3) {
6142     // Otherwise, we must have three elements from one vector, call it X, and
6143     // one element from the other, call it Y.  First, use a shufps to build an
6144     // intermediate vector with the one element from Y and the element from X
6145     // that will be in the same half in the final destination (the indexes don't
6146     // matter). Then, use a shufps to build the final vector, taking the half
6147     // containing the element from Y from the intermediate, and the other half
6148     // from X.
6149     if (NumHi == 3) {
6150       // Normalize it so the 3 elements come from V1.
6151       CommuteVectorShuffleMask(PermMask, 4);
6152       std::swap(V1, V2);
6153     }
6154
6155     // Find the element from V2.
6156     unsigned HiIndex;
6157     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6158       int Val = PermMask[HiIndex];
6159       if (Val < 0)
6160         continue;
6161       if (Val >= 4)
6162         break;
6163     }
6164
6165     Mask1[0] = PermMask[HiIndex];
6166     Mask1[1] = -1;
6167     Mask1[2] = PermMask[HiIndex^1];
6168     Mask1[3] = -1;
6169     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6170
6171     if (HiIndex >= 2) {
6172       Mask1[0] = PermMask[0];
6173       Mask1[1] = PermMask[1];
6174       Mask1[2] = HiIndex & 1 ? 6 : 4;
6175       Mask1[3] = HiIndex & 1 ? 4 : 6;
6176       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6177     }
6178
6179     Mask1[0] = HiIndex & 1 ? 2 : 0;
6180     Mask1[1] = HiIndex & 1 ? 0 : 2;
6181     Mask1[2] = PermMask[2];
6182     Mask1[3] = PermMask[3];
6183     if (Mask1[2] >= 0)
6184       Mask1[2] += 4;
6185     if (Mask1[3] >= 0)
6186       Mask1[3] += 4;
6187     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6188   }
6189
6190   // Break it into (shuffle shuffle_hi, shuffle_lo).
6191   int LoMask[] = { -1, -1, -1, -1 };
6192   int HiMask[] = { -1, -1, -1, -1 };
6193
6194   int *MaskPtr = LoMask;
6195   unsigned MaskIdx = 0;
6196   unsigned LoIdx = 0;
6197   unsigned HiIdx = 2;
6198   for (unsigned i = 0; i != 4; ++i) {
6199     if (i == 2) {
6200       MaskPtr = HiMask;
6201       MaskIdx = 1;
6202       LoIdx = 0;
6203       HiIdx = 2;
6204     }
6205     int Idx = PermMask[i];
6206     if (Idx < 0) {
6207       Locs[i] = std::make_pair(-1, -1);
6208     } else if (Idx < 4) {
6209       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6210       MaskPtr[LoIdx] = Idx;
6211       LoIdx++;
6212     } else {
6213       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6214       MaskPtr[HiIdx] = Idx;
6215       HiIdx++;
6216     }
6217   }
6218
6219   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6220   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6221   int MaskOps[] = { -1, -1, -1, -1 };
6222   for (unsigned i = 0; i != 4; ++i)
6223     if (Locs[i].first != -1)
6224       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6225   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6226 }
6227
6228 static bool MayFoldVectorLoad(SDValue V) {
6229   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6230     V = V.getOperand(0);
6231   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6232     V = V.getOperand(0);
6233   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6234       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6235     // BUILD_VECTOR (load), undef
6236     V = V.getOperand(0);
6237   if (MayFoldLoad(V))
6238     return true;
6239   return false;
6240 }
6241
6242 // FIXME: the version above should always be used. Since there's
6243 // a bug where several vector shuffles can't be folded because the
6244 // DAG is not updated during lowering and a node claims to have two
6245 // uses while it only has one, use this version, and let isel match
6246 // another instruction if the load really happens to have more than
6247 // one use. Remove this version after this bug get fixed.
6248 // rdar://8434668, PR8156
6249 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6250   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6251     V = V.getOperand(0);
6252   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6253     V = V.getOperand(0);
6254   if (ISD::isNormalLoad(V.getNode()))
6255     return true;
6256   return false;
6257 }
6258
6259 static
6260 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6261   EVT VT = Op.getValueType();
6262
6263   // Canonizalize to v2f64.
6264   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6265   return DAG.getNode(ISD::BITCAST, dl, VT,
6266                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6267                                           V1, DAG));
6268 }
6269
6270 static
6271 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6272                         bool HasSSE2) {
6273   SDValue V1 = Op.getOperand(0);
6274   SDValue V2 = Op.getOperand(1);
6275   EVT VT = Op.getValueType();
6276
6277   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6278
6279   if (HasSSE2 && VT == MVT::v2f64)
6280     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6281
6282   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6283   return DAG.getNode(ISD::BITCAST, dl, VT,
6284                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6285                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6286                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6287 }
6288
6289 static
6290 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6291   SDValue V1 = Op.getOperand(0);
6292   SDValue V2 = Op.getOperand(1);
6293   EVT VT = Op.getValueType();
6294
6295   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6296          "unsupported shuffle type");
6297
6298   if (V2.getOpcode() == ISD::UNDEF)
6299     V2 = V1;
6300
6301   // v4i32 or v4f32
6302   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6303 }
6304
6305 static
6306 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6307   SDValue V1 = Op.getOperand(0);
6308   SDValue V2 = Op.getOperand(1);
6309   EVT VT = Op.getValueType();
6310   unsigned NumElems = VT.getVectorNumElements();
6311
6312   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6313   // operand of these instructions is only memory, so check if there's a
6314   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6315   // same masks.
6316   bool CanFoldLoad = false;
6317
6318   // Trivial case, when V2 comes from a load.
6319   if (MayFoldVectorLoad(V2))
6320     CanFoldLoad = true;
6321
6322   // When V1 is a load, it can be folded later into a store in isel, example:
6323   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6324   //    turns into:
6325   //  (MOVLPSmr addr:$src1, VR128:$src2)
6326   // So, recognize this potential and also use MOVLPS or MOVLPD
6327   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6328     CanFoldLoad = true;
6329
6330   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6331   if (CanFoldLoad) {
6332     if (HasSSE2 && NumElems == 2)
6333       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6334
6335     if (NumElems == 4)
6336       // If we don't care about the second element, proceed to use movss.
6337       if (SVOp->getMaskElt(1) != -1)
6338         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6339   }
6340
6341   // movl and movlp will both match v2i64, but v2i64 is never matched by
6342   // movl earlier because we make it strict to avoid messing with the movlp load
6343   // folding logic (see the code above getMOVLP call). Match it here then,
6344   // this is horrible, but will stay like this until we move all shuffle
6345   // matching to x86 specific nodes. Note that for the 1st condition all
6346   // types are matched with movsd.
6347   if (HasSSE2) {
6348     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6349     // as to remove this logic from here, as much as possible
6350     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6351       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6352     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6353   }
6354
6355   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6356
6357   // Invert the operand order and use SHUFPS to match it.
6358   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6359                               getShuffleSHUFImmediate(SVOp), DAG);
6360 }
6361
6362 SDValue
6363 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6364   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6365   EVT VT = Op.getValueType();
6366   DebugLoc dl = Op.getDebugLoc();
6367   SDValue V1 = Op.getOperand(0);
6368   SDValue V2 = Op.getOperand(1);
6369
6370   if (isZeroShuffle(SVOp))
6371     return getZeroVector(VT, Subtarget, DAG, dl);
6372
6373   // Handle splat operations
6374   if (SVOp->isSplat()) {
6375     unsigned NumElem = VT.getVectorNumElements();
6376     int Size = VT.getSizeInBits();
6377
6378     // Use vbroadcast whenever the splat comes from a foldable load
6379     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6380     if (Broadcast.getNode())
6381       return Broadcast;
6382
6383     // Handle splats by matching through known shuffle masks
6384     if ((Size == 128 && NumElem <= 4) ||
6385         (Size == 256 && NumElem < 8))
6386       return SDValue();
6387
6388     // All remaning splats are promoted to target supported vector shuffles.
6389     return PromoteSplat(SVOp, DAG);
6390   }
6391
6392   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6393   // do it!
6394   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6395       VT == MVT::v16i16 || VT == MVT::v32i8) {
6396     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6397     if (NewOp.getNode())
6398       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6399   } else if ((VT == MVT::v4i32 ||
6400              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6401     // FIXME: Figure out a cleaner way to do this.
6402     // Try to make use of movq to zero out the top part.
6403     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6404       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6405       if (NewOp.getNode()) {
6406         EVT NewVT = NewOp.getValueType();
6407         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6408                                NewVT, true, false))
6409           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6410                               DAG, Subtarget, dl);
6411       }
6412     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6413       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6414       if (NewOp.getNode()) {
6415         EVT NewVT = NewOp.getValueType();
6416         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6417           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6418                               DAG, Subtarget, dl);
6419       }
6420     }
6421   }
6422   return SDValue();
6423 }
6424
6425 SDValue
6426 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6427   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6428   SDValue V1 = Op.getOperand(0);
6429   SDValue V2 = Op.getOperand(1);
6430   EVT VT = Op.getValueType();
6431   DebugLoc dl = Op.getDebugLoc();
6432   unsigned NumElems = VT.getVectorNumElements();
6433   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6434   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6435   bool V1IsSplat = false;
6436   bool V2IsSplat = false;
6437   bool HasSSE2 = Subtarget->hasSSE2();
6438   bool HasAVX    = Subtarget->hasAVX();
6439   bool HasAVX2   = Subtarget->hasAVX2();
6440   MachineFunction &MF = DAG.getMachineFunction();
6441   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6442
6443   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6444
6445   if (V1IsUndef && V2IsUndef)
6446     return DAG.getUNDEF(VT);
6447
6448   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6449
6450   // Vector shuffle lowering takes 3 steps:
6451   //
6452   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6453   //    narrowing and commutation of operands should be handled.
6454   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6455   //    shuffle nodes.
6456   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6457   //    so the shuffle can be broken into other shuffles and the legalizer can
6458   //    try the lowering again.
6459   //
6460   // The general idea is that no vector_shuffle operation should be left to
6461   // be matched during isel, all of them must be converted to a target specific
6462   // node here.
6463
6464   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6465   // narrowing and commutation of operands should be handled. The actual code
6466   // doesn't include all of those, work in progress...
6467   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6468   if (NewOp.getNode())
6469     return NewOp;
6470
6471   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6472
6473   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6474   // unpckh_undef). Only use pshufd if speed is more important than size.
6475   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6476     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6477   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6478     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6479
6480   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6481       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6482     return getMOVDDup(Op, dl, V1, DAG);
6483
6484   if (isMOVHLPS_v_undef_Mask(M, VT))
6485     return getMOVHighToLow(Op, dl, DAG);
6486
6487   // Use to match splats
6488   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6489       (VT == MVT::v2f64 || VT == MVT::v2i64))
6490     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6491
6492   if (isPSHUFDMask(M, VT)) {
6493     // The actual implementation will match the mask in the if above and then
6494     // during isel it can match several different instructions, not only pshufd
6495     // as its name says, sad but true, emulate the behavior for now...
6496     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6497       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6498
6499     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6500
6501     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6502       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6503
6504     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6505       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6506
6507     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6508                                 TargetMask, DAG);
6509   }
6510
6511   // Check if this can be converted into a logical shift.
6512   bool isLeft = false;
6513   unsigned ShAmt = 0;
6514   SDValue ShVal;
6515   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6516   if (isShift && ShVal.hasOneUse()) {
6517     // If the shifted value has multiple uses, it may be cheaper to use
6518     // v_set0 + movlhps or movhlps, etc.
6519     EVT EltVT = VT.getVectorElementType();
6520     ShAmt *= EltVT.getSizeInBits();
6521     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6522   }
6523
6524   if (isMOVLMask(M, VT)) {
6525     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6526       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6527     if (!isMOVLPMask(M, VT)) {
6528       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6529         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6530
6531       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6532         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6533     }
6534   }
6535
6536   // FIXME: fold these into legal mask.
6537   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6538     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6539
6540   if (isMOVHLPSMask(M, VT))
6541     return getMOVHighToLow(Op, dl, DAG);
6542
6543   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6544     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6545
6546   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6547     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6548
6549   if (isMOVLPMask(M, VT))
6550     return getMOVLP(Op, dl, DAG, HasSSE2);
6551
6552   if (ShouldXformToMOVHLPS(M, VT) ||
6553       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6554     return CommuteVectorShuffle(SVOp, DAG);
6555
6556   if (isShift) {
6557     // No better options. Use a vshldq / vsrldq.
6558     EVT EltVT = VT.getVectorElementType();
6559     ShAmt *= EltVT.getSizeInBits();
6560     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6561   }
6562
6563   bool Commuted = false;
6564   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6565   // 1,1,1,1 -> v8i16 though.
6566   V1IsSplat = isSplatVector(V1.getNode());
6567   V2IsSplat = isSplatVector(V2.getNode());
6568
6569   // Canonicalize the splat or undef, if present, to be on the RHS.
6570   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6571     CommuteVectorShuffleMask(M, NumElems);
6572     std::swap(V1, V2);
6573     std::swap(V1IsSplat, V2IsSplat);
6574     Commuted = true;
6575   }
6576
6577   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6578     // Shuffling low element of v1 into undef, just return v1.
6579     if (V2IsUndef)
6580       return V1;
6581     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6582     // the instruction selector will not match, so get a canonical MOVL with
6583     // swapped operands to undo the commute.
6584     return getMOVL(DAG, dl, VT, V2, V1);
6585   }
6586
6587   if (isUNPCKLMask(M, VT, HasAVX2))
6588     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6589
6590   if (isUNPCKHMask(M, VT, HasAVX2))
6591     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6592
6593   if (V2IsSplat) {
6594     // Normalize mask so all entries that point to V2 points to its first
6595     // element then try to match unpck{h|l} again. If match, return a
6596     // new vector_shuffle with the corrected mask.p
6597     SmallVector<int, 8> NewMask(M.begin(), M.end());
6598     NormalizeMask(NewMask, NumElems);
6599     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6600       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6601     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6602       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6603   }
6604
6605   if (Commuted) {
6606     // Commute is back and try unpck* again.
6607     // FIXME: this seems wrong.
6608     CommuteVectorShuffleMask(M, NumElems);
6609     std::swap(V1, V2);
6610     std::swap(V1IsSplat, V2IsSplat);
6611     Commuted = false;
6612
6613     if (isUNPCKLMask(M, VT, HasAVX2))
6614       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6615
6616     if (isUNPCKHMask(M, VT, HasAVX2))
6617       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6618   }
6619
6620   // Normalize the node to match x86 shuffle ops if needed
6621   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6622     return CommuteVectorShuffle(SVOp, DAG);
6623
6624   // The checks below are all present in isShuffleMaskLegal, but they are
6625   // inlined here right now to enable us to directly emit target specific
6626   // nodes, and remove one by one until they don't return Op anymore.
6627
6628   if (isPALIGNRMask(M, VT, Subtarget))
6629     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6630                                 getShufflePALIGNRImmediate(SVOp),
6631                                 DAG);
6632
6633   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6634       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6635     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6636       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6637   }
6638
6639   if (isPSHUFHWMask(M, VT, HasAVX2))
6640     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6641                                 getShufflePSHUFHWImmediate(SVOp),
6642                                 DAG);
6643
6644   if (isPSHUFLWMask(M, VT, HasAVX2))
6645     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6646                                 getShufflePSHUFLWImmediate(SVOp),
6647                                 DAG);
6648
6649   if (isSHUFPMask(M, VT, HasAVX))
6650     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6651                                 getShuffleSHUFImmediate(SVOp), DAG);
6652
6653   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6654     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6655   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6656     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6657
6658   //===--------------------------------------------------------------------===//
6659   // Generate target specific nodes for 128 or 256-bit shuffles only
6660   // supported in the AVX instruction set.
6661   //
6662
6663   // Handle VMOVDDUPY permutations
6664   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6665     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6666
6667   // Handle VPERMILPS/D* permutations
6668   if (isVPERMILPMask(M, VT, HasAVX)) {
6669     if (HasAVX2 && VT == MVT::v8i32)
6670       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6671                                   getShuffleSHUFImmediate(SVOp), DAG);
6672     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6673                                 getShuffleSHUFImmediate(SVOp), DAG);
6674   }
6675
6676   // Handle VPERM2F128/VPERM2I128 permutations
6677   if (isVPERM2X128Mask(M, VT, HasAVX))
6678     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6679                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6680
6681   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6682   if (BlendOp.getNode())
6683     return BlendOp;
6684
6685   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6686     SmallVector<SDValue, 8> permclMask;
6687     for (unsigned i = 0; i != 8; ++i) {
6688       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6689     }
6690     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6691                                &permclMask[0], 8);
6692     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6693     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6694                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6695   }
6696
6697   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6698     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6699                                 getShuffleCLImmediate(SVOp), DAG);
6700
6701
6702   //===--------------------------------------------------------------------===//
6703   // Since no target specific shuffle was selected for this generic one,
6704   // lower it into other known shuffles. FIXME: this isn't true yet, but
6705   // this is the plan.
6706   //
6707
6708   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6709   if (VT == MVT::v8i16) {
6710     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6711     if (NewOp.getNode())
6712       return NewOp;
6713   }
6714
6715   if (VT == MVT::v16i8) {
6716     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6717     if (NewOp.getNode())
6718       return NewOp;
6719   }
6720
6721   // Handle all 128-bit wide vectors with 4 elements, and match them with
6722   // several different shuffle types.
6723   if (NumElems == 4 && VT.getSizeInBits() == 128)
6724     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6725
6726   // Handle general 256-bit shuffles
6727   if (VT.is256BitVector())
6728     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6729
6730   return SDValue();
6731 }
6732
6733 SDValue
6734 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6735                                                 SelectionDAG &DAG) const {
6736   EVT VT = Op.getValueType();
6737   DebugLoc dl = Op.getDebugLoc();
6738
6739   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6740     return SDValue();
6741
6742   if (VT.getSizeInBits() == 8) {
6743     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6744                                     Op.getOperand(0), Op.getOperand(1));
6745     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6746                                     DAG.getValueType(VT));
6747     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6748   }
6749
6750   if (VT.getSizeInBits() == 16) {
6751     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6752     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6753     if (Idx == 0)
6754       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6755                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6756                                      DAG.getNode(ISD::BITCAST, dl,
6757                                                  MVT::v4i32,
6758                                                  Op.getOperand(0)),
6759                                      Op.getOperand(1)));
6760     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6761                                     Op.getOperand(0), Op.getOperand(1));
6762     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6763                                     DAG.getValueType(VT));
6764     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6765   }
6766
6767   if (VT == MVT::f32) {
6768     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6769     // the result back to FR32 register. It's only worth matching if the
6770     // result has a single use which is a store or a bitcast to i32.  And in
6771     // the case of a store, it's not worth it if the index is a constant 0,
6772     // because a MOVSSmr can be used instead, which is smaller and faster.
6773     if (!Op.hasOneUse())
6774       return SDValue();
6775     SDNode *User = *Op.getNode()->use_begin();
6776     if ((User->getOpcode() != ISD::STORE ||
6777          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6778           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6779         (User->getOpcode() != ISD::BITCAST ||
6780          User->getValueType(0) != MVT::i32))
6781       return SDValue();
6782     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6783                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6784                                               Op.getOperand(0)),
6785                                               Op.getOperand(1));
6786     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6787   }
6788
6789   if (VT == MVT::i32 || VT == MVT::i64) {
6790     // ExtractPS/pextrq works with constant index.
6791     if (isa<ConstantSDNode>(Op.getOperand(1)))
6792       return Op;
6793   }
6794   return SDValue();
6795 }
6796
6797
6798 SDValue
6799 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6800                                            SelectionDAG &DAG) const {
6801   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6802     return SDValue();
6803
6804   SDValue Vec = Op.getOperand(0);
6805   EVT VecVT = Vec.getValueType();
6806
6807   // If this is a 256-bit vector result, first extract the 128-bit vector and
6808   // then extract the element from the 128-bit vector.
6809   if (VecVT.getSizeInBits() == 256) {
6810     DebugLoc dl = Op.getNode()->getDebugLoc();
6811     unsigned NumElems = VecVT.getVectorNumElements();
6812     SDValue Idx = Op.getOperand(1);
6813     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6814
6815     // Get the 128-bit vector.
6816     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6817
6818     if (IdxVal >= NumElems/2)
6819       IdxVal -= NumElems/2;
6820     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6821                        DAG.getConstant(IdxVal, MVT::i32));
6822   }
6823
6824   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6825
6826   if (Subtarget->hasSSE41()) {
6827     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6828     if (Res.getNode())
6829       return Res;
6830   }
6831
6832   EVT VT = Op.getValueType();
6833   DebugLoc dl = Op.getDebugLoc();
6834   // TODO: handle v16i8.
6835   if (VT.getSizeInBits() == 16) {
6836     SDValue Vec = Op.getOperand(0);
6837     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6838     if (Idx == 0)
6839       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6840                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6841                                      DAG.getNode(ISD::BITCAST, dl,
6842                                                  MVT::v4i32, Vec),
6843                                      Op.getOperand(1)));
6844     // Transform it so it match pextrw which produces a 32-bit result.
6845     EVT EltVT = MVT::i32;
6846     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6847                                     Op.getOperand(0), Op.getOperand(1));
6848     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6849                                     DAG.getValueType(VT));
6850     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6851   }
6852
6853   if (VT.getSizeInBits() == 32) {
6854     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6855     if (Idx == 0)
6856       return Op;
6857
6858     // SHUFPS the element to the lowest double word, then movss.
6859     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6860     EVT VVT = Op.getOperand(0).getValueType();
6861     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6862                                        DAG.getUNDEF(VVT), Mask);
6863     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6864                        DAG.getIntPtrConstant(0));
6865   }
6866
6867   if (VT.getSizeInBits() == 64) {
6868     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6869     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6870     //        to match extract_elt for f64.
6871     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6872     if (Idx == 0)
6873       return Op;
6874
6875     // UNPCKHPD the element to the lowest double word, then movsd.
6876     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6877     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6878     int Mask[2] = { 1, -1 };
6879     EVT VVT = Op.getOperand(0).getValueType();
6880     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6881                                        DAG.getUNDEF(VVT), Mask);
6882     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6883                        DAG.getIntPtrConstant(0));
6884   }
6885
6886   return SDValue();
6887 }
6888
6889 SDValue
6890 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6891                                                SelectionDAG &DAG) const {
6892   EVT VT = Op.getValueType();
6893   EVT EltVT = VT.getVectorElementType();
6894   DebugLoc dl = Op.getDebugLoc();
6895
6896   SDValue N0 = Op.getOperand(0);
6897   SDValue N1 = Op.getOperand(1);
6898   SDValue N2 = Op.getOperand(2);
6899
6900   if (VT.getSizeInBits() == 256)
6901     return SDValue();
6902
6903   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6904       isa<ConstantSDNode>(N2)) {
6905     unsigned Opc;
6906     if (VT == MVT::v8i16)
6907       Opc = X86ISD::PINSRW;
6908     else if (VT == MVT::v16i8)
6909       Opc = X86ISD::PINSRB;
6910     else
6911       Opc = X86ISD::PINSRB;
6912
6913     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6914     // argument.
6915     if (N1.getValueType() != MVT::i32)
6916       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6917     if (N2.getValueType() != MVT::i32)
6918       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6919     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6920   }
6921
6922   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6923     // Bits [7:6] of the constant are the source select.  This will always be
6924     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6925     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6926     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6927     // Bits [5:4] of the constant are the destination select.  This is the
6928     //  value of the incoming immediate.
6929     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6930     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6931     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6932     // Create this as a scalar to vector..
6933     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6934     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6935   }
6936
6937   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
6938     // PINSR* works with constant index.
6939     return Op;
6940   }
6941   return SDValue();
6942 }
6943
6944 SDValue
6945 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6946   EVT VT = Op.getValueType();
6947   EVT EltVT = VT.getVectorElementType();
6948
6949   DebugLoc dl = Op.getDebugLoc();
6950   SDValue N0 = Op.getOperand(0);
6951   SDValue N1 = Op.getOperand(1);
6952   SDValue N2 = Op.getOperand(2);
6953
6954   // If this is a 256-bit vector result, first extract the 128-bit vector,
6955   // insert the element into the extracted half and then place it back.
6956   if (VT.getSizeInBits() == 256) {
6957     if (!isa<ConstantSDNode>(N2))
6958       return SDValue();
6959
6960     // Get the desired 128-bit vector half.
6961     unsigned NumElems = VT.getVectorNumElements();
6962     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6963     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
6964
6965     // Insert the element into the desired half.
6966     bool Upper = IdxVal >= NumElems/2;
6967     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
6968                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
6969
6970     // Insert the changed part back to the 256-bit vector
6971     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
6972   }
6973
6974   if (Subtarget->hasSSE41())
6975     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6976
6977   if (EltVT == MVT::i8)
6978     return SDValue();
6979
6980   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6981     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6982     // as its second argument.
6983     if (N1.getValueType() != MVT::i32)
6984       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6985     if (N2.getValueType() != MVT::i32)
6986       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6987     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6988   }
6989   return SDValue();
6990 }
6991
6992 SDValue
6993 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6994   LLVMContext *Context = DAG.getContext();
6995   DebugLoc dl = Op.getDebugLoc();
6996   EVT OpVT = Op.getValueType();
6997
6998   // If this is a 256-bit vector result, first insert into a 128-bit
6999   // vector and then insert into the 256-bit vector.
7000   if (OpVT.getSizeInBits() > 128) {
7001     // Insert into a 128-bit vector.
7002     EVT VT128 = EVT::getVectorVT(*Context,
7003                                  OpVT.getVectorElementType(),
7004                                  OpVT.getVectorNumElements() / 2);
7005
7006     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7007
7008     // Insert the 128-bit vector.
7009     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7010   }
7011
7012   if (OpVT == MVT::v1i64 &&
7013       Op.getOperand(0).getValueType() == MVT::i64)
7014     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7015
7016   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7017   assert(OpVT.getSizeInBits() == 128 && "Expected an SSE type!");
7018   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7019                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7020 }
7021
7022 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7023 // a simple subregister reference or explicit instructions to grab
7024 // upper bits of a vector.
7025 SDValue
7026 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7027   if (Subtarget->hasAVX()) {
7028     DebugLoc dl = Op.getNode()->getDebugLoc();
7029     SDValue Vec = Op.getNode()->getOperand(0);
7030     SDValue Idx = Op.getNode()->getOperand(1);
7031
7032     if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
7033         Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
7034         isa<ConstantSDNode>(Idx)) {
7035       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7036       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7037     }
7038   }
7039   return SDValue();
7040 }
7041
7042 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7043 // simple superregister reference or explicit instructions to insert
7044 // the upper bits of a vector.
7045 SDValue
7046 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7047   if (Subtarget->hasAVX()) {
7048     DebugLoc dl = Op.getNode()->getDebugLoc();
7049     SDValue Vec = Op.getNode()->getOperand(0);
7050     SDValue SubVec = Op.getNode()->getOperand(1);
7051     SDValue Idx = Op.getNode()->getOperand(2);
7052
7053     if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
7054         SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
7055         isa<ConstantSDNode>(Idx)) {
7056       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7057       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7058     }
7059   }
7060   return SDValue();
7061 }
7062
7063 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7064 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7065 // one of the above mentioned nodes. It has to be wrapped because otherwise
7066 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7067 // be used to form addressing mode. These wrapped nodes will be selected
7068 // into MOV32ri.
7069 SDValue
7070 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7071   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7072
7073   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7074   // global base reg.
7075   unsigned char OpFlag = 0;
7076   unsigned WrapperKind = X86ISD::Wrapper;
7077   CodeModel::Model M = getTargetMachine().getCodeModel();
7078
7079   if (Subtarget->isPICStyleRIPRel() &&
7080       (M == CodeModel::Small || M == CodeModel::Kernel))
7081     WrapperKind = X86ISD::WrapperRIP;
7082   else if (Subtarget->isPICStyleGOT())
7083     OpFlag = X86II::MO_GOTOFF;
7084   else if (Subtarget->isPICStyleStubPIC())
7085     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7086
7087   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7088                                              CP->getAlignment(),
7089                                              CP->getOffset(), OpFlag);
7090   DebugLoc DL = CP->getDebugLoc();
7091   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7092   // With PIC, the address is actually $g + Offset.
7093   if (OpFlag) {
7094     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7095                          DAG.getNode(X86ISD::GlobalBaseReg,
7096                                      DebugLoc(), getPointerTy()),
7097                          Result);
7098   }
7099
7100   return Result;
7101 }
7102
7103 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7104   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7105
7106   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7107   // global base reg.
7108   unsigned char OpFlag = 0;
7109   unsigned WrapperKind = X86ISD::Wrapper;
7110   CodeModel::Model M = getTargetMachine().getCodeModel();
7111
7112   if (Subtarget->isPICStyleRIPRel() &&
7113       (M == CodeModel::Small || M == CodeModel::Kernel))
7114     WrapperKind = X86ISD::WrapperRIP;
7115   else if (Subtarget->isPICStyleGOT())
7116     OpFlag = X86II::MO_GOTOFF;
7117   else if (Subtarget->isPICStyleStubPIC())
7118     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7119
7120   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7121                                           OpFlag);
7122   DebugLoc DL = JT->getDebugLoc();
7123   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7124
7125   // With PIC, the address is actually $g + Offset.
7126   if (OpFlag)
7127     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7128                          DAG.getNode(X86ISD::GlobalBaseReg,
7129                                      DebugLoc(), getPointerTy()),
7130                          Result);
7131
7132   return Result;
7133 }
7134
7135 SDValue
7136 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7137   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7138
7139   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7140   // global base reg.
7141   unsigned char OpFlag = 0;
7142   unsigned WrapperKind = X86ISD::Wrapper;
7143   CodeModel::Model M = getTargetMachine().getCodeModel();
7144
7145   if (Subtarget->isPICStyleRIPRel() &&
7146       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7147     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7148       OpFlag = X86II::MO_GOTPCREL;
7149     WrapperKind = X86ISD::WrapperRIP;
7150   } else if (Subtarget->isPICStyleGOT()) {
7151     OpFlag = X86II::MO_GOT;
7152   } else if (Subtarget->isPICStyleStubPIC()) {
7153     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7154   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7155     OpFlag = X86II::MO_DARWIN_NONLAZY;
7156   }
7157
7158   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7159
7160   DebugLoc DL = Op.getDebugLoc();
7161   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7162
7163
7164   // With PIC, the address is actually $g + Offset.
7165   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7166       !Subtarget->is64Bit()) {
7167     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7168                          DAG.getNode(X86ISD::GlobalBaseReg,
7169                                      DebugLoc(), getPointerTy()),
7170                          Result);
7171   }
7172
7173   // For symbols that require a load from a stub to get the address, emit the
7174   // load.
7175   if (isGlobalStubReference(OpFlag))
7176     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7177                          MachinePointerInfo::getGOT(), false, false, false, 0);
7178
7179   return Result;
7180 }
7181
7182 SDValue
7183 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7184   // Create the TargetBlockAddressAddress node.
7185   unsigned char OpFlags =
7186     Subtarget->ClassifyBlockAddressReference();
7187   CodeModel::Model M = getTargetMachine().getCodeModel();
7188   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7189   DebugLoc dl = Op.getDebugLoc();
7190   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7191                                        /*isTarget=*/true, OpFlags);
7192
7193   if (Subtarget->isPICStyleRIPRel() &&
7194       (M == CodeModel::Small || M == CodeModel::Kernel))
7195     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7196   else
7197     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7198
7199   // With PIC, the address is actually $g + Offset.
7200   if (isGlobalRelativeToPICBase(OpFlags)) {
7201     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7202                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7203                          Result);
7204   }
7205
7206   return Result;
7207 }
7208
7209 SDValue
7210 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7211                                       int64_t Offset,
7212                                       SelectionDAG &DAG) const {
7213   // Create the TargetGlobalAddress node, folding in the constant
7214   // offset if it is legal.
7215   unsigned char OpFlags =
7216     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7217   CodeModel::Model M = getTargetMachine().getCodeModel();
7218   SDValue Result;
7219   if (OpFlags == X86II::MO_NO_FLAG &&
7220       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7221     // A direct static reference to a global.
7222     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7223     Offset = 0;
7224   } else {
7225     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7226   }
7227
7228   if (Subtarget->isPICStyleRIPRel() &&
7229       (M == CodeModel::Small || M == CodeModel::Kernel))
7230     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7231   else
7232     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7233
7234   // With PIC, the address is actually $g + Offset.
7235   if (isGlobalRelativeToPICBase(OpFlags)) {
7236     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7237                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7238                          Result);
7239   }
7240
7241   // For globals that require a load from a stub to get the address, emit the
7242   // load.
7243   if (isGlobalStubReference(OpFlags))
7244     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7245                          MachinePointerInfo::getGOT(), false, false, false, 0);
7246
7247   // If there was a non-zero offset that we didn't fold, create an explicit
7248   // addition for it.
7249   if (Offset != 0)
7250     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7251                          DAG.getConstant(Offset, getPointerTy()));
7252
7253   return Result;
7254 }
7255
7256 SDValue
7257 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7258   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7259   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7260   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7261 }
7262
7263 static SDValue
7264 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7265            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7266            unsigned char OperandFlags, bool LocalDynamic = false) {
7267   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7268   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7269   DebugLoc dl = GA->getDebugLoc();
7270   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7271                                            GA->getValueType(0),
7272                                            GA->getOffset(),
7273                                            OperandFlags);
7274
7275   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7276                                            : X86ISD::TLSADDR;
7277
7278   if (InFlag) {
7279     SDValue Ops[] = { Chain,  TGA, *InFlag };
7280     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7281   } else {
7282     SDValue Ops[]  = { Chain, TGA };
7283     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7284   }
7285
7286   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7287   MFI->setAdjustsStack(true);
7288
7289   SDValue Flag = Chain.getValue(1);
7290   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7291 }
7292
7293 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7294 static SDValue
7295 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7296                                 const EVT PtrVT) {
7297   SDValue InFlag;
7298   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7299   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7300                                      DAG.getNode(X86ISD::GlobalBaseReg,
7301                                                  DebugLoc(), PtrVT), InFlag);
7302   InFlag = Chain.getValue(1);
7303
7304   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7305 }
7306
7307 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7308 static SDValue
7309 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7310                                 const EVT PtrVT) {
7311   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7312                     X86::RAX, X86II::MO_TLSGD);
7313 }
7314
7315 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7316                                            SelectionDAG &DAG,
7317                                            const EVT PtrVT,
7318                                            bool is64Bit) {
7319   DebugLoc dl = GA->getDebugLoc();
7320
7321   // Get the start address of the TLS block for this module.
7322   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7323       .getInfo<X86MachineFunctionInfo>();
7324   MFI->incNumLocalDynamicTLSAccesses();
7325
7326   SDValue Base;
7327   if (is64Bit) {
7328     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7329                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7330   } else {
7331     SDValue InFlag;
7332     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7333         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7334     InFlag = Chain.getValue(1);
7335     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7336                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7337   }
7338
7339   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7340   // of Base.
7341
7342   // Build x@dtpoff.
7343   unsigned char OperandFlags = X86II::MO_DTPOFF;
7344   unsigned WrapperKind = X86ISD::Wrapper;
7345   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7346                                            GA->getValueType(0),
7347                                            GA->getOffset(), OperandFlags);
7348   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7349
7350   // Add x@dtpoff with the base.
7351   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7352 }
7353
7354 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7355 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7356                                    const EVT PtrVT, TLSModel::Model model,
7357                                    bool is64Bit, bool isPIC) {
7358   DebugLoc dl = GA->getDebugLoc();
7359
7360   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7361   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7362                                                          is64Bit ? 257 : 256));
7363
7364   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7365                                       DAG.getIntPtrConstant(0),
7366                                       MachinePointerInfo(Ptr),
7367                                       false, false, false, 0);
7368
7369   unsigned char OperandFlags = 0;
7370   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7371   // initialexec.
7372   unsigned WrapperKind = X86ISD::Wrapper;
7373   if (model == TLSModel::LocalExec) {
7374     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7375   } else if (model == TLSModel::InitialExec) {
7376     if (is64Bit) {
7377       OperandFlags = X86II::MO_GOTTPOFF;
7378       WrapperKind = X86ISD::WrapperRIP;
7379     } else {
7380       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7381     }
7382   } else {
7383     llvm_unreachable("Unexpected model");
7384   }
7385
7386   // emit "addl x@ntpoff,%eax" (local exec)
7387   // or "addl x@indntpoff,%eax" (initial exec)
7388   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7389   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7390                                            GA->getValueType(0),
7391                                            GA->getOffset(), OperandFlags);
7392   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7393
7394   if (model == TLSModel::InitialExec) {
7395     if (isPIC && !is64Bit) {
7396       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7397                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7398                            Offset);
7399     } else {
7400       Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7401                            MachinePointerInfo::getGOT(), false, false, false,
7402                            0);
7403     }
7404   }
7405
7406   // The address of the thread local variable is the add of the thread
7407   // pointer with the offset of the variable.
7408   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7409 }
7410
7411 SDValue
7412 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7413
7414   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7415   const GlobalValue *GV = GA->getGlobal();
7416
7417   if (Subtarget->isTargetELF()) {
7418     // If GV is an alias then use the aliasee for determining
7419     // thread-localness.
7420     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7421       GV = GA->resolveAliasedGlobal(false);
7422
7423     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7424
7425     switch (model) {
7426       case TLSModel::GeneralDynamic:
7427         if (Subtarget->is64Bit())
7428           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7429         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7430       case TLSModel::LocalDynamic:
7431         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7432                                            Subtarget->is64Bit());
7433       case TLSModel::InitialExec:
7434       case TLSModel::LocalExec:
7435         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7436                                    Subtarget->is64Bit(),
7437                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7438     }
7439     llvm_unreachable("Unknown TLS model.");
7440   }
7441
7442   if (Subtarget->isTargetDarwin()) {
7443     // Darwin only has one model of TLS.  Lower to that.
7444     unsigned char OpFlag = 0;
7445     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7446                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7447
7448     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7449     // global base reg.
7450     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7451                   !Subtarget->is64Bit();
7452     if (PIC32)
7453       OpFlag = X86II::MO_TLVP_PIC_BASE;
7454     else
7455       OpFlag = X86II::MO_TLVP;
7456     DebugLoc DL = Op.getDebugLoc();
7457     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7458                                                 GA->getValueType(0),
7459                                                 GA->getOffset(), OpFlag);
7460     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7461
7462     // With PIC32, the address is actually $g + Offset.
7463     if (PIC32)
7464       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7465                            DAG.getNode(X86ISD::GlobalBaseReg,
7466                                        DebugLoc(), getPointerTy()),
7467                            Offset);
7468
7469     // Lowering the machine isd will make sure everything is in the right
7470     // location.
7471     SDValue Chain = DAG.getEntryNode();
7472     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7473     SDValue Args[] = { Chain, Offset };
7474     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7475
7476     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7477     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7478     MFI->setAdjustsStack(true);
7479
7480     // And our return value (tls address) is in the standard call return value
7481     // location.
7482     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7483     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7484                               Chain.getValue(1));
7485   }
7486
7487   if (Subtarget->isTargetWindows()) {
7488     // Just use the implicit TLS architecture
7489     // Need to generate someting similar to:
7490     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7491     //                                  ; from TEB
7492     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7493     //   mov     rcx, qword [rdx+rcx*8]
7494     //   mov     eax, .tls$:tlsvar
7495     //   [rax+rcx] contains the address
7496     // Windows 64bit: gs:0x58
7497     // Windows 32bit: fs:__tls_array
7498
7499     // If GV is an alias then use the aliasee for determining
7500     // thread-localness.
7501     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7502       GV = GA->resolveAliasedGlobal(false);
7503     DebugLoc dl = GA->getDebugLoc();
7504     SDValue Chain = DAG.getEntryNode();
7505
7506     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7507     // %gs:0x58 (64-bit).
7508     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7509                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7510                                                              256)
7511                                         : Type::getInt32PtrTy(*DAG.getContext(),
7512                                                               257));
7513
7514     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7515                                         Subtarget->is64Bit()
7516                                         ? DAG.getIntPtrConstant(0x58)
7517                                         : DAG.getExternalSymbol("_tls_array",
7518                                                                 getPointerTy()),
7519                                         MachinePointerInfo(Ptr),
7520                                         false, false, false, 0);
7521
7522     // Load the _tls_index variable
7523     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7524     if (Subtarget->is64Bit())
7525       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7526                            IDX, MachinePointerInfo(), MVT::i32,
7527                            false, false, 0);
7528     else
7529       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7530                         false, false, false, 0);
7531
7532     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7533                                     getPointerTy());
7534     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7535
7536     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7537     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7538                       false, false, false, 0);
7539
7540     // Get the offset of start of .tls section
7541     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7542                                              GA->getValueType(0),
7543                                              GA->getOffset(), X86II::MO_SECREL);
7544     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7545
7546     // The address of the thread local variable is the add of the thread
7547     // pointer with the offset of the variable.
7548     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7549   }
7550
7551   llvm_unreachable("TLS not implemented for this target.");
7552 }
7553
7554
7555 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7556 /// and take a 2 x i32 value to shift plus a shift amount.
7557 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7558   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7559   EVT VT = Op.getValueType();
7560   unsigned VTBits = VT.getSizeInBits();
7561   DebugLoc dl = Op.getDebugLoc();
7562   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7563   SDValue ShOpLo = Op.getOperand(0);
7564   SDValue ShOpHi = Op.getOperand(1);
7565   SDValue ShAmt  = Op.getOperand(2);
7566   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7567                                      DAG.getConstant(VTBits - 1, MVT::i8))
7568                        : DAG.getConstant(0, VT);
7569
7570   SDValue Tmp2, Tmp3;
7571   if (Op.getOpcode() == ISD::SHL_PARTS) {
7572     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7573     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7574   } else {
7575     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7576     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7577   }
7578
7579   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7580                                 DAG.getConstant(VTBits, MVT::i8));
7581   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7582                              AndNode, DAG.getConstant(0, MVT::i8));
7583
7584   SDValue Hi, Lo;
7585   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7586   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7587   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7588
7589   if (Op.getOpcode() == ISD::SHL_PARTS) {
7590     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7591     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7592   } else {
7593     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7594     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7595   }
7596
7597   SDValue Ops[2] = { Lo, Hi };
7598   return DAG.getMergeValues(Ops, 2, dl);
7599 }
7600
7601 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7602                                            SelectionDAG &DAG) const {
7603   EVT SrcVT = Op.getOperand(0).getValueType();
7604
7605   if (SrcVT.isVector())
7606     return SDValue();
7607
7608   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7609          "Unknown SINT_TO_FP to lower!");
7610
7611   // These are really Legal; return the operand so the caller accepts it as
7612   // Legal.
7613   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7614     return Op;
7615   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7616       Subtarget->is64Bit()) {
7617     return Op;
7618   }
7619
7620   DebugLoc dl = Op.getDebugLoc();
7621   unsigned Size = SrcVT.getSizeInBits()/8;
7622   MachineFunction &MF = DAG.getMachineFunction();
7623   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7624   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7625   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7626                                StackSlot,
7627                                MachinePointerInfo::getFixedStack(SSFI),
7628                                false, false, 0);
7629   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7630 }
7631
7632 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7633                                      SDValue StackSlot,
7634                                      SelectionDAG &DAG) const {
7635   // Build the FILD
7636   DebugLoc DL = Op.getDebugLoc();
7637   SDVTList Tys;
7638   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7639   if (useSSE)
7640     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7641   else
7642     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7643
7644   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7645
7646   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7647   MachineMemOperand *MMO;
7648   if (FI) {
7649     int SSFI = FI->getIndex();
7650     MMO =
7651       DAG.getMachineFunction()
7652       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7653                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7654   } else {
7655     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7656     StackSlot = StackSlot.getOperand(1);
7657   }
7658   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7659   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7660                                            X86ISD::FILD, DL,
7661                                            Tys, Ops, array_lengthof(Ops),
7662                                            SrcVT, MMO);
7663
7664   if (useSSE) {
7665     Chain = Result.getValue(1);
7666     SDValue InFlag = Result.getValue(2);
7667
7668     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7669     // shouldn't be necessary except that RFP cannot be live across
7670     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7671     MachineFunction &MF = DAG.getMachineFunction();
7672     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7673     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7674     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7675     Tys = DAG.getVTList(MVT::Other);
7676     SDValue Ops[] = {
7677       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7678     };
7679     MachineMemOperand *MMO =
7680       DAG.getMachineFunction()
7681       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7682                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7683
7684     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7685                                     Ops, array_lengthof(Ops),
7686                                     Op.getValueType(), MMO);
7687     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7688                          MachinePointerInfo::getFixedStack(SSFI),
7689                          false, false, false, 0);
7690   }
7691
7692   return Result;
7693 }
7694
7695 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7696 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7697                                                SelectionDAG &DAG) const {
7698   // This algorithm is not obvious. Here it is what we're trying to output:
7699   /*
7700      movq       %rax,  %xmm0
7701      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7702      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7703      #ifdef __SSE3__
7704        haddpd   %xmm0, %xmm0          
7705      #else
7706        pshufd   $0x4e, %xmm0, %xmm1 
7707        addpd    %xmm1, %xmm0
7708      #endif
7709   */
7710
7711   DebugLoc dl = Op.getDebugLoc();
7712   LLVMContext *Context = DAG.getContext();
7713
7714   // Build some magic constants.
7715   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7716   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7717   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7718
7719   SmallVector<Constant*,2> CV1;
7720   CV1.push_back(
7721         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7722   CV1.push_back(
7723         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7724   Constant *C1 = ConstantVector::get(CV1);
7725   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7726
7727   // Load the 64-bit value into an XMM register.
7728   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7729                             Op.getOperand(0));
7730   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7731                               MachinePointerInfo::getConstantPool(),
7732                               false, false, false, 16);
7733   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7734                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7735                               CLod0);
7736
7737   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7738                               MachinePointerInfo::getConstantPool(),
7739                               false, false, false, 16);
7740   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7741   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7742   SDValue Result;
7743
7744   if (Subtarget->hasSSE3()) {
7745     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7746     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7747   } else {
7748     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7749     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7750                                            S2F, 0x4E, DAG);
7751     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7752                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7753                          Sub);
7754   }
7755
7756   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7757                      DAG.getIntPtrConstant(0));
7758 }
7759
7760 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7761 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7762                                                SelectionDAG &DAG) const {
7763   DebugLoc dl = Op.getDebugLoc();
7764   // FP constant to bias correct the final result.
7765   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7766                                    MVT::f64);
7767
7768   // Load the 32-bit value into an XMM register.
7769   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7770                              Op.getOperand(0));
7771
7772   // Zero out the upper parts of the register.
7773   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7774
7775   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7776                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7777                      DAG.getIntPtrConstant(0));
7778
7779   // Or the load with the bias.
7780   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7781                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7782                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7783                                                    MVT::v2f64, Load)),
7784                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7785                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7786                                                    MVT::v2f64, Bias)));
7787   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7788                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7789                    DAG.getIntPtrConstant(0));
7790
7791   // Subtract the bias.
7792   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7793
7794   // Handle final rounding.
7795   EVT DestVT = Op.getValueType();
7796
7797   if (DestVT.bitsLT(MVT::f64))
7798     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7799                        DAG.getIntPtrConstant(0));
7800   if (DestVT.bitsGT(MVT::f64))
7801     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7802
7803   // Handle final rounding.
7804   return Sub;
7805 }
7806
7807 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7808                                            SelectionDAG &DAG) const {
7809   SDValue N0 = Op.getOperand(0);
7810   DebugLoc dl = Op.getDebugLoc();
7811
7812   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7813   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7814   // the optimization here.
7815   if (DAG.SignBitIsZero(N0))
7816     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7817
7818   EVT SrcVT = N0.getValueType();
7819   EVT DstVT = Op.getValueType();
7820   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7821     return LowerUINT_TO_FP_i64(Op, DAG);
7822   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7823     return LowerUINT_TO_FP_i32(Op, DAG);
7824   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7825     return SDValue();
7826
7827   // Make a 64-bit buffer, and use it to build an FILD.
7828   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7829   if (SrcVT == MVT::i32) {
7830     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7831     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7832                                      getPointerTy(), StackSlot, WordOff);
7833     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7834                                   StackSlot, MachinePointerInfo(),
7835                                   false, false, 0);
7836     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7837                                   OffsetSlot, MachinePointerInfo(),
7838                                   false, false, 0);
7839     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7840     return Fild;
7841   }
7842
7843   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7844   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7845                                StackSlot, MachinePointerInfo(),
7846                                false, false, 0);
7847   // For i64 source, we need to add the appropriate power of 2 if the input
7848   // was negative.  This is the same as the optimization in
7849   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7850   // we must be careful to do the computation in x87 extended precision, not
7851   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7852   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7853   MachineMemOperand *MMO =
7854     DAG.getMachineFunction()
7855     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7856                           MachineMemOperand::MOLoad, 8, 8);
7857
7858   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7859   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7860   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7861                                          MVT::i64, MMO);
7862
7863   APInt FF(32, 0x5F800000ULL);
7864
7865   // Check whether the sign bit is set.
7866   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7867                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7868                                  ISD::SETLT);
7869
7870   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7871   SDValue FudgePtr = DAG.getConstantPool(
7872                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7873                                          getPointerTy());
7874
7875   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7876   SDValue Zero = DAG.getIntPtrConstant(0);
7877   SDValue Four = DAG.getIntPtrConstant(4);
7878   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7879                                Zero, Four);
7880   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7881
7882   // Load the value out, extending it from f32 to f80.
7883   // FIXME: Avoid the extend by constructing the right constant pool?
7884   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7885                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7886                                  MVT::f32, false, false, 4);
7887   // Extend everything to 80 bits to force it to be done on x87.
7888   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7889   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7890 }
7891
7892 std::pair<SDValue,SDValue> X86TargetLowering::
7893 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7894   DebugLoc DL = Op.getDebugLoc();
7895
7896   EVT DstTy = Op.getValueType();
7897
7898   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7899     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7900     DstTy = MVT::i64;
7901   }
7902
7903   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7904          DstTy.getSimpleVT() >= MVT::i16 &&
7905          "Unknown FP_TO_INT to lower!");
7906
7907   // These are really Legal.
7908   if (DstTy == MVT::i32 &&
7909       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7910     return std::make_pair(SDValue(), SDValue());
7911   if (Subtarget->is64Bit() &&
7912       DstTy == MVT::i64 &&
7913       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7914     return std::make_pair(SDValue(), SDValue());
7915
7916   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7917   // stack slot, or into the FTOL runtime function.
7918   MachineFunction &MF = DAG.getMachineFunction();
7919   unsigned MemSize = DstTy.getSizeInBits()/8;
7920   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7921   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7922
7923   unsigned Opc;
7924   if (!IsSigned && isIntegerTypeFTOL(DstTy))
7925     Opc = X86ISD::WIN_FTOL;
7926   else
7927     switch (DstTy.getSimpleVT().SimpleTy) {
7928     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7929     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7930     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7931     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7932     }
7933
7934   SDValue Chain = DAG.getEntryNode();
7935   SDValue Value = Op.getOperand(0);
7936   EVT TheVT = Op.getOperand(0).getValueType();
7937   // FIXME This causes a redundant load/store if the SSE-class value is already
7938   // in memory, such as if it is on the callstack.
7939   if (isScalarFPTypeInSSEReg(TheVT)) {
7940     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7941     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7942                          MachinePointerInfo::getFixedStack(SSFI),
7943                          false, false, 0);
7944     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7945     SDValue Ops[] = {
7946       Chain, StackSlot, DAG.getValueType(TheVT)
7947     };
7948
7949     MachineMemOperand *MMO =
7950       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7951                               MachineMemOperand::MOLoad, MemSize, MemSize);
7952     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7953                                     DstTy, MMO);
7954     Chain = Value.getValue(1);
7955     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7956     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7957   }
7958
7959   MachineMemOperand *MMO =
7960     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7961                             MachineMemOperand::MOStore, MemSize, MemSize);
7962
7963   if (Opc != X86ISD::WIN_FTOL) {
7964     // Build the FP_TO_INT*_IN_MEM
7965     SDValue Ops[] = { Chain, Value, StackSlot };
7966     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7967                                            Ops, 3, DstTy, MMO);
7968     return std::make_pair(FIST, StackSlot);
7969   } else {
7970     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
7971       DAG.getVTList(MVT::Other, MVT::Glue),
7972       Chain, Value);
7973     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
7974       MVT::i32, ftol.getValue(1));
7975     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
7976       MVT::i32, eax.getValue(2));
7977     SDValue Ops[] = { eax, edx };
7978     SDValue pair = IsReplace
7979       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
7980       : DAG.getMergeValues(Ops, 2, DL);
7981     return std::make_pair(pair, SDValue());
7982   }
7983 }
7984
7985 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7986                                            SelectionDAG &DAG) const {
7987   if (Op.getValueType().isVector())
7988     return SDValue();
7989
7990   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
7991     /*IsSigned=*/ true, /*IsReplace=*/ false);
7992   SDValue FIST = Vals.first, StackSlot = Vals.second;
7993   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7994   if (FIST.getNode() == 0) return Op;
7995
7996   if (StackSlot.getNode())
7997     // Load the result.
7998     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7999                        FIST, StackSlot, MachinePointerInfo(),
8000                        false, false, false, 0);
8001
8002   // The node is the result.
8003   return FIST;
8004 }
8005
8006 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8007                                            SelectionDAG &DAG) const {
8008   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8009     /*IsSigned=*/ false, /*IsReplace=*/ false);
8010   SDValue FIST = Vals.first, StackSlot = Vals.second;
8011   assert(FIST.getNode() && "Unexpected failure");
8012
8013   if (StackSlot.getNode())
8014     // Load the result.
8015     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8016                        FIST, StackSlot, MachinePointerInfo(),
8017                        false, false, false, 0);
8018
8019   // The node is the result.
8020   return FIST;
8021 }
8022
8023 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8024                                      SelectionDAG &DAG) const {
8025   LLVMContext *Context = DAG.getContext();
8026   DebugLoc dl = Op.getDebugLoc();
8027   EVT VT = Op.getValueType();
8028   EVT EltVT = VT;
8029   if (VT.isVector())
8030     EltVT = VT.getVectorElementType();
8031   Constant *C;
8032   if (EltVT == MVT::f64) {
8033     C = ConstantVector::getSplat(2, 
8034                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8035   } else {
8036     C = ConstantVector::getSplat(4,
8037                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8038   }
8039   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8040   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8041                              MachinePointerInfo::getConstantPool(),
8042                              false, false, false, 16);
8043   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8044 }
8045
8046 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8047   LLVMContext *Context = DAG.getContext();
8048   DebugLoc dl = Op.getDebugLoc();
8049   EVT VT = Op.getValueType();
8050   EVT EltVT = VT;
8051   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8052   if (VT.isVector()) {
8053     EltVT = VT.getVectorElementType();
8054     NumElts = VT.getVectorNumElements();
8055   }
8056   Constant *C;
8057   if (EltVT == MVT::f64)
8058     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8059   else
8060     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8061   C = ConstantVector::getSplat(NumElts, C);
8062   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8063   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8064                              MachinePointerInfo::getConstantPool(),
8065                              false, false, false, 16);
8066   if (VT.isVector()) {
8067     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
8068     return DAG.getNode(ISD::BITCAST, dl, VT,
8069                        DAG.getNode(ISD::XOR, dl, XORVT,
8070                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8071                                                Op.getOperand(0)),
8072                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8073   }
8074
8075   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8076 }
8077
8078 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8079   LLVMContext *Context = DAG.getContext();
8080   SDValue Op0 = Op.getOperand(0);
8081   SDValue Op1 = Op.getOperand(1);
8082   DebugLoc dl = Op.getDebugLoc();
8083   EVT VT = Op.getValueType();
8084   EVT SrcVT = Op1.getValueType();
8085
8086   // If second operand is smaller, extend it first.
8087   if (SrcVT.bitsLT(VT)) {
8088     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8089     SrcVT = VT;
8090   }
8091   // And if it is bigger, shrink it first.
8092   if (SrcVT.bitsGT(VT)) {
8093     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8094     SrcVT = VT;
8095   }
8096
8097   // At this point the operands and the result should have the same
8098   // type, and that won't be f80 since that is not custom lowered.
8099
8100   // First get the sign bit of second operand.
8101   SmallVector<Constant*,4> CV;
8102   if (SrcVT == MVT::f64) {
8103     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8104     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8105   } else {
8106     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8107     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8108     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8109     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8110   }
8111   Constant *C = ConstantVector::get(CV);
8112   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8113   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8114                               MachinePointerInfo::getConstantPool(),
8115                               false, false, false, 16);
8116   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8117
8118   // Shift sign bit right or left if the two operands have different types.
8119   if (SrcVT.bitsGT(VT)) {
8120     // Op0 is MVT::f32, Op1 is MVT::f64.
8121     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8122     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8123                           DAG.getConstant(32, MVT::i32));
8124     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8125     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8126                           DAG.getIntPtrConstant(0));
8127   }
8128
8129   // Clear first operand sign bit.
8130   CV.clear();
8131   if (VT == MVT::f64) {
8132     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8133     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8134   } else {
8135     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8136     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8137     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8138     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8139   }
8140   C = ConstantVector::get(CV);
8141   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8142   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8143                               MachinePointerInfo::getConstantPool(),
8144                               false, false, false, 16);
8145   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8146
8147   // Or the value with the sign bit.
8148   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8149 }
8150
8151 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8152   SDValue N0 = Op.getOperand(0);
8153   DebugLoc dl = Op.getDebugLoc();
8154   EVT VT = Op.getValueType();
8155
8156   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8157   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8158                                   DAG.getConstant(1, VT));
8159   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8160 }
8161
8162 /// Emit nodes that will be selected as "test Op0,Op0", or something
8163 /// equivalent.
8164 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8165                                     SelectionDAG &DAG) const {
8166   DebugLoc dl = Op.getDebugLoc();
8167
8168   // CF and OF aren't always set the way we want. Determine which
8169   // of these we need.
8170   bool NeedCF = false;
8171   bool NeedOF = false;
8172   switch (X86CC) {
8173   default: break;
8174   case X86::COND_A: case X86::COND_AE:
8175   case X86::COND_B: case X86::COND_BE:
8176     NeedCF = true;
8177     break;
8178   case X86::COND_G: case X86::COND_GE:
8179   case X86::COND_L: case X86::COND_LE:
8180   case X86::COND_O: case X86::COND_NO:
8181     NeedOF = true;
8182     break;
8183   }
8184
8185   // See if we can use the EFLAGS value from the operand instead of
8186   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8187   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8188   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8189     // Emit a CMP with 0, which is the TEST pattern.
8190     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8191                        DAG.getConstant(0, Op.getValueType()));
8192
8193   unsigned Opcode = 0;
8194   unsigned NumOperands = 0;
8195   switch (Op.getNode()->getOpcode()) {
8196   case ISD::ADD:
8197     // Due to an isel shortcoming, be conservative if this add is likely to be
8198     // selected as part of a load-modify-store instruction. When the root node
8199     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8200     // uses of other nodes in the match, such as the ADD in this case. This
8201     // leads to the ADD being left around and reselected, with the result being
8202     // two adds in the output.  Alas, even if none our users are stores, that
8203     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8204     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8205     // climbing the DAG back to the root, and it doesn't seem to be worth the
8206     // effort.
8207     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8208          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8209       if (UI->getOpcode() != ISD::CopyToReg &&
8210           UI->getOpcode() != ISD::SETCC &&
8211           UI->getOpcode() != ISD::STORE)
8212         goto default_case;
8213
8214     if (ConstantSDNode *C =
8215         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8216       // An add of one will be selected as an INC.
8217       if (C->getAPIntValue() == 1) {
8218         Opcode = X86ISD::INC;
8219         NumOperands = 1;
8220         break;
8221       }
8222
8223       // An add of negative one (subtract of one) will be selected as a DEC.
8224       if (C->getAPIntValue().isAllOnesValue()) {
8225         Opcode = X86ISD::DEC;
8226         NumOperands = 1;
8227         break;
8228       }
8229     }
8230
8231     // Otherwise use a regular EFLAGS-setting add.
8232     Opcode = X86ISD::ADD;
8233     NumOperands = 2;
8234     break;
8235   case ISD::AND: {
8236     // If the primary and result isn't used, don't bother using X86ISD::AND,
8237     // because a TEST instruction will be better.
8238     bool NonFlagUse = false;
8239     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8240            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8241       SDNode *User = *UI;
8242       unsigned UOpNo = UI.getOperandNo();
8243       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8244         // Look pass truncate.
8245         UOpNo = User->use_begin().getOperandNo();
8246         User = *User->use_begin();
8247       }
8248
8249       if (User->getOpcode() != ISD::BRCOND &&
8250           User->getOpcode() != ISD::SETCC &&
8251           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8252         NonFlagUse = true;
8253         break;
8254       }
8255     }
8256
8257     if (!NonFlagUse)
8258       break;
8259   }
8260     // FALL THROUGH
8261   case ISD::SUB:
8262   case ISD::OR:
8263   case ISD::XOR:
8264     // Due to the ISEL shortcoming noted above, be conservative if this op is
8265     // likely to be selected as part of a load-modify-store instruction.
8266     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8267            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8268       if (UI->getOpcode() == ISD::STORE)
8269         goto default_case;
8270
8271     // Otherwise use a regular EFLAGS-setting instruction.
8272     switch (Op.getNode()->getOpcode()) {
8273     default: llvm_unreachable("unexpected operator!");
8274     case ISD::SUB: Opcode = X86ISD::SUB; break;
8275     case ISD::OR:  Opcode = X86ISD::OR;  break;
8276     case ISD::XOR: Opcode = X86ISD::XOR; break;
8277     case ISD::AND: Opcode = X86ISD::AND; break;
8278     }
8279
8280     NumOperands = 2;
8281     break;
8282   case X86ISD::ADD:
8283   case X86ISD::SUB:
8284   case X86ISD::INC:
8285   case X86ISD::DEC:
8286   case X86ISD::OR:
8287   case X86ISD::XOR:
8288   case X86ISD::AND:
8289     return SDValue(Op.getNode(), 1);
8290   default:
8291   default_case:
8292     break;
8293   }
8294
8295   if (Opcode == 0)
8296     // Emit a CMP with 0, which is the TEST pattern.
8297     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8298                        DAG.getConstant(0, Op.getValueType()));
8299
8300   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8301   SmallVector<SDValue, 4> Ops;
8302   for (unsigned i = 0; i != NumOperands; ++i)
8303     Ops.push_back(Op.getOperand(i));
8304
8305   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8306   DAG.ReplaceAllUsesWith(Op, New);
8307   return SDValue(New.getNode(), 1);
8308 }
8309
8310 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8311 /// equivalent.
8312 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8313                                    SelectionDAG &DAG) const {
8314   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8315     if (C->getAPIntValue() == 0)
8316       return EmitTest(Op0, X86CC, DAG);
8317
8318   DebugLoc dl = Op0.getDebugLoc();
8319   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8320 }
8321
8322 /// Convert a comparison if required by the subtarget.
8323 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8324                                                  SelectionDAG &DAG) const {
8325   // If the subtarget does not support the FUCOMI instruction, floating-point
8326   // comparisons have to be converted.
8327   if (Subtarget->hasCMov() ||
8328       Cmp.getOpcode() != X86ISD::CMP ||
8329       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8330       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8331     return Cmp;
8332
8333   // The instruction selector will select an FUCOM instruction instead of
8334   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8335   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8336   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8337   DebugLoc dl = Cmp.getDebugLoc();
8338   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8339   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8340   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8341                             DAG.getConstant(8, MVT::i8));
8342   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8343   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8344 }
8345
8346 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8347 /// if it's possible.
8348 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8349                                      DebugLoc dl, SelectionDAG &DAG) const {
8350   SDValue Op0 = And.getOperand(0);
8351   SDValue Op1 = And.getOperand(1);
8352   if (Op0.getOpcode() == ISD::TRUNCATE)
8353     Op0 = Op0.getOperand(0);
8354   if (Op1.getOpcode() == ISD::TRUNCATE)
8355     Op1 = Op1.getOperand(0);
8356
8357   SDValue LHS, RHS;
8358   if (Op1.getOpcode() == ISD::SHL)
8359     std::swap(Op0, Op1);
8360   if (Op0.getOpcode() == ISD::SHL) {
8361     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8362       if (And00C->getZExtValue() == 1) {
8363         // If we looked past a truncate, check that it's only truncating away
8364         // known zeros.
8365         unsigned BitWidth = Op0.getValueSizeInBits();
8366         unsigned AndBitWidth = And.getValueSizeInBits();
8367         if (BitWidth > AndBitWidth) {
8368           APInt Zeros, Ones;
8369           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8370           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8371             return SDValue();
8372         }
8373         LHS = Op1;
8374         RHS = Op0.getOperand(1);
8375       }
8376   } else if (Op1.getOpcode() == ISD::Constant) {
8377     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8378     uint64_t AndRHSVal = AndRHS->getZExtValue();
8379     SDValue AndLHS = Op0;
8380
8381     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8382       LHS = AndLHS.getOperand(0);
8383       RHS = AndLHS.getOperand(1);
8384     }
8385
8386     // Use BT if the immediate can't be encoded in a TEST instruction.
8387     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8388       LHS = AndLHS;
8389       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8390     }
8391   }
8392
8393   if (LHS.getNode()) {
8394     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8395     // instruction.  Since the shift amount is in-range-or-undefined, we know
8396     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8397     // the encoding for the i16 version is larger than the i32 version.
8398     // Also promote i16 to i32 for performance / code size reason.
8399     if (LHS.getValueType() == MVT::i8 ||
8400         LHS.getValueType() == MVT::i16)
8401       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8402
8403     // If the operand types disagree, extend the shift amount to match.  Since
8404     // BT ignores high bits (like shifts) we can use anyextend.
8405     if (LHS.getValueType() != RHS.getValueType())
8406       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8407
8408     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8409     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8410     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8411                        DAG.getConstant(Cond, MVT::i8), BT);
8412   }
8413
8414   return SDValue();
8415 }
8416
8417 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8418
8419   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8420
8421   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8422   SDValue Op0 = Op.getOperand(0);
8423   SDValue Op1 = Op.getOperand(1);
8424   DebugLoc dl = Op.getDebugLoc();
8425   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8426
8427   // Optimize to BT if possible.
8428   // Lower (X & (1 << N)) == 0 to BT(X, N).
8429   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8430   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8431   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8432       Op1.getOpcode() == ISD::Constant &&
8433       cast<ConstantSDNode>(Op1)->isNullValue() &&
8434       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8435     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8436     if (NewSetCC.getNode())
8437       return NewSetCC;
8438   }
8439
8440   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8441   // these.
8442   if (Op1.getOpcode() == ISD::Constant &&
8443       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8444        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8445       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8446
8447     // If the input is a setcc, then reuse the input setcc or use a new one with
8448     // the inverted condition.
8449     if (Op0.getOpcode() == X86ISD::SETCC) {
8450       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8451       bool Invert = (CC == ISD::SETNE) ^
8452         cast<ConstantSDNode>(Op1)->isNullValue();
8453       if (!Invert) return Op0;
8454
8455       CCode = X86::GetOppositeBranchCondition(CCode);
8456       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8457                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8458     }
8459   }
8460
8461   bool isFP = Op1.getValueType().isFloatingPoint();
8462   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8463   if (X86CC == X86::COND_INVALID)
8464     return SDValue();
8465
8466   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8467   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8468   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8469                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8470 }
8471
8472 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8473 // ones, and then concatenate the result back.
8474 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8475   EVT VT = Op.getValueType();
8476
8477   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8478          "Unsupported value type for operation");
8479
8480   unsigned NumElems = VT.getVectorNumElements();
8481   DebugLoc dl = Op.getDebugLoc();
8482   SDValue CC = Op.getOperand(2);
8483
8484   // Extract the LHS vectors
8485   SDValue LHS = Op.getOperand(0);
8486   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8487   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8488
8489   // Extract the RHS vectors
8490   SDValue RHS = Op.getOperand(1);
8491   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8492   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8493
8494   // Issue the operation on the smaller types and concatenate the result back
8495   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8496   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8497   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8498                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8499                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8500 }
8501
8502
8503 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8504   SDValue Cond;
8505   SDValue Op0 = Op.getOperand(0);
8506   SDValue Op1 = Op.getOperand(1);
8507   SDValue CC = Op.getOperand(2);
8508   EVT VT = Op.getValueType();
8509   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8510   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8511   DebugLoc dl = Op.getDebugLoc();
8512
8513   if (isFP) {
8514     unsigned SSECC = 8;
8515     EVT EltVT = Op0.getValueType().getVectorElementType();
8516     assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8517
8518     bool Swap = false;
8519
8520     // SSE Condition code mapping:
8521     //  0 - EQ
8522     //  1 - LT
8523     //  2 - LE
8524     //  3 - UNORD
8525     //  4 - NEQ
8526     //  5 - NLT
8527     //  6 - NLE
8528     //  7 - ORD
8529     switch (SetCCOpcode) {
8530     default: break;
8531     case ISD::SETOEQ:
8532     case ISD::SETEQ:  SSECC = 0; break;
8533     case ISD::SETOGT:
8534     case ISD::SETGT: Swap = true; // Fallthrough
8535     case ISD::SETLT:
8536     case ISD::SETOLT: SSECC = 1; break;
8537     case ISD::SETOGE:
8538     case ISD::SETGE: Swap = true; // Fallthrough
8539     case ISD::SETLE:
8540     case ISD::SETOLE: SSECC = 2; break;
8541     case ISD::SETUO:  SSECC = 3; break;
8542     case ISD::SETUNE:
8543     case ISD::SETNE:  SSECC = 4; break;
8544     case ISD::SETULE: Swap = true;
8545     case ISD::SETUGE: SSECC = 5; break;
8546     case ISD::SETULT: Swap = true;
8547     case ISD::SETUGT: SSECC = 6; break;
8548     case ISD::SETO:   SSECC = 7; break;
8549     }
8550     if (Swap)
8551       std::swap(Op0, Op1);
8552
8553     // In the two special cases we can't handle, emit two comparisons.
8554     if (SSECC == 8) {
8555       if (SetCCOpcode == ISD::SETUEQ) {
8556         SDValue UNORD, EQ;
8557         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8558                             DAG.getConstant(3, MVT::i8));
8559         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8560                          DAG.getConstant(0, MVT::i8));
8561         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8562       }
8563       if (SetCCOpcode == ISD::SETONE) {
8564         SDValue ORD, NEQ;
8565         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8566                           DAG.getConstant(7, MVT::i8));
8567         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8568                           DAG.getConstant(4, MVT::i8));
8569         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8570       }
8571       llvm_unreachable("Illegal FP comparison");
8572     }
8573     // Handle all other FP comparisons here.
8574     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8575                        DAG.getConstant(SSECC, MVT::i8));
8576   }
8577
8578   // Break 256-bit integer vector compare into smaller ones.
8579   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8580     return Lower256IntVSETCC(Op, DAG);
8581
8582   // We are handling one of the integer comparisons here.  Since SSE only has
8583   // GT and EQ comparisons for integer, swapping operands and multiple
8584   // operations may be required for some comparisons.
8585   unsigned Opc = 0;
8586   bool Swap = false, Invert = false, FlipSigns = false;
8587
8588   switch (SetCCOpcode) {
8589   default: break;
8590   case ISD::SETNE:  Invert = true;
8591   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8592   case ISD::SETLT:  Swap = true;
8593   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8594   case ISD::SETGE:  Swap = true;
8595   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8596   case ISD::SETULT: Swap = true;
8597   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8598   case ISD::SETUGE: Swap = true;
8599   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8600   }
8601   if (Swap)
8602     std::swap(Op0, Op1);
8603
8604   // Check that the operation in question is available (most are plain SSE2,
8605   // but PCMPGTQ and PCMPEQQ have different requirements).
8606   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8607     return SDValue();
8608   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8609     return SDValue();
8610
8611   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8612   // bits of the inputs before performing those operations.
8613   if (FlipSigns) {
8614     EVT EltVT = VT.getVectorElementType();
8615     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8616                                       EltVT);
8617     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8618     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8619                                     SignBits.size());
8620     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8621     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8622   }
8623
8624   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8625
8626   // If the logical-not of the result is required, perform that now.
8627   if (Invert)
8628     Result = DAG.getNOT(dl, Result, VT);
8629
8630   return Result;
8631 }
8632
8633 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8634 static bool isX86LogicalCmp(SDValue Op) {
8635   unsigned Opc = Op.getNode()->getOpcode();
8636   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8637       Opc == X86ISD::SAHF)
8638     return true;
8639   if (Op.getResNo() == 1 &&
8640       (Opc == X86ISD::ADD ||
8641        Opc == X86ISD::SUB ||
8642        Opc == X86ISD::ADC ||
8643        Opc == X86ISD::SBB ||
8644        Opc == X86ISD::SMUL ||
8645        Opc == X86ISD::UMUL ||
8646        Opc == X86ISD::INC ||
8647        Opc == X86ISD::DEC ||
8648        Opc == X86ISD::OR ||
8649        Opc == X86ISD::XOR ||
8650        Opc == X86ISD::AND))
8651     return true;
8652
8653   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8654     return true;
8655
8656   return false;
8657 }
8658
8659 static bool isZero(SDValue V) {
8660   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8661   return C && C->isNullValue();
8662 }
8663
8664 static bool isAllOnes(SDValue V) {
8665   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8666   return C && C->isAllOnesValue();
8667 }
8668
8669 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8670   bool addTest = true;
8671   SDValue Cond  = Op.getOperand(0);
8672   SDValue Op1 = Op.getOperand(1);
8673   SDValue Op2 = Op.getOperand(2);
8674   DebugLoc DL = Op.getDebugLoc();
8675   SDValue CC;
8676
8677   if (Cond.getOpcode() == ISD::SETCC) {
8678     SDValue NewCond = LowerSETCC(Cond, DAG);
8679     if (NewCond.getNode())
8680       Cond = NewCond;
8681   }
8682
8683   // Handle the following cases related to max and min:
8684   // (a > b) ? (a-b) : 0
8685   // (a >= b) ? (a-b) : 0
8686   // (b < a) ? (a-b) : 0
8687   // (b <= a) ? (a-b) : 0
8688   // Comparison is removed to use EFLAGS from SUB.
8689   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2))
8690     if (Cond.getOpcode() == X86ISD::SETCC &&
8691         Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8692         (Op1.getOpcode() == ISD::SUB || Op1.getOpcode() == X86ISD::SUB) &&
8693         C->getAPIntValue() == 0) {
8694       SDValue Cmp = Cond.getOperand(1);
8695       unsigned CC = cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8696       if ((DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(0)) &&
8697            DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(1)) &&
8698            (CC == X86::COND_G || CC == X86::COND_GE ||
8699             CC == X86::COND_A || CC == X86::COND_AE)) ||
8700           (DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(1)) &&
8701            DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(0)) &&
8702            (CC == X86::COND_L || CC == X86::COND_LE ||
8703             CC == X86::COND_B || CC == X86::COND_BE))) {
8704
8705         if (Op1.getOpcode() == ISD::SUB) {
8706           SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i32);
8707           SDValue New = DAG.getNode(X86ISD::SUB, DL, VTs,
8708                                     Op1.getOperand(0), Op1.getOperand(1));
8709           DAG.ReplaceAllUsesWith(Op1, New);
8710           Op1 = New;
8711         }
8712
8713         SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8714         unsigned NewCC = (CC == X86::COND_G || CC == X86::COND_GE ||
8715                           CC == X86::COND_L ||
8716                           CC == X86::COND_LE) ? X86::COND_GE : X86::COND_AE;
8717         SDValue Ops[] = { Op2, Op1, DAG.getConstant(NewCC, MVT::i8),
8718                           SDValue(Op1.getNode(), 1) };
8719         return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8720       }
8721     }
8722
8723   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8724   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8725   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8726   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8727   if (Cond.getOpcode() == X86ISD::SETCC &&
8728       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8729       isZero(Cond.getOperand(1).getOperand(1))) {
8730     SDValue Cmp = Cond.getOperand(1);
8731
8732     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8733
8734     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8735         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8736       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8737
8738       SDValue CmpOp0 = Cmp.getOperand(0);
8739       // Apply further optimizations for special cases
8740       // (select (x != 0), -1, 0) -> neg & sbb
8741       // (select (x == 0), 0, -1) -> neg & sbb
8742       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8743         if (YC->isNullValue() && 
8744             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8745           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8746           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs, 
8747                                     DAG.getConstant(0, CmpOp0.getValueType()), 
8748                                     CmpOp0);
8749           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8750                                     DAG.getConstant(X86::COND_B, MVT::i8),
8751                                     SDValue(Neg.getNode(), 1));
8752           return Res;
8753         }
8754
8755       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8756                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8757       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8758
8759       SDValue Res =   // Res = 0 or -1.
8760         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8761                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8762
8763       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8764         Res = DAG.getNOT(DL, Res, Res.getValueType());
8765
8766       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8767       if (N2C == 0 || !N2C->isNullValue())
8768         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8769       return Res;
8770     }
8771   }
8772
8773   // Look past (and (setcc_carry (cmp ...)), 1).
8774   if (Cond.getOpcode() == ISD::AND &&
8775       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8776     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8777     if (C && C->getAPIntValue() == 1)
8778       Cond = Cond.getOperand(0);
8779   }
8780
8781   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8782   // setting operand in place of the X86ISD::SETCC.
8783   unsigned CondOpcode = Cond.getOpcode();
8784   if (CondOpcode == X86ISD::SETCC ||
8785       CondOpcode == X86ISD::SETCC_CARRY) {
8786     CC = Cond.getOperand(0);
8787
8788     SDValue Cmp = Cond.getOperand(1);
8789     unsigned Opc = Cmp.getOpcode();
8790     EVT VT = Op.getValueType();
8791
8792     bool IllegalFPCMov = false;
8793     if (VT.isFloatingPoint() && !VT.isVector() &&
8794         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8795       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8796
8797     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8798         Opc == X86ISD::BT) { // FIXME
8799       Cond = Cmp;
8800       addTest = false;
8801     }
8802   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8803              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8804              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8805               Cond.getOperand(0).getValueType() != MVT::i8)) {
8806     SDValue LHS = Cond.getOperand(0);
8807     SDValue RHS = Cond.getOperand(1);
8808     unsigned X86Opcode;
8809     unsigned X86Cond;
8810     SDVTList VTs;
8811     switch (CondOpcode) {
8812     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8813     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8814     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8815     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8816     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8817     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8818     default: llvm_unreachable("unexpected overflowing operator");
8819     }
8820     if (CondOpcode == ISD::UMULO)
8821       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8822                           MVT::i32);
8823     else
8824       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8825
8826     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8827
8828     if (CondOpcode == ISD::UMULO)
8829       Cond = X86Op.getValue(2);
8830     else
8831       Cond = X86Op.getValue(1);
8832
8833     CC = DAG.getConstant(X86Cond, MVT::i8);
8834     addTest = false;
8835   }
8836
8837   if (addTest) {
8838     // Look pass the truncate.
8839     if (Cond.getOpcode() == ISD::TRUNCATE)
8840       Cond = Cond.getOperand(0);
8841
8842     // We know the result of AND is compared against zero. Try to match
8843     // it to BT.
8844     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8845       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8846       if (NewSetCC.getNode()) {
8847         CC = NewSetCC.getOperand(0);
8848         Cond = NewSetCC.getOperand(1);
8849         addTest = false;
8850       }
8851     }
8852   }
8853
8854   if (addTest) {
8855     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8856     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8857   }
8858
8859   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8860   // a <  b ?  0 : -1 -> RES = setcc_carry
8861   // a >= b ? -1 :  0 -> RES = setcc_carry
8862   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8863   if (Cond.getOpcode() == X86ISD::CMP) {
8864     Cond = ConvertCmpIfNecessary(Cond, DAG);
8865     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8866
8867     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8868         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8869       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8870                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8871       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8872         return DAG.getNOT(DL, Res, Res.getValueType());
8873       return Res;
8874     }
8875   }
8876
8877   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8878   // condition is true.
8879   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8880   SDValue Ops[] = { Op2, Op1, CC, Cond };
8881   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8882 }
8883
8884 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8885 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8886 // from the AND / OR.
8887 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8888   Opc = Op.getOpcode();
8889   if (Opc != ISD::OR && Opc != ISD::AND)
8890     return false;
8891   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8892           Op.getOperand(0).hasOneUse() &&
8893           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8894           Op.getOperand(1).hasOneUse());
8895 }
8896
8897 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8898 // 1 and that the SETCC node has a single use.
8899 static bool isXor1OfSetCC(SDValue Op) {
8900   if (Op.getOpcode() != ISD::XOR)
8901     return false;
8902   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8903   if (N1C && N1C->getAPIntValue() == 1) {
8904     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8905       Op.getOperand(0).hasOneUse();
8906   }
8907   return false;
8908 }
8909
8910 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8911   bool addTest = true;
8912   SDValue Chain = Op.getOperand(0);
8913   SDValue Cond  = Op.getOperand(1);
8914   SDValue Dest  = Op.getOperand(2);
8915   DebugLoc dl = Op.getDebugLoc();
8916   SDValue CC;
8917   bool Inverted = false;
8918
8919   if (Cond.getOpcode() == ISD::SETCC) {
8920     // Check for setcc([su]{add,sub,mul}o == 0).
8921     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8922         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8923         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8924         Cond.getOperand(0).getResNo() == 1 &&
8925         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8926          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8927          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8928          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8929          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8930          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8931       Inverted = true;
8932       Cond = Cond.getOperand(0);
8933     } else {
8934       SDValue NewCond = LowerSETCC(Cond, DAG);
8935       if (NewCond.getNode())
8936         Cond = NewCond;
8937     }
8938   }
8939 #if 0
8940   // FIXME: LowerXALUO doesn't handle these!!
8941   else if (Cond.getOpcode() == X86ISD::ADD  ||
8942            Cond.getOpcode() == X86ISD::SUB  ||
8943            Cond.getOpcode() == X86ISD::SMUL ||
8944            Cond.getOpcode() == X86ISD::UMUL)
8945     Cond = LowerXALUO(Cond, DAG);
8946 #endif
8947
8948   // Look pass (and (setcc_carry (cmp ...)), 1).
8949   if (Cond.getOpcode() == ISD::AND &&
8950       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8951     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8952     if (C && C->getAPIntValue() == 1)
8953       Cond = Cond.getOperand(0);
8954   }
8955
8956   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8957   // setting operand in place of the X86ISD::SETCC.
8958   unsigned CondOpcode = Cond.getOpcode();
8959   if (CondOpcode == X86ISD::SETCC ||
8960       CondOpcode == X86ISD::SETCC_CARRY) {
8961     CC = Cond.getOperand(0);
8962
8963     SDValue Cmp = Cond.getOperand(1);
8964     unsigned Opc = Cmp.getOpcode();
8965     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8966     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8967       Cond = Cmp;
8968       addTest = false;
8969     } else {
8970       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8971       default: break;
8972       case X86::COND_O:
8973       case X86::COND_B:
8974         // These can only come from an arithmetic instruction with overflow,
8975         // e.g. SADDO, UADDO.
8976         Cond = Cond.getNode()->getOperand(1);
8977         addTest = false;
8978         break;
8979       }
8980     }
8981   }
8982   CondOpcode = Cond.getOpcode();
8983   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8984       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8985       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8986        Cond.getOperand(0).getValueType() != MVT::i8)) {
8987     SDValue LHS = Cond.getOperand(0);
8988     SDValue RHS = Cond.getOperand(1);
8989     unsigned X86Opcode;
8990     unsigned X86Cond;
8991     SDVTList VTs;
8992     switch (CondOpcode) {
8993     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8994     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8995     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8996     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8997     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8998     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8999     default: llvm_unreachable("unexpected overflowing operator");
9000     }
9001     if (Inverted)
9002       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9003     if (CondOpcode == ISD::UMULO)
9004       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9005                           MVT::i32);
9006     else
9007       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9008
9009     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9010
9011     if (CondOpcode == ISD::UMULO)
9012       Cond = X86Op.getValue(2);
9013     else
9014       Cond = X86Op.getValue(1);
9015
9016     CC = DAG.getConstant(X86Cond, MVT::i8);
9017     addTest = false;
9018   } else {
9019     unsigned CondOpc;
9020     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9021       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9022       if (CondOpc == ISD::OR) {
9023         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9024         // two branches instead of an explicit OR instruction with a
9025         // separate test.
9026         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9027             isX86LogicalCmp(Cmp)) {
9028           CC = Cond.getOperand(0).getOperand(0);
9029           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9030                               Chain, Dest, CC, Cmp);
9031           CC = Cond.getOperand(1).getOperand(0);
9032           Cond = Cmp;
9033           addTest = false;
9034         }
9035       } else { // ISD::AND
9036         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9037         // two branches instead of an explicit AND instruction with a
9038         // separate test. However, we only do this if this block doesn't
9039         // have a fall-through edge, because this requires an explicit
9040         // jmp when the condition is false.
9041         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9042             isX86LogicalCmp(Cmp) &&
9043             Op.getNode()->hasOneUse()) {
9044           X86::CondCode CCode =
9045             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9046           CCode = X86::GetOppositeBranchCondition(CCode);
9047           CC = DAG.getConstant(CCode, MVT::i8);
9048           SDNode *User = *Op.getNode()->use_begin();
9049           // Look for an unconditional branch following this conditional branch.
9050           // We need this because we need to reverse the successors in order
9051           // to implement FCMP_OEQ.
9052           if (User->getOpcode() == ISD::BR) {
9053             SDValue FalseBB = User->getOperand(1);
9054             SDNode *NewBR =
9055               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9056             assert(NewBR == User);
9057             (void)NewBR;
9058             Dest = FalseBB;
9059
9060             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9061                                 Chain, Dest, CC, Cmp);
9062             X86::CondCode CCode =
9063               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9064             CCode = X86::GetOppositeBranchCondition(CCode);
9065             CC = DAG.getConstant(CCode, MVT::i8);
9066             Cond = Cmp;
9067             addTest = false;
9068           }
9069         }
9070       }
9071     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9072       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9073       // It should be transformed during dag combiner except when the condition
9074       // is set by a arithmetics with overflow node.
9075       X86::CondCode CCode =
9076         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9077       CCode = X86::GetOppositeBranchCondition(CCode);
9078       CC = DAG.getConstant(CCode, MVT::i8);
9079       Cond = Cond.getOperand(0).getOperand(1);
9080       addTest = false;
9081     } else if (Cond.getOpcode() == ISD::SETCC &&
9082                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9083       // For FCMP_OEQ, we can emit
9084       // two branches instead of an explicit AND instruction with a
9085       // separate test. However, we only do this if this block doesn't
9086       // have a fall-through edge, because this requires an explicit
9087       // jmp when the condition is false.
9088       if (Op.getNode()->hasOneUse()) {
9089         SDNode *User = *Op.getNode()->use_begin();
9090         // Look for an unconditional branch following this conditional branch.
9091         // We need this because we need to reverse the successors in order
9092         // to implement FCMP_OEQ.
9093         if (User->getOpcode() == ISD::BR) {
9094           SDValue FalseBB = User->getOperand(1);
9095           SDNode *NewBR =
9096             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9097           assert(NewBR == User);
9098           (void)NewBR;
9099           Dest = FalseBB;
9100
9101           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9102                                     Cond.getOperand(0), Cond.getOperand(1));
9103           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9104           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9105           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9106                               Chain, Dest, CC, Cmp);
9107           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9108           Cond = Cmp;
9109           addTest = false;
9110         }
9111       }
9112     } else if (Cond.getOpcode() == ISD::SETCC &&
9113                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9114       // For FCMP_UNE, we can emit
9115       // two branches instead of an explicit AND instruction with a
9116       // separate test. However, we only do this if this block doesn't
9117       // have a fall-through edge, because this requires an explicit
9118       // jmp when the condition is false.
9119       if (Op.getNode()->hasOneUse()) {
9120         SDNode *User = *Op.getNode()->use_begin();
9121         // Look for an unconditional branch following this conditional branch.
9122         // We need this because we need to reverse the successors in order
9123         // to implement FCMP_UNE.
9124         if (User->getOpcode() == ISD::BR) {
9125           SDValue FalseBB = User->getOperand(1);
9126           SDNode *NewBR =
9127             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9128           assert(NewBR == User);
9129           (void)NewBR;
9130
9131           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9132                                     Cond.getOperand(0), Cond.getOperand(1));
9133           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9134           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9135           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9136                               Chain, Dest, CC, Cmp);
9137           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9138           Cond = Cmp;
9139           addTest = false;
9140           Dest = FalseBB;
9141         }
9142       }
9143     }
9144   }
9145
9146   if (addTest) {
9147     // Look pass the truncate.
9148     if (Cond.getOpcode() == ISD::TRUNCATE)
9149       Cond = Cond.getOperand(0);
9150
9151     // We know the result of AND is compared against zero. Try to match
9152     // it to BT.
9153     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9154       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9155       if (NewSetCC.getNode()) {
9156         CC = NewSetCC.getOperand(0);
9157         Cond = NewSetCC.getOperand(1);
9158         addTest = false;
9159       }
9160     }
9161   }
9162
9163   if (addTest) {
9164     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9165     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9166   }
9167   Cond = ConvertCmpIfNecessary(Cond, DAG);
9168   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9169                      Chain, Dest, CC, Cond);
9170 }
9171
9172
9173 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9174 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9175 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9176 // that the guard pages used by the OS virtual memory manager are allocated in
9177 // correct sequence.
9178 SDValue
9179 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9180                                            SelectionDAG &DAG) const {
9181   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9182           getTargetMachine().Options.EnableSegmentedStacks) &&
9183          "This should be used only on Windows targets or when segmented stacks "
9184          "are being used");
9185   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9186   DebugLoc dl = Op.getDebugLoc();
9187
9188   // Get the inputs.
9189   SDValue Chain = Op.getOperand(0);
9190   SDValue Size  = Op.getOperand(1);
9191   // FIXME: Ensure alignment here
9192
9193   bool Is64Bit = Subtarget->is64Bit();
9194   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9195
9196   if (getTargetMachine().Options.EnableSegmentedStacks) {
9197     MachineFunction &MF = DAG.getMachineFunction();
9198     MachineRegisterInfo &MRI = MF.getRegInfo();
9199
9200     if (Is64Bit) {
9201       // The 64 bit implementation of segmented stacks needs to clobber both r10
9202       // r11. This makes it impossible to use it along with nested parameters.
9203       const Function *F = MF.getFunction();
9204
9205       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9206            I != E; ++I)
9207         if (I->hasNestAttr())
9208           report_fatal_error("Cannot use segmented stacks with functions that "
9209                              "have nested arguments.");
9210     }
9211
9212     const TargetRegisterClass *AddrRegClass =
9213       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9214     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9215     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9216     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9217                                 DAG.getRegister(Vreg, SPTy));
9218     SDValue Ops1[2] = { Value, Chain };
9219     return DAG.getMergeValues(Ops1, 2, dl);
9220   } else {
9221     SDValue Flag;
9222     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9223
9224     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9225     Flag = Chain.getValue(1);
9226     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9227
9228     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9229     Flag = Chain.getValue(1);
9230
9231     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9232
9233     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9234     return DAG.getMergeValues(Ops1, 2, dl);
9235   }
9236 }
9237
9238 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9239   MachineFunction &MF = DAG.getMachineFunction();
9240   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9241
9242   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9243   DebugLoc DL = Op.getDebugLoc();
9244
9245   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9246     // vastart just stores the address of the VarArgsFrameIndex slot into the
9247     // memory location argument.
9248     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9249                                    getPointerTy());
9250     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9251                         MachinePointerInfo(SV), false, false, 0);
9252   }
9253
9254   // __va_list_tag:
9255   //   gp_offset         (0 - 6 * 8)
9256   //   fp_offset         (48 - 48 + 8 * 16)
9257   //   overflow_arg_area (point to parameters coming in memory).
9258   //   reg_save_area
9259   SmallVector<SDValue, 8> MemOps;
9260   SDValue FIN = Op.getOperand(1);
9261   // Store gp_offset
9262   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9263                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9264                                                MVT::i32),
9265                                FIN, MachinePointerInfo(SV), false, false, 0);
9266   MemOps.push_back(Store);
9267
9268   // Store fp_offset
9269   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9270                     FIN, DAG.getIntPtrConstant(4));
9271   Store = DAG.getStore(Op.getOperand(0), DL,
9272                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9273                                        MVT::i32),
9274                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9275   MemOps.push_back(Store);
9276
9277   // Store ptr to overflow_arg_area
9278   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9279                     FIN, DAG.getIntPtrConstant(4));
9280   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9281                                     getPointerTy());
9282   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9283                        MachinePointerInfo(SV, 8),
9284                        false, false, 0);
9285   MemOps.push_back(Store);
9286
9287   // Store ptr to reg_save_area.
9288   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9289                     FIN, DAG.getIntPtrConstant(8));
9290   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9291                                     getPointerTy());
9292   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9293                        MachinePointerInfo(SV, 16), false, false, 0);
9294   MemOps.push_back(Store);
9295   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9296                      &MemOps[0], MemOps.size());
9297 }
9298
9299 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9300   assert(Subtarget->is64Bit() &&
9301          "LowerVAARG only handles 64-bit va_arg!");
9302   assert((Subtarget->isTargetLinux() ||
9303           Subtarget->isTargetDarwin()) &&
9304           "Unhandled target in LowerVAARG");
9305   assert(Op.getNode()->getNumOperands() == 4);
9306   SDValue Chain = Op.getOperand(0);
9307   SDValue SrcPtr = Op.getOperand(1);
9308   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9309   unsigned Align = Op.getConstantOperandVal(3);
9310   DebugLoc dl = Op.getDebugLoc();
9311
9312   EVT ArgVT = Op.getNode()->getValueType(0);
9313   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9314   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9315   uint8_t ArgMode;
9316
9317   // Decide which area this value should be read from.
9318   // TODO: Implement the AMD64 ABI in its entirety. This simple
9319   // selection mechanism works only for the basic types.
9320   if (ArgVT == MVT::f80) {
9321     llvm_unreachable("va_arg for f80 not yet implemented");
9322   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9323     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9324   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9325     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9326   } else {
9327     llvm_unreachable("Unhandled argument type in LowerVAARG");
9328   }
9329
9330   if (ArgMode == 2) {
9331     // Sanity Check: Make sure using fp_offset makes sense.
9332     assert(!getTargetMachine().Options.UseSoftFloat &&
9333            !(DAG.getMachineFunction()
9334                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9335            Subtarget->hasSSE1());
9336   }
9337
9338   // Insert VAARG_64 node into the DAG
9339   // VAARG_64 returns two values: Variable Argument Address, Chain
9340   SmallVector<SDValue, 11> InstOps;
9341   InstOps.push_back(Chain);
9342   InstOps.push_back(SrcPtr);
9343   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9344   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9345   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9346   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9347   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9348                                           VTs, &InstOps[0], InstOps.size(),
9349                                           MVT::i64,
9350                                           MachinePointerInfo(SV),
9351                                           /*Align=*/0,
9352                                           /*Volatile=*/false,
9353                                           /*ReadMem=*/true,
9354                                           /*WriteMem=*/true);
9355   Chain = VAARG.getValue(1);
9356
9357   // Load the next argument and return it
9358   return DAG.getLoad(ArgVT, dl,
9359                      Chain,
9360                      VAARG,
9361                      MachinePointerInfo(),
9362                      false, false, false, 0);
9363 }
9364
9365 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9366   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9367   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9368   SDValue Chain = Op.getOperand(0);
9369   SDValue DstPtr = Op.getOperand(1);
9370   SDValue SrcPtr = Op.getOperand(2);
9371   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9372   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9373   DebugLoc DL = Op.getDebugLoc();
9374
9375   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9376                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9377                        false,
9378                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9379 }
9380
9381 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9382 // may or may not be a constant. Takes immediate version of shift as input.
9383 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9384                                    SDValue SrcOp, SDValue ShAmt,
9385                                    SelectionDAG &DAG) {
9386   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9387
9388   if (isa<ConstantSDNode>(ShAmt)) {
9389     switch (Opc) {
9390       default: llvm_unreachable("Unknown target vector shift node");
9391       case X86ISD::VSHLI:
9392       case X86ISD::VSRLI:
9393       case X86ISD::VSRAI:
9394         return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9395     }
9396   }
9397
9398   // Change opcode to non-immediate version
9399   switch (Opc) {
9400     default: llvm_unreachable("Unknown target vector shift node");
9401     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9402     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9403     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9404   }
9405
9406   // Need to build a vector containing shift amount
9407   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9408   SDValue ShOps[4];
9409   ShOps[0] = ShAmt;
9410   ShOps[1] = DAG.getConstant(0, MVT::i32);
9411   ShOps[2] = DAG.getUNDEF(MVT::i32);
9412   ShOps[3] = DAG.getUNDEF(MVT::i32);
9413   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9414   ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9415   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9416 }
9417
9418 SDValue
9419 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9420   DebugLoc dl = Op.getDebugLoc();
9421   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9422   switch (IntNo) {
9423   default: return SDValue();    // Don't custom lower most intrinsics.
9424   // Comparison intrinsics.
9425   case Intrinsic::x86_sse_comieq_ss:
9426   case Intrinsic::x86_sse_comilt_ss:
9427   case Intrinsic::x86_sse_comile_ss:
9428   case Intrinsic::x86_sse_comigt_ss:
9429   case Intrinsic::x86_sse_comige_ss:
9430   case Intrinsic::x86_sse_comineq_ss:
9431   case Intrinsic::x86_sse_ucomieq_ss:
9432   case Intrinsic::x86_sse_ucomilt_ss:
9433   case Intrinsic::x86_sse_ucomile_ss:
9434   case Intrinsic::x86_sse_ucomigt_ss:
9435   case Intrinsic::x86_sse_ucomige_ss:
9436   case Intrinsic::x86_sse_ucomineq_ss:
9437   case Intrinsic::x86_sse2_comieq_sd:
9438   case Intrinsic::x86_sse2_comilt_sd:
9439   case Intrinsic::x86_sse2_comile_sd:
9440   case Intrinsic::x86_sse2_comigt_sd:
9441   case Intrinsic::x86_sse2_comige_sd:
9442   case Intrinsic::x86_sse2_comineq_sd:
9443   case Intrinsic::x86_sse2_ucomieq_sd:
9444   case Intrinsic::x86_sse2_ucomilt_sd:
9445   case Intrinsic::x86_sse2_ucomile_sd:
9446   case Intrinsic::x86_sse2_ucomigt_sd:
9447   case Intrinsic::x86_sse2_ucomige_sd:
9448   case Intrinsic::x86_sse2_ucomineq_sd: {
9449     unsigned Opc = 0;
9450     ISD::CondCode CC = ISD::SETCC_INVALID;
9451     switch (IntNo) {
9452     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9453     case Intrinsic::x86_sse_comieq_ss:
9454     case Intrinsic::x86_sse2_comieq_sd:
9455       Opc = X86ISD::COMI;
9456       CC = ISD::SETEQ;
9457       break;
9458     case Intrinsic::x86_sse_comilt_ss:
9459     case Intrinsic::x86_sse2_comilt_sd:
9460       Opc = X86ISD::COMI;
9461       CC = ISD::SETLT;
9462       break;
9463     case Intrinsic::x86_sse_comile_ss:
9464     case Intrinsic::x86_sse2_comile_sd:
9465       Opc = X86ISD::COMI;
9466       CC = ISD::SETLE;
9467       break;
9468     case Intrinsic::x86_sse_comigt_ss:
9469     case Intrinsic::x86_sse2_comigt_sd:
9470       Opc = X86ISD::COMI;
9471       CC = ISD::SETGT;
9472       break;
9473     case Intrinsic::x86_sse_comige_ss:
9474     case Intrinsic::x86_sse2_comige_sd:
9475       Opc = X86ISD::COMI;
9476       CC = ISD::SETGE;
9477       break;
9478     case Intrinsic::x86_sse_comineq_ss:
9479     case Intrinsic::x86_sse2_comineq_sd:
9480       Opc = X86ISD::COMI;
9481       CC = ISD::SETNE;
9482       break;
9483     case Intrinsic::x86_sse_ucomieq_ss:
9484     case Intrinsic::x86_sse2_ucomieq_sd:
9485       Opc = X86ISD::UCOMI;
9486       CC = ISD::SETEQ;
9487       break;
9488     case Intrinsic::x86_sse_ucomilt_ss:
9489     case Intrinsic::x86_sse2_ucomilt_sd:
9490       Opc = X86ISD::UCOMI;
9491       CC = ISD::SETLT;
9492       break;
9493     case Intrinsic::x86_sse_ucomile_ss:
9494     case Intrinsic::x86_sse2_ucomile_sd:
9495       Opc = X86ISD::UCOMI;
9496       CC = ISD::SETLE;
9497       break;
9498     case Intrinsic::x86_sse_ucomigt_ss:
9499     case Intrinsic::x86_sse2_ucomigt_sd:
9500       Opc = X86ISD::UCOMI;
9501       CC = ISD::SETGT;
9502       break;
9503     case Intrinsic::x86_sse_ucomige_ss:
9504     case Intrinsic::x86_sse2_ucomige_sd:
9505       Opc = X86ISD::UCOMI;
9506       CC = ISD::SETGE;
9507       break;
9508     case Intrinsic::x86_sse_ucomineq_ss:
9509     case Intrinsic::x86_sse2_ucomineq_sd:
9510       Opc = X86ISD::UCOMI;
9511       CC = ISD::SETNE;
9512       break;
9513     }
9514
9515     SDValue LHS = Op.getOperand(1);
9516     SDValue RHS = Op.getOperand(2);
9517     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9518     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9519     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9520     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9521                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9522     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9523   }
9524   // XOP comparison intrinsics
9525   case Intrinsic::x86_xop_vpcomltb:
9526   case Intrinsic::x86_xop_vpcomltw:
9527   case Intrinsic::x86_xop_vpcomltd:
9528   case Intrinsic::x86_xop_vpcomltq:
9529   case Intrinsic::x86_xop_vpcomltub:
9530   case Intrinsic::x86_xop_vpcomltuw:
9531   case Intrinsic::x86_xop_vpcomltud:
9532   case Intrinsic::x86_xop_vpcomltuq:
9533   case Intrinsic::x86_xop_vpcomleb:
9534   case Intrinsic::x86_xop_vpcomlew:
9535   case Intrinsic::x86_xop_vpcomled:
9536   case Intrinsic::x86_xop_vpcomleq:
9537   case Intrinsic::x86_xop_vpcomleub:
9538   case Intrinsic::x86_xop_vpcomleuw:
9539   case Intrinsic::x86_xop_vpcomleud:
9540   case Intrinsic::x86_xop_vpcomleuq:
9541   case Intrinsic::x86_xop_vpcomgtb:
9542   case Intrinsic::x86_xop_vpcomgtw:
9543   case Intrinsic::x86_xop_vpcomgtd:
9544   case Intrinsic::x86_xop_vpcomgtq:
9545   case Intrinsic::x86_xop_vpcomgtub:
9546   case Intrinsic::x86_xop_vpcomgtuw:
9547   case Intrinsic::x86_xop_vpcomgtud:
9548   case Intrinsic::x86_xop_vpcomgtuq:
9549   case Intrinsic::x86_xop_vpcomgeb:
9550   case Intrinsic::x86_xop_vpcomgew:
9551   case Intrinsic::x86_xop_vpcomged:
9552   case Intrinsic::x86_xop_vpcomgeq:
9553   case Intrinsic::x86_xop_vpcomgeub:
9554   case Intrinsic::x86_xop_vpcomgeuw:
9555   case Intrinsic::x86_xop_vpcomgeud:
9556   case Intrinsic::x86_xop_vpcomgeuq:
9557   case Intrinsic::x86_xop_vpcomeqb:
9558   case Intrinsic::x86_xop_vpcomeqw:
9559   case Intrinsic::x86_xop_vpcomeqd:
9560   case Intrinsic::x86_xop_vpcomeqq:
9561   case Intrinsic::x86_xop_vpcomequb:
9562   case Intrinsic::x86_xop_vpcomequw:
9563   case Intrinsic::x86_xop_vpcomequd:
9564   case Intrinsic::x86_xop_vpcomequq:
9565   case Intrinsic::x86_xop_vpcomneb:
9566   case Intrinsic::x86_xop_vpcomnew:
9567   case Intrinsic::x86_xop_vpcomned:
9568   case Intrinsic::x86_xop_vpcomneq:
9569   case Intrinsic::x86_xop_vpcomneub:
9570   case Intrinsic::x86_xop_vpcomneuw:
9571   case Intrinsic::x86_xop_vpcomneud:
9572   case Intrinsic::x86_xop_vpcomneuq:
9573   case Intrinsic::x86_xop_vpcomfalseb:
9574   case Intrinsic::x86_xop_vpcomfalsew:
9575   case Intrinsic::x86_xop_vpcomfalsed:
9576   case Intrinsic::x86_xop_vpcomfalseq:
9577   case Intrinsic::x86_xop_vpcomfalseub:
9578   case Intrinsic::x86_xop_vpcomfalseuw:
9579   case Intrinsic::x86_xop_vpcomfalseud:
9580   case Intrinsic::x86_xop_vpcomfalseuq:
9581   case Intrinsic::x86_xop_vpcomtrueb:
9582   case Intrinsic::x86_xop_vpcomtruew:
9583   case Intrinsic::x86_xop_vpcomtrued:
9584   case Intrinsic::x86_xop_vpcomtrueq:
9585   case Intrinsic::x86_xop_vpcomtrueub:
9586   case Intrinsic::x86_xop_vpcomtrueuw:
9587   case Intrinsic::x86_xop_vpcomtrueud:
9588   case Intrinsic::x86_xop_vpcomtrueuq: {
9589     unsigned CC = 0;
9590     unsigned Opc = 0;
9591
9592     switch (IntNo) {
9593     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9594     case Intrinsic::x86_xop_vpcomltb:
9595     case Intrinsic::x86_xop_vpcomltw:
9596     case Intrinsic::x86_xop_vpcomltd:
9597     case Intrinsic::x86_xop_vpcomltq:
9598       CC = 0;
9599       Opc = X86ISD::VPCOM;
9600       break;
9601     case Intrinsic::x86_xop_vpcomltub:
9602     case Intrinsic::x86_xop_vpcomltuw:
9603     case Intrinsic::x86_xop_vpcomltud:
9604     case Intrinsic::x86_xop_vpcomltuq:
9605       CC = 0;
9606       Opc = X86ISD::VPCOMU;
9607       break;
9608     case Intrinsic::x86_xop_vpcomleb:
9609     case Intrinsic::x86_xop_vpcomlew:
9610     case Intrinsic::x86_xop_vpcomled:
9611     case Intrinsic::x86_xop_vpcomleq:
9612       CC = 1;
9613       Opc = X86ISD::VPCOM;
9614       break;
9615     case Intrinsic::x86_xop_vpcomleub:
9616     case Intrinsic::x86_xop_vpcomleuw:
9617     case Intrinsic::x86_xop_vpcomleud:
9618     case Intrinsic::x86_xop_vpcomleuq:
9619       CC = 1;
9620       Opc = X86ISD::VPCOMU;
9621       break;
9622     case Intrinsic::x86_xop_vpcomgtb:
9623     case Intrinsic::x86_xop_vpcomgtw:
9624     case Intrinsic::x86_xop_vpcomgtd:
9625     case Intrinsic::x86_xop_vpcomgtq:
9626       CC = 2;
9627       Opc = X86ISD::VPCOM;
9628       break;
9629     case Intrinsic::x86_xop_vpcomgtub:
9630     case Intrinsic::x86_xop_vpcomgtuw:
9631     case Intrinsic::x86_xop_vpcomgtud:
9632     case Intrinsic::x86_xop_vpcomgtuq:
9633       CC = 2;
9634       Opc = X86ISD::VPCOMU;
9635       break;
9636     case Intrinsic::x86_xop_vpcomgeb:
9637     case Intrinsic::x86_xop_vpcomgew:
9638     case Intrinsic::x86_xop_vpcomged:
9639     case Intrinsic::x86_xop_vpcomgeq:
9640       CC = 3;
9641       Opc = X86ISD::VPCOM;
9642       break;
9643     case Intrinsic::x86_xop_vpcomgeub:
9644     case Intrinsic::x86_xop_vpcomgeuw:
9645     case Intrinsic::x86_xop_vpcomgeud:
9646     case Intrinsic::x86_xop_vpcomgeuq:
9647       CC = 3;
9648       Opc = X86ISD::VPCOMU;
9649       break;
9650     case Intrinsic::x86_xop_vpcomeqb:
9651     case Intrinsic::x86_xop_vpcomeqw:
9652     case Intrinsic::x86_xop_vpcomeqd:
9653     case Intrinsic::x86_xop_vpcomeqq:
9654       CC = 4;
9655       Opc = X86ISD::VPCOM;
9656       break;
9657     case Intrinsic::x86_xop_vpcomequb:
9658     case Intrinsic::x86_xop_vpcomequw:
9659     case Intrinsic::x86_xop_vpcomequd:
9660     case Intrinsic::x86_xop_vpcomequq:
9661       CC = 4;
9662       Opc = X86ISD::VPCOMU;
9663       break;
9664     case Intrinsic::x86_xop_vpcomneb:
9665     case Intrinsic::x86_xop_vpcomnew:
9666     case Intrinsic::x86_xop_vpcomned:
9667     case Intrinsic::x86_xop_vpcomneq:
9668       CC = 5;
9669       Opc = X86ISD::VPCOM;
9670       break;
9671     case Intrinsic::x86_xop_vpcomneub:
9672     case Intrinsic::x86_xop_vpcomneuw:
9673     case Intrinsic::x86_xop_vpcomneud:
9674     case Intrinsic::x86_xop_vpcomneuq:
9675       CC = 5;
9676       Opc = X86ISD::VPCOMU;
9677       break;
9678     case Intrinsic::x86_xop_vpcomfalseb:
9679     case Intrinsic::x86_xop_vpcomfalsew:
9680     case Intrinsic::x86_xop_vpcomfalsed:
9681     case Intrinsic::x86_xop_vpcomfalseq:
9682       CC = 6;
9683       Opc = X86ISD::VPCOM;
9684       break;
9685     case Intrinsic::x86_xop_vpcomfalseub:
9686     case Intrinsic::x86_xop_vpcomfalseuw:
9687     case Intrinsic::x86_xop_vpcomfalseud:
9688     case Intrinsic::x86_xop_vpcomfalseuq:
9689       CC = 6;
9690       Opc = X86ISD::VPCOMU;
9691       break;
9692     case Intrinsic::x86_xop_vpcomtrueb:
9693     case Intrinsic::x86_xop_vpcomtruew:
9694     case Intrinsic::x86_xop_vpcomtrued:
9695     case Intrinsic::x86_xop_vpcomtrueq:
9696       CC = 7;
9697       Opc = X86ISD::VPCOM;
9698       break;
9699     case Intrinsic::x86_xop_vpcomtrueub:
9700     case Intrinsic::x86_xop_vpcomtrueuw:
9701     case Intrinsic::x86_xop_vpcomtrueud:
9702     case Intrinsic::x86_xop_vpcomtrueuq:
9703       CC = 7;
9704       Opc = X86ISD::VPCOMU;
9705       break;
9706     }
9707
9708     SDValue LHS = Op.getOperand(1);
9709     SDValue RHS = Op.getOperand(2);
9710     return DAG.getNode(Opc, dl, Op.getValueType(), LHS, RHS,
9711                        DAG.getConstant(CC, MVT::i8));
9712   }
9713
9714   // Arithmetic intrinsics.
9715   case Intrinsic::x86_sse2_pmulu_dq:
9716   case Intrinsic::x86_avx2_pmulu_dq:
9717     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9718                        Op.getOperand(1), Op.getOperand(2));
9719   case Intrinsic::x86_sse3_hadd_ps:
9720   case Intrinsic::x86_sse3_hadd_pd:
9721   case Intrinsic::x86_avx_hadd_ps_256:
9722   case Intrinsic::x86_avx_hadd_pd_256:
9723     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9724                        Op.getOperand(1), Op.getOperand(2));
9725   case Intrinsic::x86_sse3_hsub_ps:
9726   case Intrinsic::x86_sse3_hsub_pd:
9727   case Intrinsic::x86_avx_hsub_ps_256:
9728   case Intrinsic::x86_avx_hsub_pd_256:
9729     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9730                        Op.getOperand(1), Op.getOperand(2));
9731   case Intrinsic::x86_ssse3_phadd_w_128:
9732   case Intrinsic::x86_ssse3_phadd_d_128:
9733   case Intrinsic::x86_avx2_phadd_w:
9734   case Intrinsic::x86_avx2_phadd_d:
9735     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9736                        Op.getOperand(1), Op.getOperand(2));
9737   case Intrinsic::x86_ssse3_phsub_w_128:
9738   case Intrinsic::x86_ssse3_phsub_d_128:
9739   case Intrinsic::x86_avx2_phsub_w:
9740   case Intrinsic::x86_avx2_phsub_d:
9741     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9742                        Op.getOperand(1), Op.getOperand(2));
9743   case Intrinsic::x86_avx2_psllv_d:
9744   case Intrinsic::x86_avx2_psllv_q:
9745   case Intrinsic::x86_avx2_psllv_d_256:
9746   case Intrinsic::x86_avx2_psllv_q_256:
9747     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9748                       Op.getOperand(1), Op.getOperand(2));
9749   case Intrinsic::x86_avx2_psrlv_d:
9750   case Intrinsic::x86_avx2_psrlv_q:
9751   case Intrinsic::x86_avx2_psrlv_d_256:
9752   case Intrinsic::x86_avx2_psrlv_q_256:
9753     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9754                       Op.getOperand(1), Op.getOperand(2));
9755   case Intrinsic::x86_avx2_psrav_d:
9756   case Intrinsic::x86_avx2_psrav_d_256:
9757     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9758                       Op.getOperand(1), Op.getOperand(2));
9759   case Intrinsic::x86_ssse3_pshuf_b_128:
9760   case Intrinsic::x86_avx2_pshuf_b:
9761     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9762                        Op.getOperand(1), Op.getOperand(2));
9763   case Intrinsic::x86_ssse3_psign_b_128:
9764   case Intrinsic::x86_ssse3_psign_w_128:
9765   case Intrinsic::x86_ssse3_psign_d_128:
9766   case Intrinsic::x86_avx2_psign_b:
9767   case Intrinsic::x86_avx2_psign_w:
9768   case Intrinsic::x86_avx2_psign_d:
9769     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9770                        Op.getOperand(1), Op.getOperand(2));
9771   case Intrinsic::x86_sse41_insertps:
9772     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9773                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9774   case Intrinsic::x86_avx_vperm2f128_ps_256:
9775   case Intrinsic::x86_avx_vperm2f128_pd_256:
9776   case Intrinsic::x86_avx_vperm2f128_si_256:
9777   case Intrinsic::x86_avx2_vperm2i128:
9778     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9779                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9780   case Intrinsic::x86_avx2_permd:
9781   case Intrinsic::x86_avx2_permps:
9782     // Operands intentionally swapped. Mask is last operand to intrinsic,
9783     // but second operand for node/intruction.
9784     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9785                        Op.getOperand(2), Op.getOperand(1));
9786
9787   // ptest and testp intrinsics. The intrinsic these come from are designed to
9788   // return an integer value, not just an instruction so lower it to the ptest
9789   // or testp pattern and a setcc for the result.
9790   case Intrinsic::x86_sse41_ptestz:
9791   case Intrinsic::x86_sse41_ptestc:
9792   case Intrinsic::x86_sse41_ptestnzc:
9793   case Intrinsic::x86_avx_ptestz_256:
9794   case Intrinsic::x86_avx_ptestc_256:
9795   case Intrinsic::x86_avx_ptestnzc_256:
9796   case Intrinsic::x86_avx_vtestz_ps:
9797   case Intrinsic::x86_avx_vtestc_ps:
9798   case Intrinsic::x86_avx_vtestnzc_ps:
9799   case Intrinsic::x86_avx_vtestz_pd:
9800   case Intrinsic::x86_avx_vtestc_pd:
9801   case Intrinsic::x86_avx_vtestnzc_pd:
9802   case Intrinsic::x86_avx_vtestz_ps_256:
9803   case Intrinsic::x86_avx_vtestc_ps_256:
9804   case Intrinsic::x86_avx_vtestnzc_ps_256:
9805   case Intrinsic::x86_avx_vtestz_pd_256:
9806   case Intrinsic::x86_avx_vtestc_pd_256:
9807   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9808     bool IsTestPacked = false;
9809     unsigned X86CC = 0;
9810     switch (IntNo) {
9811     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9812     case Intrinsic::x86_avx_vtestz_ps:
9813     case Intrinsic::x86_avx_vtestz_pd:
9814     case Intrinsic::x86_avx_vtestz_ps_256:
9815     case Intrinsic::x86_avx_vtestz_pd_256:
9816       IsTestPacked = true; // Fallthrough
9817     case Intrinsic::x86_sse41_ptestz:
9818     case Intrinsic::x86_avx_ptestz_256:
9819       // ZF = 1
9820       X86CC = X86::COND_E;
9821       break;
9822     case Intrinsic::x86_avx_vtestc_ps:
9823     case Intrinsic::x86_avx_vtestc_pd:
9824     case Intrinsic::x86_avx_vtestc_ps_256:
9825     case Intrinsic::x86_avx_vtestc_pd_256:
9826       IsTestPacked = true; // Fallthrough
9827     case Intrinsic::x86_sse41_ptestc:
9828     case Intrinsic::x86_avx_ptestc_256:
9829       // CF = 1
9830       X86CC = X86::COND_B;
9831       break;
9832     case Intrinsic::x86_avx_vtestnzc_ps:
9833     case Intrinsic::x86_avx_vtestnzc_pd:
9834     case Intrinsic::x86_avx_vtestnzc_ps_256:
9835     case Intrinsic::x86_avx_vtestnzc_pd_256:
9836       IsTestPacked = true; // Fallthrough
9837     case Intrinsic::x86_sse41_ptestnzc:
9838     case Intrinsic::x86_avx_ptestnzc_256:
9839       // ZF and CF = 0
9840       X86CC = X86::COND_A;
9841       break;
9842     }
9843
9844     SDValue LHS = Op.getOperand(1);
9845     SDValue RHS = Op.getOperand(2);
9846     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9847     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9848     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9849     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9850     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9851   }
9852
9853   // SSE/AVX shift intrinsics
9854   case Intrinsic::x86_sse2_psll_w:
9855   case Intrinsic::x86_sse2_psll_d:
9856   case Intrinsic::x86_sse2_psll_q:
9857   case Intrinsic::x86_avx2_psll_w:
9858   case Intrinsic::x86_avx2_psll_d:
9859   case Intrinsic::x86_avx2_psll_q:
9860     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9861                        Op.getOperand(1), Op.getOperand(2));
9862   case Intrinsic::x86_sse2_psrl_w:
9863   case Intrinsic::x86_sse2_psrl_d:
9864   case Intrinsic::x86_sse2_psrl_q:
9865   case Intrinsic::x86_avx2_psrl_w:
9866   case Intrinsic::x86_avx2_psrl_d:
9867   case Intrinsic::x86_avx2_psrl_q:
9868     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9869                        Op.getOperand(1), Op.getOperand(2));
9870   case Intrinsic::x86_sse2_psra_w:
9871   case Intrinsic::x86_sse2_psra_d:
9872   case Intrinsic::x86_avx2_psra_w:
9873   case Intrinsic::x86_avx2_psra_d:
9874     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9875                        Op.getOperand(1), Op.getOperand(2));
9876   case Intrinsic::x86_sse2_pslli_w:
9877   case Intrinsic::x86_sse2_pslli_d:
9878   case Intrinsic::x86_sse2_pslli_q:
9879   case Intrinsic::x86_avx2_pslli_w:
9880   case Intrinsic::x86_avx2_pslli_d:
9881   case Intrinsic::x86_avx2_pslli_q:
9882     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9883                                Op.getOperand(1), Op.getOperand(2), DAG);
9884   case Intrinsic::x86_sse2_psrli_w:
9885   case Intrinsic::x86_sse2_psrli_d:
9886   case Intrinsic::x86_sse2_psrli_q:
9887   case Intrinsic::x86_avx2_psrli_w:
9888   case Intrinsic::x86_avx2_psrli_d:
9889   case Intrinsic::x86_avx2_psrli_q:
9890     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9891                                Op.getOperand(1), Op.getOperand(2), DAG);
9892   case Intrinsic::x86_sse2_psrai_w:
9893   case Intrinsic::x86_sse2_psrai_d:
9894   case Intrinsic::x86_avx2_psrai_w:
9895   case Intrinsic::x86_avx2_psrai_d:
9896     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9897                                Op.getOperand(1), Op.getOperand(2), DAG);
9898   // Fix vector shift instructions where the last operand is a non-immediate
9899   // i32 value.
9900   case Intrinsic::x86_mmx_pslli_w:
9901   case Intrinsic::x86_mmx_pslli_d:
9902   case Intrinsic::x86_mmx_pslli_q:
9903   case Intrinsic::x86_mmx_psrli_w:
9904   case Intrinsic::x86_mmx_psrli_d:
9905   case Intrinsic::x86_mmx_psrli_q:
9906   case Intrinsic::x86_mmx_psrai_w:
9907   case Intrinsic::x86_mmx_psrai_d: {
9908     SDValue ShAmt = Op.getOperand(2);
9909     if (isa<ConstantSDNode>(ShAmt))
9910       return SDValue();
9911
9912     unsigned NewIntNo = 0;
9913     switch (IntNo) {
9914     case Intrinsic::x86_mmx_pslli_w:
9915       NewIntNo = Intrinsic::x86_mmx_psll_w;
9916       break;
9917     case Intrinsic::x86_mmx_pslli_d:
9918       NewIntNo = Intrinsic::x86_mmx_psll_d;
9919       break;
9920     case Intrinsic::x86_mmx_pslli_q:
9921       NewIntNo = Intrinsic::x86_mmx_psll_q;
9922       break;
9923     case Intrinsic::x86_mmx_psrli_w:
9924       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9925       break;
9926     case Intrinsic::x86_mmx_psrli_d:
9927       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9928       break;
9929     case Intrinsic::x86_mmx_psrli_q:
9930       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9931       break;
9932     case Intrinsic::x86_mmx_psrai_w:
9933       NewIntNo = Intrinsic::x86_mmx_psra_w;
9934       break;
9935     case Intrinsic::x86_mmx_psrai_d:
9936       NewIntNo = Intrinsic::x86_mmx_psra_d;
9937       break;
9938     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9939     }
9940
9941     // The vector shift intrinsics with scalars uses 32b shift amounts but
9942     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9943     // to be zero.
9944     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9945                          DAG.getConstant(0, MVT::i32));
9946 // FIXME this must be lowered to get rid of the invalid type.
9947
9948     EVT VT = Op.getValueType();
9949     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9950     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9951                        DAG.getConstant(NewIntNo, MVT::i32),
9952                        Op.getOperand(1), ShAmt);
9953   }
9954   }
9955 }
9956
9957 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9958                                            SelectionDAG &DAG) const {
9959   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9960   MFI->setReturnAddressIsTaken(true);
9961
9962   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9963   DebugLoc dl = Op.getDebugLoc();
9964
9965   if (Depth > 0) {
9966     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9967     SDValue Offset =
9968       DAG.getConstant(TD->getPointerSize(),
9969                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9970     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9971                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9972                                    FrameAddr, Offset),
9973                        MachinePointerInfo(), false, false, false, 0);
9974   }
9975
9976   // Just load the return address.
9977   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9978   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9979                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9980 }
9981
9982 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9983   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9984   MFI->setFrameAddressIsTaken(true);
9985
9986   EVT VT = Op.getValueType();
9987   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9988   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9989   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9990   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9991   while (Depth--)
9992     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9993                             MachinePointerInfo(),
9994                             false, false, false, 0);
9995   return FrameAddr;
9996 }
9997
9998 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9999                                                      SelectionDAG &DAG) const {
10000   return DAG.getIntPtrConstant(2*TD->getPointerSize());
10001 }
10002
10003 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10004   MachineFunction &MF = DAG.getMachineFunction();
10005   SDValue Chain     = Op.getOperand(0);
10006   SDValue Offset    = Op.getOperand(1);
10007   SDValue Handler   = Op.getOperand(2);
10008   DebugLoc dl       = Op.getDebugLoc();
10009
10010   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10011                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10012                                      getPointerTy());
10013   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10014
10015   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10016                                   DAG.getIntPtrConstant(TD->getPointerSize()));
10017   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10018   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10019                        false, false, 0);
10020   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10021   MF.getRegInfo().addLiveOut(StoreAddrReg);
10022
10023   return DAG.getNode(X86ISD::EH_RETURN, dl,
10024                      MVT::Other,
10025                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10026 }
10027
10028 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10029                                                   SelectionDAG &DAG) const {
10030   return Op.getOperand(0);
10031 }
10032
10033 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10034                                                 SelectionDAG &DAG) const {
10035   SDValue Root = Op.getOperand(0);
10036   SDValue Trmp = Op.getOperand(1); // trampoline
10037   SDValue FPtr = Op.getOperand(2); // nested function
10038   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10039   DebugLoc dl  = Op.getDebugLoc();
10040
10041   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10042
10043   if (Subtarget->is64Bit()) {
10044     SDValue OutChains[6];
10045
10046     // Large code-model.
10047     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10048     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10049
10050     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10051     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10052
10053     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10054
10055     // Load the pointer to the nested function into R11.
10056     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10057     SDValue Addr = Trmp;
10058     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10059                                 Addr, MachinePointerInfo(TrmpAddr),
10060                                 false, false, 0);
10061
10062     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10063                        DAG.getConstant(2, MVT::i64));
10064     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10065                                 MachinePointerInfo(TrmpAddr, 2),
10066                                 false, false, 2);
10067
10068     // Load the 'nest' parameter value into R10.
10069     // R10 is specified in X86CallingConv.td
10070     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10071     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10072                        DAG.getConstant(10, MVT::i64));
10073     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10074                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10075                                 false, false, 0);
10076
10077     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10078                        DAG.getConstant(12, MVT::i64));
10079     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10080                                 MachinePointerInfo(TrmpAddr, 12),
10081                                 false, false, 2);
10082
10083     // Jump to the nested function.
10084     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10085     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10086                        DAG.getConstant(20, MVT::i64));
10087     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10088                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10089                                 false, false, 0);
10090
10091     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10092     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10093                        DAG.getConstant(22, MVT::i64));
10094     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10095                                 MachinePointerInfo(TrmpAddr, 22),
10096                                 false, false, 0);
10097
10098     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10099   } else {
10100     const Function *Func =
10101       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10102     CallingConv::ID CC = Func->getCallingConv();
10103     unsigned NestReg;
10104
10105     switch (CC) {
10106     default:
10107       llvm_unreachable("Unsupported calling convention");
10108     case CallingConv::C:
10109     case CallingConv::X86_StdCall: {
10110       // Pass 'nest' parameter in ECX.
10111       // Must be kept in sync with X86CallingConv.td
10112       NestReg = X86::ECX;
10113
10114       // Check that ECX wasn't needed by an 'inreg' parameter.
10115       FunctionType *FTy = Func->getFunctionType();
10116       const AttrListPtr &Attrs = Func->getAttributes();
10117
10118       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10119         unsigned InRegCount = 0;
10120         unsigned Idx = 1;
10121
10122         for (FunctionType::param_iterator I = FTy->param_begin(),
10123              E = FTy->param_end(); I != E; ++I, ++Idx)
10124           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10125             // FIXME: should only count parameters that are lowered to integers.
10126             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10127
10128         if (InRegCount > 2) {
10129           report_fatal_error("Nest register in use - reduce number of inreg"
10130                              " parameters!");
10131         }
10132       }
10133       break;
10134     }
10135     case CallingConv::X86_FastCall:
10136     case CallingConv::X86_ThisCall:
10137     case CallingConv::Fast:
10138       // Pass 'nest' parameter in EAX.
10139       // Must be kept in sync with X86CallingConv.td
10140       NestReg = X86::EAX;
10141       break;
10142     }
10143
10144     SDValue OutChains[4];
10145     SDValue Addr, Disp;
10146
10147     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10148                        DAG.getConstant(10, MVT::i32));
10149     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10150
10151     // This is storing the opcode for MOV32ri.
10152     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10153     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10154     OutChains[0] = DAG.getStore(Root, dl,
10155                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10156                                 Trmp, MachinePointerInfo(TrmpAddr),
10157                                 false, false, 0);
10158
10159     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10160                        DAG.getConstant(1, MVT::i32));
10161     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10162                                 MachinePointerInfo(TrmpAddr, 1),
10163                                 false, false, 1);
10164
10165     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10166     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10167                        DAG.getConstant(5, MVT::i32));
10168     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10169                                 MachinePointerInfo(TrmpAddr, 5),
10170                                 false, false, 1);
10171
10172     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10173                        DAG.getConstant(6, MVT::i32));
10174     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10175                                 MachinePointerInfo(TrmpAddr, 6),
10176                                 false, false, 1);
10177
10178     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10179   }
10180 }
10181
10182 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10183                                             SelectionDAG &DAG) const {
10184   /*
10185    The rounding mode is in bits 11:10 of FPSR, and has the following
10186    settings:
10187      00 Round to nearest
10188      01 Round to -inf
10189      10 Round to +inf
10190      11 Round to 0
10191
10192   FLT_ROUNDS, on the other hand, expects the following:
10193     -1 Undefined
10194      0 Round to 0
10195      1 Round to nearest
10196      2 Round to +inf
10197      3 Round to -inf
10198
10199   To perform the conversion, we do:
10200     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10201   */
10202
10203   MachineFunction &MF = DAG.getMachineFunction();
10204   const TargetMachine &TM = MF.getTarget();
10205   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10206   unsigned StackAlignment = TFI.getStackAlignment();
10207   EVT VT = Op.getValueType();
10208   DebugLoc DL = Op.getDebugLoc();
10209
10210   // Save FP Control Word to stack slot
10211   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10212   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10213
10214
10215   MachineMemOperand *MMO =
10216    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10217                            MachineMemOperand::MOStore, 2, 2);
10218
10219   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10220   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10221                                           DAG.getVTList(MVT::Other),
10222                                           Ops, 2, MVT::i16, MMO);
10223
10224   // Load FP Control Word from stack slot
10225   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10226                             MachinePointerInfo(), false, false, false, 0);
10227
10228   // Transform as necessary
10229   SDValue CWD1 =
10230     DAG.getNode(ISD::SRL, DL, MVT::i16,
10231                 DAG.getNode(ISD::AND, DL, MVT::i16,
10232                             CWD, DAG.getConstant(0x800, MVT::i16)),
10233                 DAG.getConstant(11, MVT::i8));
10234   SDValue CWD2 =
10235     DAG.getNode(ISD::SRL, DL, MVT::i16,
10236                 DAG.getNode(ISD::AND, DL, MVT::i16,
10237                             CWD, DAG.getConstant(0x400, MVT::i16)),
10238                 DAG.getConstant(9, MVT::i8));
10239
10240   SDValue RetVal =
10241     DAG.getNode(ISD::AND, DL, MVT::i16,
10242                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10243                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10244                             DAG.getConstant(1, MVT::i16)),
10245                 DAG.getConstant(3, MVT::i16));
10246
10247
10248   return DAG.getNode((VT.getSizeInBits() < 16 ?
10249                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10250 }
10251
10252 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10253   EVT VT = Op.getValueType();
10254   EVT OpVT = VT;
10255   unsigned NumBits = VT.getSizeInBits();
10256   DebugLoc dl = Op.getDebugLoc();
10257
10258   Op = Op.getOperand(0);
10259   if (VT == MVT::i8) {
10260     // Zero extend to i32 since there is not an i8 bsr.
10261     OpVT = MVT::i32;
10262     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10263   }
10264
10265   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10266   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10267   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10268
10269   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10270   SDValue Ops[] = {
10271     Op,
10272     DAG.getConstant(NumBits+NumBits-1, OpVT),
10273     DAG.getConstant(X86::COND_E, MVT::i8),
10274     Op.getValue(1)
10275   };
10276   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10277
10278   // Finally xor with NumBits-1.
10279   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10280
10281   if (VT == MVT::i8)
10282     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10283   return Op;
10284 }
10285
10286 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10287                                                 SelectionDAG &DAG) const {
10288   EVT VT = Op.getValueType();
10289   EVT OpVT = VT;
10290   unsigned NumBits = VT.getSizeInBits();
10291   DebugLoc dl = Op.getDebugLoc();
10292
10293   Op = Op.getOperand(0);
10294   if (VT == MVT::i8) {
10295     // Zero extend to i32 since there is not an i8 bsr.
10296     OpVT = MVT::i32;
10297     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10298   }
10299
10300   // Issue a bsr (scan bits in reverse).
10301   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10302   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10303
10304   // And xor with NumBits-1.
10305   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10306
10307   if (VT == MVT::i8)
10308     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10309   return Op;
10310 }
10311
10312 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10313   EVT VT = Op.getValueType();
10314   unsigned NumBits = VT.getSizeInBits();
10315   DebugLoc dl = Op.getDebugLoc();
10316   Op = Op.getOperand(0);
10317
10318   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10319   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10320   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10321
10322   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10323   SDValue Ops[] = {
10324     Op,
10325     DAG.getConstant(NumBits, VT),
10326     DAG.getConstant(X86::COND_E, MVT::i8),
10327     Op.getValue(1)
10328   };
10329   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10330 }
10331
10332 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10333 // ones, and then concatenate the result back.
10334 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10335   EVT VT = Op.getValueType();
10336
10337   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10338          "Unsupported value type for operation");
10339
10340   unsigned NumElems = VT.getVectorNumElements();
10341   DebugLoc dl = Op.getDebugLoc();
10342
10343   // Extract the LHS vectors
10344   SDValue LHS = Op.getOperand(0);
10345   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10346   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10347
10348   // Extract the RHS vectors
10349   SDValue RHS = Op.getOperand(1);
10350   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10351   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10352
10353   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10354   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10355
10356   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10357                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10358                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10359 }
10360
10361 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10362   assert(Op.getValueType().getSizeInBits() == 256 &&
10363          Op.getValueType().isInteger() &&
10364          "Only handle AVX 256-bit vector integer operation");
10365   return Lower256IntArith(Op, DAG);
10366 }
10367
10368 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10369   assert(Op.getValueType().getSizeInBits() == 256 &&
10370          Op.getValueType().isInteger() &&
10371          "Only handle AVX 256-bit vector integer operation");
10372   return Lower256IntArith(Op, DAG);
10373 }
10374
10375 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10376   EVT VT = Op.getValueType();
10377
10378   // Decompose 256-bit ops into smaller 128-bit ops.
10379   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10380     return Lower256IntArith(Op, DAG);
10381
10382   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10383          "Only know how to lower V2I64/V4I64 multiply");
10384
10385   DebugLoc dl = Op.getDebugLoc();
10386
10387   //  Ahi = psrlqi(a, 32);
10388   //  Bhi = psrlqi(b, 32);
10389   //
10390   //  AloBlo = pmuludq(a, b);
10391   //  AloBhi = pmuludq(a, Bhi);
10392   //  AhiBlo = pmuludq(Ahi, b);
10393
10394   //  AloBhi = psllqi(AloBhi, 32);
10395   //  AhiBlo = psllqi(AhiBlo, 32);
10396   //  return AloBlo + AloBhi + AhiBlo;
10397
10398   SDValue A = Op.getOperand(0);
10399   SDValue B = Op.getOperand(1);
10400
10401   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10402
10403   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10404   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10405
10406   // Bit cast to 32-bit vectors for MULUDQ
10407   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10408   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10409   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10410   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10411   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10412
10413   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10414   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10415   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10416
10417   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10418   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10419
10420   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10421   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10422 }
10423
10424 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10425
10426   EVT VT = Op.getValueType();
10427   DebugLoc dl = Op.getDebugLoc();
10428   SDValue R = Op.getOperand(0);
10429   SDValue Amt = Op.getOperand(1);
10430   LLVMContext *Context = DAG.getContext();
10431
10432   if (!Subtarget->hasSSE2())
10433     return SDValue();
10434
10435   // Optimize shl/srl/sra with constant shift amount.
10436   if (isSplatVector(Amt.getNode())) {
10437     SDValue SclrAmt = Amt->getOperand(0);
10438     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10439       uint64_t ShiftAmt = C->getZExtValue();
10440
10441       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10442           (Subtarget->hasAVX2() &&
10443            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10444         if (Op.getOpcode() == ISD::SHL)
10445           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10446                              DAG.getConstant(ShiftAmt, MVT::i32));
10447         if (Op.getOpcode() == ISD::SRL)
10448           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10449                              DAG.getConstant(ShiftAmt, MVT::i32));
10450         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10451           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10452                              DAG.getConstant(ShiftAmt, MVT::i32));
10453       }
10454
10455       if (VT == MVT::v16i8) {
10456         if (Op.getOpcode() == ISD::SHL) {
10457           // Make a large shift.
10458           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10459                                     DAG.getConstant(ShiftAmt, MVT::i32));
10460           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10461           // Zero out the rightmost bits.
10462           SmallVector<SDValue, 16> V(16,
10463                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10464                                                      MVT::i8));
10465           return DAG.getNode(ISD::AND, dl, VT, SHL,
10466                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10467         }
10468         if (Op.getOpcode() == ISD::SRL) {
10469           // Make a large shift.
10470           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10471                                     DAG.getConstant(ShiftAmt, MVT::i32));
10472           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10473           // Zero out the leftmost bits.
10474           SmallVector<SDValue, 16> V(16,
10475                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10476                                                      MVT::i8));
10477           return DAG.getNode(ISD::AND, dl, VT, SRL,
10478                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10479         }
10480         if (Op.getOpcode() == ISD::SRA) {
10481           if (ShiftAmt == 7) {
10482             // R s>> 7  ===  R s< 0
10483             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10484             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10485           }
10486
10487           // R s>> a === ((R u>> a) ^ m) - m
10488           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10489           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10490                                                          MVT::i8));
10491           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10492           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10493           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10494           return Res;
10495         }
10496         llvm_unreachable("Unknown shift opcode.");
10497       }
10498
10499       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10500         if (Op.getOpcode() == ISD::SHL) {
10501           // Make a large shift.
10502           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10503                                     DAG.getConstant(ShiftAmt, MVT::i32));
10504           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10505           // Zero out the rightmost bits.
10506           SmallVector<SDValue, 32> V(32,
10507                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10508                                                      MVT::i8));
10509           return DAG.getNode(ISD::AND, dl, VT, SHL,
10510                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10511         }
10512         if (Op.getOpcode() == ISD::SRL) {
10513           // Make a large shift.
10514           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10515                                     DAG.getConstant(ShiftAmt, MVT::i32));
10516           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10517           // Zero out the leftmost bits.
10518           SmallVector<SDValue, 32> V(32,
10519                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10520                                                      MVT::i8));
10521           return DAG.getNode(ISD::AND, dl, VT, SRL,
10522                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10523         }
10524         if (Op.getOpcode() == ISD::SRA) {
10525           if (ShiftAmt == 7) {
10526             // R s>> 7  ===  R s< 0
10527             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10528             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10529           }
10530
10531           // R s>> a === ((R u>> a) ^ m) - m
10532           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10533           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10534                                                          MVT::i8));
10535           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10536           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10537           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10538           return Res;
10539         }
10540         llvm_unreachable("Unknown shift opcode.");
10541       }
10542     }
10543   }
10544
10545   // Lower SHL with variable shift amount.
10546   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10547     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10548                      DAG.getConstant(23, MVT::i32));
10549
10550     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10551     Constant *C = ConstantDataVector::get(*Context, CV);
10552     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10553     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10554                                  MachinePointerInfo::getConstantPool(),
10555                                  false, false, false, 16);
10556
10557     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10558     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10559     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10560     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10561   }
10562   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10563     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10564
10565     // a = a << 5;
10566     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10567                      DAG.getConstant(5, MVT::i32));
10568     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10569
10570     // Turn 'a' into a mask suitable for VSELECT
10571     SDValue VSelM = DAG.getConstant(0x80, VT);
10572     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10573     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10574
10575     SDValue CM1 = DAG.getConstant(0x0f, VT);
10576     SDValue CM2 = DAG.getConstant(0x3f, VT);
10577
10578     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10579     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10580     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10581                             DAG.getConstant(4, MVT::i32), DAG);
10582     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10583     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10584
10585     // a += a
10586     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10587     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10588     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10589
10590     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10591     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10592     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10593                             DAG.getConstant(2, MVT::i32), DAG);
10594     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10595     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10596
10597     // a += a
10598     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10599     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10600     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10601
10602     // return VSELECT(r, r+r, a);
10603     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10604                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10605     return R;
10606   }
10607
10608   // Decompose 256-bit shifts into smaller 128-bit shifts.
10609   if (VT.getSizeInBits() == 256) {
10610     unsigned NumElems = VT.getVectorNumElements();
10611     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10612     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10613
10614     // Extract the two vectors
10615     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10616     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10617
10618     // Recreate the shift amount vectors
10619     SDValue Amt1, Amt2;
10620     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10621       // Constant shift amount
10622       SmallVector<SDValue, 4> Amt1Csts;
10623       SmallVector<SDValue, 4> Amt2Csts;
10624       for (unsigned i = 0; i != NumElems/2; ++i)
10625         Amt1Csts.push_back(Amt->getOperand(i));
10626       for (unsigned i = NumElems/2; i != NumElems; ++i)
10627         Amt2Csts.push_back(Amt->getOperand(i));
10628
10629       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10630                                  &Amt1Csts[0], NumElems/2);
10631       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10632                                  &Amt2Csts[0], NumElems/2);
10633     } else {
10634       // Variable shift amount
10635       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10636       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10637     }
10638
10639     // Issue new vector shifts for the smaller types
10640     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10641     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10642
10643     // Concatenate the result back
10644     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10645   }
10646
10647   return SDValue();
10648 }
10649
10650 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10651   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10652   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10653   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10654   // has only one use.
10655   SDNode *N = Op.getNode();
10656   SDValue LHS = N->getOperand(0);
10657   SDValue RHS = N->getOperand(1);
10658   unsigned BaseOp = 0;
10659   unsigned Cond = 0;
10660   DebugLoc DL = Op.getDebugLoc();
10661   switch (Op.getOpcode()) {
10662   default: llvm_unreachable("Unknown ovf instruction!");
10663   case ISD::SADDO:
10664     // A subtract of one will be selected as a INC. Note that INC doesn't
10665     // set CF, so we can't do this for UADDO.
10666     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10667       if (C->isOne()) {
10668         BaseOp = X86ISD::INC;
10669         Cond = X86::COND_O;
10670         break;
10671       }
10672     BaseOp = X86ISD::ADD;
10673     Cond = X86::COND_O;
10674     break;
10675   case ISD::UADDO:
10676     BaseOp = X86ISD::ADD;
10677     Cond = X86::COND_B;
10678     break;
10679   case ISD::SSUBO:
10680     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10681     // set CF, so we can't do this for USUBO.
10682     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10683       if (C->isOne()) {
10684         BaseOp = X86ISD::DEC;
10685         Cond = X86::COND_O;
10686         break;
10687       }
10688     BaseOp = X86ISD::SUB;
10689     Cond = X86::COND_O;
10690     break;
10691   case ISD::USUBO:
10692     BaseOp = X86ISD::SUB;
10693     Cond = X86::COND_B;
10694     break;
10695   case ISD::SMULO:
10696     BaseOp = X86ISD::SMUL;
10697     Cond = X86::COND_O;
10698     break;
10699   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10700     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10701                                  MVT::i32);
10702     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10703
10704     SDValue SetCC =
10705       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10706                   DAG.getConstant(X86::COND_O, MVT::i32),
10707                   SDValue(Sum.getNode(), 2));
10708
10709     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10710   }
10711   }
10712
10713   // Also sets EFLAGS.
10714   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10715   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10716
10717   SDValue SetCC =
10718     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10719                 DAG.getConstant(Cond, MVT::i32),
10720                 SDValue(Sum.getNode(), 1));
10721
10722   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10723 }
10724
10725 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10726                                                   SelectionDAG &DAG) const {
10727   DebugLoc dl = Op.getDebugLoc();
10728   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10729   EVT VT = Op.getValueType();
10730
10731   if (!Subtarget->hasSSE2() || !VT.isVector())
10732     return SDValue();
10733
10734   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10735                       ExtraVT.getScalarType().getSizeInBits();
10736   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10737
10738   switch (VT.getSimpleVT().SimpleTy) {
10739     default: return SDValue();
10740     case MVT::v8i32:
10741     case MVT::v16i16:
10742       if (!Subtarget->hasAVX())
10743         return SDValue();
10744       if (!Subtarget->hasAVX2()) {
10745         // needs to be split
10746         unsigned NumElems = VT.getVectorNumElements();
10747
10748         // Extract the LHS vectors
10749         SDValue LHS = Op.getOperand(0);
10750         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10751         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10752
10753         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10754         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10755
10756         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10757         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10758         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10759                                    ExtraNumElems/2);
10760         SDValue Extra = DAG.getValueType(ExtraVT);
10761
10762         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10763         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10764
10765         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10766       }
10767       // fall through
10768     case MVT::v4i32:
10769     case MVT::v8i16: {
10770       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10771                                          Op.getOperand(0), ShAmt, DAG);
10772       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10773     }
10774   }
10775 }
10776
10777
10778 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10779   DebugLoc dl = Op.getDebugLoc();
10780
10781   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10782   // There isn't any reason to disable it if the target processor supports it.
10783   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10784     SDValue Chain = Op.getOperand(0);
10785     SDValue Zero = DAG.getConstant(0, MVT::i32);
10786     SDValue Ops[] = {
10787       DAG.getRegister(X86::ESP, MVT::i32), // Base
10788       DAG.getTargetConstant(1, MVT::i8),   // Scale
10789       DAG.getRegister(0, MVT::i32),        // Index
10790       DAG.getTargetConstant(0, MVT::i32),  // Disp
10791       DAG.getRegister(0, MVT::i32),        // Segment.
10792       Zero,
10793       Chain
10794     };
10795     SDNode *Res =
10796       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10797                           array_lengthof(Ops));
10798     return SDValue(Res, 0);
10799   }
10800
10801   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10802   if (!isDev)
10803     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10804
10805   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10806   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10807   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10808   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10809
10810   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10811   if (!Op1 && !Op2 && !Op3 && Op4)
10812     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10813
10814   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10815   if (Op1 && !Op2 && !Op3 && !Op4)
10816     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10817
10818   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10819   //           (MFENCE)>;
10820   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10821 }
10822
10823 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10824                                              SelectionDAG &DAG) const {
10825   DebugLoc dl = Op.getDebugLoc();
10826   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10827     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10828   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10829     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10830
10831   // The only fence that needs an instruction is a sequentially-consistent
10832   // cross-thread fence.
10833   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10834     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10835     // no-sse2). There isn't any reason to disable it if the target processor
10836     // supports it.
10837     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10838       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10839
10840     SDValue Chain = Op.getOperand(0);
10841     SDValue Zero = DAG.getConstant(0, MVT::i32);
10842     SDValue Ops[] = {
10843       DAG.getRegister(X86::ESP, MVT::i32), // Base
10844       DAG.getTargetConstant(1, MVT::i8),   // Scale
10845       DAG.getRegister(0, MVT::i32),        // Index
10846       DAG.getTargetConstant(0, MVT::i32),  // Disp
10847       DAG.getRegister(0, MVT::i32),        // Segment.
10848       Zero,
10849       Chain
10850     };
10851     SDNode *Res =
10852       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10853                          array_lengthof(Ops));
10854     return SDValue(Res, 0);
10855   }
10856
10857   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10858   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10859 }
10860
10861
10862 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10863   EVT T = Op.getValueType();
10864   DebugLoc DL = Op.getDebugLoc();
10865   unsigned Reg = 0;
10866   unsigned size = 0;
10867   switch(T.getSimpleVT().SimpleTy) {
10868   default: llvm_unreachable("Invalid value type!");
10869   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10870   case MVT::i16: Reg = X86::AX;  size = 2; break;
10871   case MVT::i32: Reg = X86::EAX; size = 4; break;
10872   case MVT::i64:
10873     assert(Subtarget->is64Bit() && "Node not type legal!");
10874     Reg = X86::RAX; size = 8;
10875     break;
10876   }
10877   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10878                                     Op.getOperand(2), SDValue());
10879   SDValue Ops[] = { cpIn.getValue(0),
10880                     Op.getOperand(1),
10881                     Op.getOperand(3),
10882                     DAG.getTargetConstant(size, MVT::i8),
10883                     cpIn.getValue(1) };
10884   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10885   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10886   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10887                                            Ops, 5, T, MMO);
10888   SDValue cpOut =
10889     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10890   return cpOut;
10891 }
10892
10893 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10894                                                  SelectionDAG &DAG) const {
10895   assert(Subtarget->is64Bit() && "Result not type legalized?");
10896   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10897   SDValue TheChain = Op.getOperand(0);
10898   DebugLoc dl = Op.getDebugLoc();
10899   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10900   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10901   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10902                                    rax.getValue(2));
10903   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10904                             DAG.getConstant(32, MVT::i8));
10905   SDValue Ops[] = {
10906     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10907     rdx.getValue(1)
10908   };
10909   return DAG.getMergeValues(Ops, 2, dl);
10910 }
10911
10912 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10913                                             SelectionDAG &DAG) const {
10914   EVT SrcVT = Op.getOperand(0).getValueType();
10915   EVT DstVT = Op.getValueType();
10916   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10917          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10918   assert((DstVT == MVT::i64 ||
10919           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10920          "Unexpected custom BITCAST");
10921   // i64 <=> MMX conversions are Legal.
10922   if (SrcVT==MVT::i64 && DstVT.isVector())
10923     return Op;
10924   if (DstVT==MVT::i64 && SrcVT.isVector())
10925     return Op;
10926   // MMX <=> MMX conversions are Legal.
10927   if (SrcVT.isVector() && DstVT.isVector())
10928     return Op;
10929   // All other conversions need to be expanded.
10930   return SDValue();
10931 }
10932
10933 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10934   SDNode *Node = Op.getNode();
10935   DebugLoc dl = Node->getDebugLoc();
10936   EVT T = Node->getValueType(0);
10937   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10938                               DAG.getConstant(0, T), Node->getOperand(2));
10939   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10940                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10941                        Node->getOperand(0),
10942                        Node->getOperand(1), negOp,
10943                        cast<AtomicSDNode>(Node)->getSrcValue(),
10944                        cast<AtomicSDNode>(Node)->getAlignment(),
10945                        cast<AtomicSDNode>(Node)->getOrdering(),
10946                        cast<AtomicSDNode>(Node)->getSynchScope());
10947 }
10948
10949 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10950   SDNode *Node = Op.getNode();
10951   DebugLoc dl = Node->getDebugLoc();
10952   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10953
10954   // Convert seq_cst store -> xchg
10955   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10956   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10957   //        (The only way to get a 16-byte store is cmpxchg16b)
10958   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10959   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10960       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10961     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10962                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10963                                  Node->getOperand(0),
10964                                  Node->getOperand(1), Node->getOperand(2),
10965                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10966                                  cast<AtomicSDNode>(Node)->getOrdering(),
10967                                  cast<AtomicSDNode>(Node)->getSynchScope());
10968     return Swap.getValue(1);
10969   }
10970   // Other atomic stores have a simple pattern.
10971   return Op;
10972 }
10973
10974 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10975   EVT VT = Op.getNode()->getValueType(0);
10976
10977   // Let legalize expand this if it isn't a legal type yet.
10978   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10979     return SDValue();
10980
10981   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10982
10983   unsigned Opc;
10984   bool ExtraOp = false;
10985   switch (Op.getOpcode()) {
10986   default: llvm_unreachable("Invalid code");
10987   case ISD::ADDC: Opc = X86ISD::ADD; break;
10988   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10989   case ISD::SUBC: Opc = X86ISD::SUB; break;
10990   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10991   }
10992
10993   if (!ExtraOp)
10994     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10995                        Op.getOperand(1));
10996   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10997                      Op.getOperand(1), Op.getOperand(2));
10998 }
10999
11000 /// LowerOperation - Provide custom lowering hooks for some operations.
11001 ///
11002 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11003   switch (Op.getOpcode()) {
11004   default: llvm_unreachable("Should not custom lower this!");
11005   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11006   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
11007   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
11008   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
11009   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11010   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11011   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11012   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11013   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11014   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11015   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11016   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
11017   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
11018   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11019   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11020   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11021   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11022   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11023   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11024   case ISD::SHL_PARTS:
11025   case ISD::SRA_PARTS:
11026   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11027   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11028   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11029   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11030   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11031   case ISD::FABS:               return LowerFABS(Op, DAG);
11032   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11033   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11034   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11035   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11036   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11037   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11038   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11039   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11040   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11041   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11042   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11043   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11044   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11045   case ISD::FRAME_TO_ARGS_OFFSET:
11046                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11047   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11048   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11049   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11050   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11051   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11052   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11053   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11054   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11055   case ISD::MUL:                return LowerMUL(Op, DAG);
11056   case ISD::SRA:
11057   case ISD::SRL:
11058   case ISD::SHL:                return LowerShift(Op, DAG);
11059   case ISD::SADDO:
11060   case ISD::UADDO:
11061   case ISD::SSUBO:
11062   case ISD::USUBO:
11063   case ISD::SMULO:
11064   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11065   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
11066   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11067   case ISD::ADDC:
11068   case ISD::ADDE:
11069   case ISD::SUBC:
11070   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11071   case ISD::ADD:                return LowerADD(Op, DAG);
11072   case ISD::SUB:                return LowerSUB(Op, DAG);
11073   }
11074 }
11075
11076 static void ReplaceATOMIC_LOAD(SDNode *Node,
11077                                   SmallVectorImpl<SDValue> &Results,
11078                                   SelectionDAG &DAG) {
11079   DebugLoc dl = Node->getDebugLoc();
11080   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11081
11082   // Convert wide load -> cmpxchg8b/cmpxchg16b
11083   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11084   //        (The only way to get a 16-byte load is cmpxchg16b)
11085   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11086   SDValue Zero = DAG.getConstant(0, VT);
11087   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11088                                Node->getOperand(0),
11089                                Node->getOperand(1), Zero, Zero,
11090                                cast<AtomicSDNode>(Node)->getMemOperand(),
11091                                cast<AtomicSDNode>(Node)->getOrdering(),
11092                                cast<AtomicSDNode>(Node)->getSynchScope());
11093   Results.push_back(Swap.getValue(0));
11094   Results.push_back(Swap.getValue(1));
11095 }
11096
11097 void X86TargetLowering::
11098 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11099                         SelectionDAG &DAG, unsigned NewOp) const {
11100   DebugLoc dl = Node->getDebugLoc();
11101   assert (Node->getValueType(0) == MVT::i64 &&
11102           "Only know how to expand i64 atomics");
11103
11104   SDValue Chain = Node->getOperand(0);
11105   SDValue In1 = Node->getOperand(1);
11106   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11107                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11108   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11109                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11110   SDValue Ops[] = { Chain, In1, In2L, In2H };
11111   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11112   SDValue Result =
11113     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11114                             cast<MemSDNode>(Node)->getMemOperand());
11115   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11116   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11117   Results.push_back(Result.getValue(2));
11118 }
11119
11120 /// ReplaceNodeResults - Replace a node with an illegal result type
11121 /// with a new node built out of custom code.
11122 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11123                                            SmallVectorImpl<SDValue>&Results,
11124                                            SelectionDAG &DAG) const {
11125   DebugLoc dl = N->getDebugLoc();
11126   switch (N->getOpcode()) {
11127   default:
11128     llvm_unreachable("Do not know how to custom type legalize this operation!");
11129   case ISD::SIGN_EXTEND_INREG:
11130   case ISD::ADDC:
11131   case ISD::ADDE:
11132   case ISD::SUBC:
11133   case ISD::SUBE:
11134     // We don't want to expand or promote these.
11135     return;
11136   case ISD::FP_TO_SINT:
11137   case ISD::FP_TO_UINT: {
11138     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11139
11140     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11141       return;
11142
11143     std::pair<SDValue,SDValue> Vals =
11144         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11145     SDValue FIST = Vals.first, StackSlot = Vals.second;
11146     if (FIST.getNode() != 0) {
11147       EVT VT = N->getValueType(0);
11148       // Return a load from the stack slot.
11149       if (StackSlot.getNode() != 0)
11150         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11151                                       MachinePointerInfo(),
11152                                       false, false, false, 0));
11153       else
11154         Results.push_back(FIST);
11155     }
11156     return;
11157   }
11158   case ISD::READCYCLECOUNTER: {
11159     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11160     SDValue TheChain = N->getOperand(0);
11161     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11162     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11163                                      rd.getValue(1));
11164     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11165                                      eax.getValue(2));
11166     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11167     SDValue Ops[] = { eax, edx };
11168     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11169     Results.push_back(edx.getValue(1));
11170     return;
11171   }
11172   case ISD::ATOMIC_CMP_SWAP: {
11173     EVT T = N->getValueType(0);
11174     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11175     bool Regs64bit = T == MVT::i128;
11176     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11177     SDValue cpInL, cpInH;
11178     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11179                         DAG.getConstant(0, HalfT));
11180     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11181                         DAG.getConstant(1, HalfT));
11182     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11183                              Regs64bit ? X86::RAX : X86::EAX,
11184                              cpInL, SDValue());
11185     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11186                              Regs64bit ? X86::RDX : X86::EDX,
11187                              cpInH, cpInL.getValue(1));
11188     SDValue swapInL, swapInH;
11189     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11190                           DAG.getConstant(0, HalfT));
11191     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11192                           DAG.getConstant(1, HalfT));
11193     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11194                                Regs64bit ? X86::RBX : X86::EBX,
11195                                swapInL, cpInH.getValue(1));
11196     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11197                                Regs64bit ? X86::RCX : X86::ECX, 
11198                                swapInH, swapInL.getValue(1));
11199     SDValue Ops[] = { swapInH.getValue(0),
11200                       N->getOperand(1),
11201                       swapInH.getValue(1) };
11202     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11203     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11204     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11205                                   X86ISD::LCMPXCHG8_DAG;
11206     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11207                                              Ops, 3, T, MMO);
11208     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11209                                         Regs64bit ? X86::RAX : X86::EAX,
11210                                         HalfT, Result.getValue(1));
11211     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11212                                         Regs64bit ? X86::RDX : X86::EDX,
11213                                         HalfT, cpOutL.getValue(2));
11214     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11215     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11216     Results.push_back(cpOutH.getValue(1));
11217     return;
11218   }
11219   case ISD::ATOMIC_LOAD_ADD:
11220     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11221     return;
11222   case ISD::ATOMIC_LOAD_AND:
11223     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11224     return;
11225   case ISD::ATOMIC_LOAD_NAND:
11226     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11227     return;
11228   case ISD::ATOMIC_LOAD_OR:
11229     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11230     return;
11231   case ISD::ATOMIC_LOAD_SUB:
11232     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11233     return;
11234   case ISD::ATOMIC_LOAD_XOR:
11235     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11236     return;
11237   case ISD::ATOMIC_SWAP:
11238     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11239     return;
11240   case ISD::ATOMIC_LOAD:
11241     ReplaceATOMIC_LOAD(N, Results, DAG);
11242   }
11243 }
11244
11245 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11246   switch (Opcode) {
11247   default: return NULL;
11248   case X86ISD::BSF:                return "X86ISD::BSF";
11249   case X86ISD::BSR:                return "X86ISD::BSR";
11250   case X86ISD::SHLD:               return "X86ISD::SHLD";
11251   case X86ISD::SHRD:               return "X86ISD::SHRD";
11252   case X86ISD::FAND:               return "X86ISD::FAND";
11253   case X86ISD::FOR:                return "X86ISD::FOR";
11254   case X86ISD::FXOR:               return "X86ISD::FXOR";
11255   case X86ISD::FSRL:               return "X86ISD::FSRL";
11256   case X86ISD::FILD:               return "X86ISD::FILD";
11257   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11258   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11259   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11260   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11261   case X86ISD::FLD:                return "X86ISD::FLD";
11262   case X86ISD::FST:                return "X86ISD::FST";
11263   case X86ISD::CALL:               return "X86ISD::CALL";
11264   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11265   case X86ISD::BT:                 return "X86ISD::BT";
11266   case X86ISD::CMP:                return "X86ISD::CMP";
11267   case X86ISD::COMI:               return "X86ISD::COMI";
11268   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11269   case X86ISD::SETCC:              return "X86ISD::SETCC";
11270   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11271   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11272   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11273   case X86ISD::CMOV:               return "X86ISD::CMOV";
11274   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11275   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11276   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11277   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11278   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11279   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11280   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11281   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11282   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11283   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11284   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11285   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11286   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11287   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11288   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11289   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11290   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11291   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11292   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11293   case X86ISD::HADD:               return "X86ISD::HADD";
11294   case X86ISD::HSUB:               return "X86ISD::HSUB";
11295   case X86ISD::FHADD:              return "X86ISD::FHADD";
11296   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11297   case X86ISD::FMAX:               return "X86ISD::FMAX";
11298   case X86ISD::FMIN:               return "X86ISD::FMIN";
11299   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11300   case X86ISD::FRCP:               return "X86ISD::FRCP";
11301   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11302   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11303   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11304   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11305   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11306   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11307   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11308   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11309   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11310   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11311   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11312   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11313   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11314   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11315   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11316   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11317   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11318   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11319   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11320   case X86ISD::VSHL:               return "X86ISD::VSHL";
11321   case X86ISD::VSRL:               return "X86ISD::VSRL";
11322   case X86ISD::VSRA:               return "X86ISD::VSRA";
11323   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11324   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11325   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11326   case X86ISD::CMPP:               return "X86ISD::CMPP";
11327   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11328   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11329   case X86ISD::ADD:                return "X86ISD::ADD";
11330   case X86ISD::SUB:                return "X86ISD::SUB";
11331   case X86ISD::ADC:                return "X86ISD::ADC";
11332   case X86ISD::SBB:                return "X86ISD::SBB";
11333   case X86ISD::SMUL:               return "X86ISD::SMUL";
11334   case X86ISD::UMUL:               return "X86ISD::UMUL";
11335   case X86ISD::INC:                return "X86ISD::INC";
11336   case X86ISD::DEC:                return "X86ISD::DEC";
11337   case X86ISD::OR:                 return "X86ISD::OR";
11338   case X86ISD::XOR:                return "X86ISD::XOR";
11339   case X86ISD::AND:                return "X86ISD::AND";
11340   case X86ISD::ANDN:               return "X86ISD::ANDN";
11341   case X86ISD::BLSI:               return "X86ISD::BLSI";
11342   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11343   case X86ISD::BLSR:               return "X86ISD::BLSR";
11344   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11345   case X86ISD::PTEST:              return "X86ISD::PTEST";
11346   case X86ISD::TESTP:              return "X86ISD::TESTP";
11347   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11348   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11349   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11350   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11351   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11352   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11353   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11354   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11355   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11356   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11357   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11358   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11359   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11360   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11361   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11362   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11363   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11364   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11365   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11366   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11367   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11368   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11369   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11370   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11371   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11372   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11373   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11374   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11375   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11376   case X86ISD::SAHF:               return "X86ISD::SAHF";
11377   }
11378 }
11379
11380 // isLegalAddressingMode - Return true if the addressing mode represented
11381 // by AM is legal for this target, for a load/store of the specified type.
11382 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11383                                               Type *Ty) const {
11384   // X86 supports extremely general addressing modes.
11385   CodeModel::Model M = getTargetMachine().getCodeModel();
11386   Reloc::Model R = getTargetMachine().getRelocationModel();
11387
11388   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11389   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11390     return false;
11391
11392   if (AM.BaseGV) {
11393     unsigned GVFlags =
11394       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11395
11396     // If a reference to this global requires an extra load, we can't fold it.
11397     if (isGlobalStubReference(GVFlags))
11398       return false;
11399
11400     // If BaseGV requires a register for the PIC base, we cannot also have a
11401     // BaseReg specified.
11402     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11403       return false;
11404
11405     // If lower 4G is not available, then we must use rip-relative addressing.
11406     if ((M != CodeModel::Small || R != Reloc::Static) &&
11407         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11408       return false;
11409   }
11410
11411   switch (AM.Scale) {
11412   case 0:
11413   case 1:
11414   case 2:
11415   case 4:
11416   case 8:
11417     // These scales always work.
11418     break;
11419   case 3:
11420   case 5:
11421   case 9:
11422     // These scales are formed with basereg+scalereg.  Only accept if there is
11423     // no basereg yet.
11424     if (AM.HasBaseReg)
11425       return false;
11426     break;
11427   default:  // Other stuff never works.
11428     return false;
11429   }
11430
11431   return true;
11432 }
11433
11434
11435 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11436   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11437     return false;
11438   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11439   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11440   if (NumBits1 <= NumBits2)
11441     return false;
11442   return true;
11443 }
11444
11445 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11446   if (!VT1.isInteger() || !VT2.isInteger())
11447     return false;
11448   unsigned NumBits1 = VT1.getSizeInBits();
11449   unsigned NumBits2 = VT2.getSizeInBits();
11450   if (NumBits1 <= NumBits2)
11451     return false;
11452   return true;
11453 }
11454
11455 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11456   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11457   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11458 }
11459
11460 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11461   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11462   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11463 }
11464
11465 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11466   // i16 instructions are longer (0x66 prefix) and potentially slower.
11467   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11468 }
11469
11470 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11471 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11472 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11473 /// are assumed to be legal.
11474 bool
11475 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11476                                       EVT VT) const {
11477   // Very little shuffling can be done for 64-bit vectors right now.
11478   if (VT.getSizeInBits() == 64)
11479     return false;
11480
11481   // FIXME: pshufb, blends, shifts.
11482   return (VT.getVectorNumElements() == 2 ||
11483           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11484           isMOVLMask(M, VT) ||
11485           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11486           isPSHUFDMask(M, VT) ||
11487           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11488           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11489           isPALIGNRMask(M, VT, Subtarget) ||
11490           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11491           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11492           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11493           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11494 }
11495
11496 bool
11497 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11498                                           EVT VT) const {
11499   unsigned NumElts = VT.getVectorNumElements();
11500   // FIXME: This collection of masks seems suspect.
11501   if (NumElts == 2)
11502     return true;
11503   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11504     return (isMOVLMask(Mask, VT)  ||
11505             isCommutedMOVLMask(Mask, VT, true) ||
11506             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11507             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11508   }
11509   return false;
11510 }
11511
11512 //===----------------------------------------------------------------------===//
11513 //                           X86 Scheduler Hooks
11514 //===----------------------------------------------------------------------===//
11515
11516 // private utility function
11517 MachineBasicBlock *
11518 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11519                                                        MachineBasicBlock *MBB,
11520                                                        unsigned regOpc,
11521                                                        unsigned immOpc,
11522                                                        unsigned LoadOpc,
11523                                                        unsigned CXchgOpc,
11524                                                        unsigned notOpc,
11525                                                        unsigned EAXreg,
11526                                                  const TargetRegisterClass *RC,
11527                                                        bool Invert) const {
11528   // For the atomic bitwise operator, we generate
11529   //   thisMBB:
11530   //   newMBB:
11531   //     ld  t1 = [bitinstr.addr]
11532   //     op  t2 = t1, [bitinstr.val]
11533   //     not t3 = t2  (if Invert)
11534   //     mov EAX = t1
11535   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11536   //     bz  newMBB
11537   //     fallthrough -->nextMBB
11538   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11539   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11540   MachineFunction::iterator MBBIter = MBB;
11541   ++MBBIter;
11542
11543   /// First build the CFG
11544   MachineFunction *F = MBB->getParent();
11545   MachineBasicBlock *thisMBB = MBB;
11546   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11547   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11548   F->insert(MBBIter, newMBB);
11549   F->insert(MBBIter, nextMBB);
11550
11551   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11552   nextMBB->splice(nextMBB->begin(), thisMBB,
11553                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11554                   thisMBB->end());
11555   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11556
11557   // Update thisMBB to fall through to newMBB
11558   thisMBB->addSuccessor(newMBB);
11559
11560   // newMBB jumps to itself and fall through to nextMBB
11561   newMBB->addSuccessor(nextMBB);
11562   newMBB->addSuccessor(newMBB);
11563
11564   // Insert instructions into newMBB based on incoming instruction
11565   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11566          "unexpected number of operands");
11567   DebugLoc dl = bInstr->getDebugLoc();
11568   MachineOperand& destOper = bInstr->getOperand(0);
11569   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11570   int numArgs = bInstr->getNumOperands() - 1;
11571   for (int i=0; i < numArgs; ++i)
11572     argOpers[i] = &bInstr->getOperand(i+1);
11573
11574   // x86 address has 4 operands: base, index, scale, and displacement
11575   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11576   int valArgIndx = lastAddrIndx + 1;
11577
11578   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11579   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11580   for (int i=0; i <= lastAddrIndx; ++i)
11581     (*MIB).addOperand(*argOpers[i]);
11582
11583   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11584   assert((argOpers[valArgIndx]->isReg() ||
11585           argOpers[valArgIndx]->isImm()) &&
11586          "invalid operand");
11587   if (argOpers[valArgIndx]->isReg())
11588     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11589   else
11590     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11591   MIB.addReg(t1);
11592   (*MIB).addOperand(*argOpers[valArgIndx]);
11593
11594   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11595   if (Invert) {
11596     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11597   }
11598   else
11599     t3 = t2;
11600
11601   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11602   MIB.addReg(t1);
11603
11604   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11605   for (int i=0; i <= lastAddrIndx; ++i)
11606     (*MIB).addOperand(*argOpers[i]);
11607   MIB.addReg(t3);
11608   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11609   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11610                     bInstr->memoperands_end());
11611
11612   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11613   MIB.addReg(EAXreg);
11614
11615   // insert branch
11616   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11617
11618   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11619   return nextMBB;
11620 }
11621
11622 // private utility function:  64 bit atomics on 32 bit host.
11623 MachineBasicBlock *
11624 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11625                                                        MachineBasicBlock *MBB,
11626                                                        unsigned regOpcL,
11627                                                        unsigned regOpcH,
11628                                                        unsigned immOpcL,
11629                                                        unsigned immOpcH,
11630                                                        bool Invert) const {
11631   // For the atomic bitwise operator, we generate
11632   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11633   //     ld t1,t2 = [bitinstr.addr]
11634   //   newMBB:
11635   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11636   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11637   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11638   //     neg t7, t8 < t5, t6  (if Invert)
11639   //     mov ECX, EBX <- t5, t6
11640   //     mov EAX, EDX <- t1, t2
11641   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11642   //     mov t3, t4 <- EAX, EDX
11643   //     bz  newMBB
11644   //     result in out1, out2
11645   //     fallthrough -->nextMBB
11646
11647   const TargetRegisterClass *RC = &X86::GR32RegClass;
11648   const unsigned LoadOpc = X86::MOV32rm;
11649   const unsigned NotOpc = X86::NOT32r;
11650   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11651   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11652   MachineFunction::iterator MBBIter = MBB;
11653   ++MBBIter;
11654
11655   /// First build the CFG
11656   MachineFunction *F = MBB->getParent();
11657   MachineBasicBlock *thisMBB = MBB;
11658   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11659   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11660   F->insert(MBBIter, newMBB);
11661   F->insert(MBBIter, nextMBB);
11662
11663   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11664   nextMBB->splice(nextMBB->begin(), thisMBB,
11665                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11666                   thisMBB->end());
11667   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11668
11669   // Update thisMBB to fall through to newMBB
11670   thisMBB->addSuccessor(newMBB);
11671
11672   // newMBB jumps to itself and fall through to nextMBB
11673   newMBB->addSuccessor(nextMBB);
11674   newMBB->addSuccessor(newMBB);
11675
11676   DebugLoc dl = bInstr->getDebugLoc();
11677   // Insert instructions into newMBB based on incoming instruction
11678   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11679   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11680          "unexpected number of operands");
11681   MachineOperand& dest1Oper = bInstr->getOperand(0);
11682   MachineOperand& dest2Oper = bInstr->getOperand(1);
11683   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11684   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11685     argOpers[i] = &bInstr->getOperand(i+2);
11686
11687     // We use some of the operands multiple times, so conservatively just
11688     // clear any kill flags that might be present.
11689     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11690       argOpers[i]->setIsKill(false);
11691   }
11692
11693   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11694   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11695
11696   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11697   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11698   for (int i=0; i <= lastAddrIndx; ++i)
11699     (*MIB).addOperand(*argOpers[i]);
11700   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11701   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11702   // add 4 to displacement.
11703   for (int i=0; i <= lastAddrIndx-2; ++i)
11704     (*MIB).addOperand(*argOpers[i]);
11705   MachineOperand newOp3 = *(argOpers[3]);
11706   if (newOp3.isImm())
11707     newOp3.setImm(newOp3.getImm()+4);
11708   else
11709     newOp3.setOffset(newOp3.getOffset()+4);
11710   (*MIB).addOperand(newOp3);
11711   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11712
11713   // t3/4 are defined later, at the bottom of the loop
11714   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11715   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11716   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11717     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11718   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11719     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11720
11721   // The subsequent operations should be using the destination registers of
11722   // the PHI instructions.
11723   t1 = dest1Oper.getReg();
11724   t2 = dest2Oper.getReg();
11725
11726   int valArgIndx = lastAddrIndx + 1;
11727   assert((argOpers[valArgIndx]->isReg() ||
11728           argOpers[valArgIndx]->isImm()) &&
11729          "invalid operand");
11730   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11731   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11732   if (argOpers[valArgIndx]->isReg())
11733     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11734   else
11735     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11736   if (regOpcL != X86::MOV32rr)
11737     MIB.addReg(t1);
11738   (*MIB).addOperand(*argOpers[valArgIndx]);
11739   assert(argOpers[valArgIndx + 1]->isReg() ==
11740          argOpers[valArgIndx]->isReg());
11741   assert(argOpers[valArgIndx + 1]->isImm() ==
11742          argOpers[valArgIndx]->isImm());
11743   if (argOpers[valArgIndx + 1]->isReg())
11744     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11745   else
11746     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11747   if (regOpcH != X86::MOV32rr)
11748     MIB.addReg(t2);
11749   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11750
11751   unsigned t7, t8;
11752   if (Invert) {
11753     t7 = F->getRegInfo().createVirtualRegister(RC);
11754     t8 = F->getRegInfo().createVirtualRegister(RC);
11755     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11756     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11757   } else {
11758     t7 = t5;
11759     t8 = t6;
11760   }
11761
11762   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11763   MIB.addReg(t1);
11764   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11765   MIB.addReg(t2);
11766
11767   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11768   MIB.addReg(t7);
11769   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11770   MIB.addReg(t8);
11771
11772   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11773   for (int i=0; i <= lastAddrIndx; ++i)
11774     (*MIB).addOperand(*argOpers[i]);
11775
11776   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11777   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11778                     bInstr->memoperands_end());
11779
11780   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11781   MIB.addReg(X86::EAX);
11782   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11783   MIB.addReg(X86::EDX);
11784
11785   // insert branch
11786   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11787
11788   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11789   return nextMBB;
11790 }
11791
11792 // private utility function
11793 MachineBasicBlock *
11794 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11795                                                       MachineBasicBlock *MBB,
11796                                                       unsigned cmovOpc) const {
11797   // For the atomic min/max operator, we generate
11798   //   thisMBB:
11799   //   newMBB:
11800   //     ld t1 = [min/max.addr]
11801   //     mov t2 = [min/max.val]
11802   //     cmp  t1, t2
11803   //     cmov[cond] t2 = t1
11804   //     mov EAX = t1
11805   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11806   //     bz   newMBB
11807   //     fallthrough -->nextMBB
11808   //
11809   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11810   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11811   MachineFunction::iterator MBBIter = MBB;
11812   ++MBBIter;
11813
11814   /// First build the CFG
11815   MachineFunction *F = MBB->getParent();
11816   MachineBasicBlock *thisMBB = MBB;
11817   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11818   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11819   F->insert(MBBIter, newMBB);
11820   F->insert(MBBIter, nextMBB);
11821
11822   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11823   nextMBB->splice(nextMBB->begin(), thisMBB,
11824                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11825                   thisMBB->end());
11826   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11827
11828   // Update thisMBB to fall through to newMBB
11829   thisMBB->addSuccessor(newMBB);
11830
11831   // newMBB jumps to newMBB and fall through to nextMBB
11832   newMBB->addSuccessor(nextMBB);
11833   newMBB->addSuccessor(newMBB);
11834
11835   DebugLoc dl = mInstr->getDebugLoc();
11836   // Insert instructions into newMBB based on incoming instruction
11837   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11838          "unexpected number of operands");
11839   MachineOperand& destOper = mInstr->getOperand(0);
11840   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11841   int numArgs = mInstr->getNumOperands() - 1;
11842   for (int i=0; i < numArgs; ++i)
11843     argOpers[i] = &mInstr->getOperand(i+1);
11844
11845   // x86 address has 4 operands: base, index, scale, and displacement
11846   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11847   int valArgIndx = lastAddrIndx + 1;
11848
11849   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11850   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11851   for (int i=0; i <= lastAddrIndx; ++i)
11852     (*MIB).addOperand(*argOpers[i]);
11853
11854   // We only support register and immediate values
11855   assert((argOpers[valArgIndx]->isReg() ||
11856           argOpers[valArgIndx]->isImm()) &&
11857          "invalid operand");
11858
11859   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11860   if (argOpers[valArgIndx]->isReg())
11861     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11862   else
11863     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11864   (*MIB).addOperand(*argOpers[valArgIndx]);
11865
11866   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11867   MIB.addReg(t1);
11868
11869   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11870   MIB.addReg(t1);
11871   MIB.addReg(t2);
11872
11873   // Generate movc
11874   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11875   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11876   MIB.addReg(t2);
11877   MIB.addReg(t1);
11878
11879   // Cmp and exchange if none has modified the memory location
11880   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11881   for (int i=0; i <= lastAddrIndx; ++i)
11882     (*MIB).addOperand(*argOpers[i]);
11883   MIB.addReg(t3);
11884   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11885   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11886                     mInstr->memoperands_end());
11887
11888   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11889   MIB.addReg(X86::EAX);
11890
11891   // insert branch
11892   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11893
11894   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11895   return nextMBB;
11896 }
11897
11898 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11899 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11900 // in the .td file.
11901 MachineBasicBlock *
11902 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11903                             unsigned numArgs, bool memArg) const {
11904   assert(Subtarget->hasSSE42() &&
11905          "Target must have SSE4.2 or AVX features enabled");
11906
11907   DebugLoc dl = MI->getDebugLoc();
11908   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11909   unsigned Opc;
11910   if (!Subtarget->hasAVX()) {
11911     if (memArg)
11912       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11913     else
11914       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11915   } else {
11916     if (memArg)
11917       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11918     else
11919       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11920   }
11921
11922   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11923   for (unsigned i = 0; i < numArgs; ++i) {
11924     MachineOperand &Op = MI->getOperand(i+1);
11925     if (!(Op.isReg() && Op.isImplicit()))
11926       MIB.addOperand(Op);
11927   }
11928   BuildMI(*BB, MI, dl,
11929     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11930              MI->getOperand(0).getReg())
11931     .addReg(X86::XMM0);
11932
11933   MI->eraseFromParent();
11934   return BB;
11935 }
11936
11937 MachineBasicBlock *
11938 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11939   DebugLoc dl = MI->getDebugLoc();
11940   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11941
11942   // Address into RAX/EAX, other two args into ECX, EDX.
11943   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11944   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11945   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11946   for (int i = 0; i < X86::AddrNumOperands; ++i)
11947     MIB.addOperand(MI->getOperand(i));
11948
11949   unsigned ValOps = X86::AddrNumOperands;
11950   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11951     .addReg(MI->getOperand(ValOps).getReg());
11952   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11953     .addReg(MI->getOperand(ValOps+1).getReg());
11954
11955   // The instruction doesn't actually take any operands though.
11956   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11957
11958   MI->eraseFromParent(); // The pseudo is gone now.
11959   return BB;
11960 }
11961
11962 MachineBasicBlock *
11963 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11964   DebugLoc dl = MI->getDebugLoc();
11965   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11966
11967   // First arg in ECX, the second in EAX.
11968   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11969     .addReg(MI->getOperand(0).getReg());
11970   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11971     .addReg(MI->getOperand(1).getReg());
11972
11973   // The instruction doesn't actually take any operands though.
11974   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11975
11976   MI->eraseFromParent(); // The pseudo is gone now.
11977   return BB;
11978 }
11979
11980 MachineBasicBlock *
11981 X86TargetLowering::EmitVAARG64WithCustomInserter(
11982                    MachineInstr *MI,
11983                    MachineBasicBlock *MBB) const {
11984   // Emit va_arg instruction on X86-64.
11985
11986   // Operands to this pseudo-instruction:
11987   // 0  ) Output        : destination address (reg)
11988   // 1-5) Input         : va_list address (addr, i64mem)
11989   // 6  ) ArgSize       : Size (in bytes) of vararg type
11990   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11991   // 8  ) Align         : Alignment of type
11992   // 9  ) EFLAGS (implicit-def)
11993
11994   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11995   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11996
11997   unsigned DestReg = MI->getOperand(0).getReg();
11998   MachineOperand &Base = MI->getOperand(1);
11999   MachineOperand &Scale = MI->getOperand(2);
12000   MachineOperand &Index = MI->getOperand(3);
12001   MachineOperand &Disp = MI->getOperand(4);
12002   MachineOperand &Segment = MI->getOperand(5);
12003   unsigned ArgSize = MI->getOperand(6).getImm();
12004   unsigned ArgMode = MI->getOperand(7).getImm();
12005   unsigned Align = MI->getOperand(8).getImm();
12006
12007   // Memory Reference
12008   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12009   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12010   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12011
12012   // Machine Information
12013   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12014   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12015   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12016   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12017   DebugLoc DL = MI->getDebugLoc();
12018
12019   // struct va_list {
12020   //   i32   gp_offset
12021   //   i32   fp_offset
12022   //   i64   overflow_area (address)
12023   //   i64   reg_save_area (address)
12024   // }
12025   // sizeof(va_list) = 24
12026   // alignment(va_list) = 8
12027
12028   unsigned TotalNumIntRegs = 6;
12029   unsigned TotalNumXMMRegs = 8;
12030   bool UseGPOffset = (ArgMode == 1);
12031   bool UseFPOffset = (ArgMode == 2);
12032   unsigned MaxOffset = TotalNumIntRegs * 8 +
12033                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12034
12035   /* Align ArgSize to a multiple of 8 */
12036   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12037   bool NeedsAlign = (Align > 8);
12038
12039   MachineBasicBlock *thisMBB = MBB;
12040   MachineBasicBlock *overflowMBB;
12041   MachineBasicBlock *offsetMBB;
12042   MachineBasicBlock *endMBB;
12043
12044   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12045   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12046   unsigned OffsetReg = 0;
12047
12048   if (!UseGPOffset && !UseFPOffset) {
12049     // If we only pull from the overflow region, we don't create a branch.
12050     // We don't need to alter control flow.
12051     OffsetDestReg = 0; // unused
12052     OverflowDestReg = DestReg;
12053
12054     offsetMBB = NULL;
12055     overflowMBB = thisMBB;
12056     endMBB = thisMBB;
12057   } else {
12058     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12059     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12060     // If not, pull from overflow_area. (branch to overflowMBB)
12061     //
12062     //       thisMBB
12063     //         |     .
12064     //         |        .
12065     //     offsetMBB   overflowMBB
12066     //         |        .
12067     //         |     .
12068     //        endMBB
12069
12070     // Registers for the PHI in endMBB
12071     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12072     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12073
12074     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12075     MachineFunction *MF = MBB->getParent();
12076     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12077     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12078     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12079
12080     MachineFunction::iterator MBBIter = MBB;
12081     ++MBBIter;
12082
12083     // Insert the new basic blocks
12084     MF->insert(MBBIter, offsetMBB);
12085     MF->insert(MBBIter, overflowMBB);
12086     MF->insert(MBBIter, endMBB);
12087
12088     // Transfer the remainder of MBB and its successor edges to endMBB.
12089     endMBB->splice(endMBB->begin(), thisMBB,
12090                     llvm::next(MachineBasicBlock::iterator(MI)),
12091                     thisMBB->end());
12092     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12093
12094     // Make offsetMBB and overflowMBB successors of thisMBB
12095     thisMBB->addSuccessor(offsetMBB);
12096     thisMBB->addSuccessor(overflowMBB);
12097
12098     // endMBB is a successor of both offsetMBB and overflowMBB
12099     offsetMBB->addSuccessor(endMBB);
12100     overflowMBB->addSuccessor(endMBB);
12101
12102     // Load the offset value into a register
12103     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12104     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12105       .addOperand(Base)
12106       .addOperand(Scale)
12107       .addOperand(Index)
12108       .addDisp(Disp, UseFPOffset ? 4 : 0)
12109       .addOperand(Segment)
12110       .setMemRefs(MMOBegin, MMOEnd);
12111
12112     // Check if there is enough room left to pull this argument.
12113     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12114       .addReg(OffsetReg)
12115       .addImm(MaxOffset + 8 - ArgSizeA8);
12116
12117     // Branch to "overflowMBB" if offset >= max
12118     // Fall through to "offsetMBB" otherwise
12119     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12120       .addMBB(overflowMBB);
12121   }
12122
12123   // In offsetMBB, emit code to use the reg_save_area.
12124   if (offsetMBB) {
12125     assert(OffsetReg != 0);
12126
12127     // Read the reg_save_area address.
12128     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12129     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12130       .addOperand(Base)
12131       .addOperand(Scale)
12132       .addOperand(Index)
12133       .addDisp(Disp, 16)
12134       .addOperand(Segment)
12135       .setMemRefs(MMOBegin, MMOEnd);
12136
12137     // Zero-extend the offset
12138     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12139       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12140         .addImm(0)
12141         .addReg(OffsetReg)
12142         .addImm(X86::sub_32bit);
12143
12144     // Add the offset to the reg_save_area to get the final address.
12145     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12146       .addReg(OffsetReg64)
12147       .addReg(RegSaveReg);
12148
12149     // Compute the offset for the next argument
12150     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12151     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12152       .addReg(OffsetReg)
12153       .addImm(UseFPOffset ? 16 : 8);
12154
12155     // Store it back into the va_list.
12156     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12157       .addOperand(Base)
12158       .addOperand(Scale)
12159       .addOperand(Index)
12160       .addDisp(Disp, UseFPOffset ? 4 : 0)
12161       .addOperand(Segment)
12162       .addReg(NextOffsetReg)
12163       .setMemRefs(MMOBegin, MMOEnd);
12164
12165     // Jump to endMBB
12166     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12167       .addMBB(endMBB);
12168   }
12169
12170   //
12171   // Emit code to use overflow area
12172   //
12173
12174   // Load the overflow_area address into a register.
12175   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12176   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12177     .addOperand(Base)
12178     .addOperand(Scale)
12179     .addOperand(Index)
12180     .addDisp(Disp, 8)
12181     .addOperand(Segment)
12182     .setMemRefs(MMOBegin, MMOEnd);
12183
12184   // If we need to align it, do so. Otherwise, just copy the address
12185   // to OverflowDestReg.
12186   if (NeedsAlign) {
12187     // Align the overflow address
12188     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12189     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12190
12191     // aligned_addr = (addr + (align-1)) & ~(align-1)
12192     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12193       .addReg(OverflowAddrReg)
12194       .addImm(Align-1);
12195
12196     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12197       .addReg(TmpReg)
12198       .addImm(~(uint64_t)(Align-1));
12199   } else {
12200     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12201       .addReg(OverflowAddrReg);
12202   }
12203
12204   // Compute the next overflow address after this argument.
12205   // (the overflow address should be kept 8-byte aligned)
12206   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12207   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12208     .addReg(OverflowDestReg)
12209     .addImm(ArgSizeA8);
12210
12211   // Store the new overflow address.
12212   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12213     .addOperand(Base)
12214     .addOperand(Scale)
12215     .addOperand(Index)
12216     .addDisp(Disp, 8)
12217     .addOperand(Segment)
12218     .addReg(NextAddrReg)
12219     .setMemRefs(MMOBegin, MMOEnd);
12220
12221   // If we branched, emit the PHI to the front of endMBB.
12222   if (offsetMBB) {
12223     BuildMI(*endMBB, endMBB->begin(), DL,
12224             TII->get(X86::PHI), DestReg)
12225       .addReg(OffsetDestReg).addMBB(offsetMBB)
12226       .addReg(OverflowDestReg).addMBB(overflowMBB);
12227   }
12228
12229   // Erase the pseudo instruction
12230   MI->eraseFromParent();
12231
12232   return endMBB;
12233 }
12234
12235 MachineBasicBlock *
12236 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12237                                                  MachineInstr *MI,
12238                                                  MachineBasicBlock *MBB) const {
12239   // Emit code to save XMM registers to the stack. The ABI says that the
12240   // number of registers to save is given in %al, so it's theoretically
12241   // possible to do an indirect jump trick to avoid saving all of them,
12242   // however this code takes a simpler approach and just executes all
12243   // of the stores if %al is non-zero. It's less code, and it's probably
12244   // easier on the hardware branch predictor, and stores aren't all that
12245   // expensive anyway.
12246
12247   // Create the new basic blocks. One block contains all the XMM stores,
12248   // and one block is the final destination regardless of whether any
12249   // stores were performed.
12250   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12251   MachineFunction *F = MBB->getParent();
12252   MachineFunction::iterator MBBIter = MBB;
12253   ++MBBIter;
12254   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12255   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12256   F->insert(MBBIter, XMMSaveMBB);
12257   F->insert(MBBIter, EndMBB);
12258
12259   // Transfer the remainder of MBB and its successor edges to EndMBB.
12260   EndMBB->splice(EndMBB->begin(), MBB,
12261                  llvm::next(MachineBasicBlock::iterator(MI)),
12262                  MBB->end());
12263   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12264
12265   // The original block will now fall through to the XMM save block.
12266   MBB->addSuccessor(XMMSaveMBB);
12267   // The XMMSaveMBB will fall through to the end block.
12268   XMMSaveMBB->addSuccessor(EndMBB);
12269
12270   // Now add the instructions.
12271   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12272   DebugLoc DL = MI->getDebugLoc();
12273
12274   unsigned CountReg = MI->getOperand(0).getReg();
12275   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12276   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12277
12278   if (!Subtarget->isTargetWin64()) {
12279     // If %al is 0, branch around the XMM save block.
12280     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12281     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12282     MBB->addSuccessor(EndMBB);
12283   }
12284
12285   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12286   // In the XMM save block, save all the XMM argument registers.
12287   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12288     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12289     MachineMemOperand *MMO =
12290       F->getMachineMemOperand(
12291           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12292         MachineMemOperand::MOStore,
12293         /*Size=*/16, /*Align=*/16);
12294     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12295       .addFrameIndex(RegSaveFrameIndex)
12296       .addImm(/*Scale=*/1)
12297       .addReg(/*IndexReg=*/0)
12298       .addImm(/*Disp=*/Offset)
12299       .addReg(/*Segment=*/0)
12300       .addReg(MI->getOperand(i).getReg())
12301       .addMemOperand(MMO);
12302   }
12303
12304   MI->eraseFromParent();   // The pseudo instruction is gone now.
12305
12306   return EndMBB;
12307 }
12308
12309 // The EFLAGS operand of SelectItr might be missing a kill marker
12310 // because there were multiple uses of EFLAGS, and ISel didn't know
12311 // which to mark. Figure out whether SelectItr should have had a
12312 // kill marker, and set it if it should. Returns the correct kill
12313 // marker value.
12314 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12315                                      MachineBasicBlock* BB,
12316                                      const TargetRegisterInfo* TRI) {
12317   // Scan forward through BB for a use/def of EFLAGS.
12318   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12319   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12320     const MachineInstr& mi = *miI;
12321     if (mi.readsRegister(X86::EFLAGS))
12322       return false;
12323     if (mi.definesRegister(X86::EFLAGS))
12324       break; // Should have kill-flag - update below.
12325   }
12326
12327   // If we hit the end of the block, check whether EFLAGS is live into a
12328   // successor.
12329   if (miI == BB->end()) {
12330     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12331                                           sEnd = BB->succ_end();
12332          sItr != sEnd; ++sItr) {
12333       MachineBasicBlock* succ = *sItr;
12334       if (succ->isLiveIn(X86::EFLAGS))
12335         return false;
12336     }
12337   }
12338
12339   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12340   // out. SelectMI should have a kill flag on EFLAGS.
12341   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12342   return true;
12343 }
12344
12345 MachineBasicBlock *
12346 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12347                                      MachineBasicBlock *BB) const {
12348   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12349   DebugLoc DL = MI->getDebugLoc();
12350
12351   // To "insert" a SELECT_CC instruction, we actually have to insert the
12352   // diamond control-flow pattern.  The incoming instruction knows the
12353   // destination vreg to set, the condition code register to branch on, the
12354   // true/false values to select between, and a branch opcode to use.
12355   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12356   MachineFunction::iterator It = BB;
12357   ++It;
12358
12359   //  thisMBB:
12360   //  ...
12361   //   TrueVal = ...
12362   //   cmpTY ccX, r1, r2
12363   //   bCC copy1MBB
12364   //   fallthrough --> copy0MBB
12365   MachineBasicBlock *thisMBB = BB;
12366   MachineFunction *F = BB->getParent();
12367   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12368   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12369   F->insert(It, copy0MBB);
12370   F->insert(It, sinkMBB);
12371
12372   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12373   // live into the sink and copy blocks.
12374   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12375   if (!MI->killsRegister(X86::EFLAGS) &&
12376       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12377     copy0MBB->addLiveIn(X86::EFLAGS);
12378     sinkMBB->addLiveIn(X86::EFLAGS);
12379   }
12380
12381   // Transfer the remainder of BB and its successor edges to sinkMBB.
12382   sinkMBB->splice(sinkMBB->begin(), BB,
12383                   llvm::next(MachineBasicBlock::iterator(MI)),
12384                   BB->end());
12385   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12386
12387   // Add the true and fallthrough blocks as its successors.
12388   BB->addSuccessor(copy0MBB);
12389   BB->addSuccessor(sinkMBB);
12390
12391   // Create the conditional branch instruction.
12392   unsigned Opc =
12393     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12394   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12395
12396   //  copy0MBB:
12397   //   %FalseValue = ...
12398   //   # fallthrough to sinkMBB
12399   copy0MBB->addSuccessor(sinkMBB);
12400
12401   //  sinkMBB:
12402   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12403   //  ...
12404   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12405           TII->get(X86::PHI), MI->getOperand(0).getReg())
12406     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12407     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12408
12409   MI->eraseFromParent();   // The pseudo instruction is gone now.
12410   return sinkMBB;
12411 }
12412
12413 MachineBasicBlock *
12414 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12415                                         bool Is64Bit) const {
12416   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12417   DebugLoc DL = MI->getDebugLoc();
12418   MachineFunction *MF = BB->getParent();
12419   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12420
12421   assert(getTargetMachine().Options.EnableSegmentedStacks);
12422
12423   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12424   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12425
12426   // BB:
12427   //  ... [Till the alloca]
12428   // If stacklet is not large enough, jump to mallocMBB
12429   //
12430   // bumpMBB:
12431   //  Allocate by subtracting from RSP
12432   //  Jump to continueMBB
12433   //
12434   // mallocMBB:
12435   //  Allocate by call to runtime
12436   //
12437   // continueMBB:
12438   //  ...
12439   //  [rest of original BB]
12440   //
12441
12442   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12443   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12444   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12445
12446   MachineRegisterInfo &MRI = MF->getRegInfo();
12447   const TargetRegisterClass *AddrRegClass =
12448     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12449
12450   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12451     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12452     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12453     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12454     sizeVReg = MI->getOperand(1).getReg(),
12455     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12456
12457   MachineFunction::iterator MBBIter = BB;
12458   ++MBBIter;
12459
12460   MF->insert(MBBIter, bumpMBB);
12461   MF->insert(MBBIter, mallocMBB);
12462   MF->insert(MBBIter, continueMBB);
12463
12464   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12465                       (MachineBasicBlock::iterator(MI)), BB->end());
12466   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12467
12468   // Add code to the main basic block to check if the stack limit has been hit,
12469   // and if so, jump to mallocMBB otherwise to bumpMBB.
12470   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12471   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12472     .addReg(tmpSPVReg).addReg(sizeVReg);
12473   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12474     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12475     .addReg(SPLimitVReg);
12476   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12477
12478   // bumpMBB simply decreases the stack pointer, since we know the current
12479   // stacklet has enough space.
12480   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12481     .addReg(SPLimitVReg);
12482   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12483     .addReg(SPLimitVReg);
12484   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12485
12486   // Calls into a routine in libgcc to allocate more space from the heap.
12487   const uint32_t *RegMask =
12488     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12489   if (Is64Bit) {
12490     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12491       .addReg(sizeVReg);
12492     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12493       .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI)
12494       .addRegMask(RegMask)
12495       .addReg(X86::RAX, RegState::ImplicitDefine);
12496   } else {
12497     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12498       .addImm(12);
12499     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12500     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12501       .addExternalSymbol("__morestack_allocate_stack_space")
12502       .addRegMask(RegMask)
12503       .addReg(X86::EAX, RegState::ImplicitDefine);
12504   }
12505
12506   if (!Is64Bit)
12507     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12508       .addImm(16);
12509
12510   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12511     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12512   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12513
12514   // Set up the CFG correctly.
12515   BB->addSuccessor(bumpMBB);
12516   BB->addSuccessor(mallocMBB);
12517   mallocMBB->addSuccessor(continueMBB);
12518   bumpMBB->addSuccessor(continueMBB);
12519
12520   // Take care of the PHI nodes.
12521   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12522           MI->getOperand(0).getReg())
12523     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12524     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12525
12526   // Delete the original pseudo instruction.
12527   MI->eraseFromParent();
12528
12529   // And we're done.
12530   return continueMBB;
12531 }
12532
12533 MachineBasicBlock *
12534 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12535                                           MachineBasicBlock *BB) const {
12536   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12537   DebugLoc DL = MI->getDebugLoc();
12538
12539   assert(!Subtarget->isTargetEnvMacho());
12540
12541   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12542   // non-trivial part is impdef of ESP.
12543
12544   if (Subtarget->isTargetWin64()) {
12545     if (Subtarget->isTargetCygMing()) {
12546       // ___chkstk(Mingw64):
12547       // Clobbers R10, R11, RAX and EFLAGS.
12548       // Updates RSP.
12549       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12550         .addExternalSymbol("___chkstk")
12551         .addReg(X86::RAX, RegState::Implicit)
12552         .addReg(X86::RSP, RegState::Implicit)
12553         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12554         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12555         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12556     } else {
12557       // __chkstk(MSVCRT): does not update stack pointer.
12558       // Clobbers R10, R11 and EFLAGS.
12559       // FIXME: RAX(allocated size) might be reused and not killed.
12560       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12561         .addExternalSymbol("__chkstk")
12562         .addReg(X86::RAX, RegState::Implicit)
12563         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12564       // RAX has the offset to subtracted from RSP.
12565       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12566         .addReg(X86::RSP)
12567         .addReg(X86::RAX);
12568     }
12569   } else {
12570     const char *StackProbeSymbol =
12571       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12572
12573     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12574       .addExternalSymbol(StackProbeSymbol)
12575       .addReg(X86::EAX, RegState::Implicit)
12576       .addReg(X86::ESP, RegState::Implicit)
12577       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12578       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12579       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12580   }
12581
12582   MI->eraseFromParent();   // The pseudo instruction is gone now.
12583   return BB;
12584 }
12585
12586 MachineBasicBlock *
12587 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12588                                       MachineBasicBlock *BB) const {
12589   // This is pretty easy.  We're taking the value that we received from
12590   // our load from the relocation, sticking it in either RDI (x86-64)
12591   // or EAX and doing an indirect call.  The return value will then
12592   // be in the normal return register.
12593   const X86InstrInfo *TII
12594     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12595   DebugLoc DL = MI->getDebugLoc();
12596   MachineFunction *F = BB->getParent();
12597
12598   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12599   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12600
12601   // Get a register mask for the lowered call.
12602   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12603   // proper register mask.
12604   const uint32_t *RegMask =
12605     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12606   if (Subtarget->is64Bit()) {
12607     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12608                                       TII->get(X86::MOV64rm), X86::RDI)
12609     .addReg(X86::RIP)
12610     .addImm(0).addReg(0)
12611     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12612                       MI->getOperand(3).getTargetFlags())
12613     .addReg(0);
12614     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12615     addDirectMem(MIB, X86::RDI);
12616     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12617   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12618     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12619                                       TII->get(X86::MOV32rm), X86::EAX)
12620     .addReg(0)
12621     .addImm(0).addReg(0)
12622     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12623                       MI->getOperand(3).getTargetFlags())
12624     .addReg(0);
12625     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12626     addDirectMem(MIB, X86::EAX);
12627     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12628   } else {
12629     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12630                                       TII->get(X86::MOV32rm), X86::EAX)
12631     .addReg(TII->getGlobalBaseReg(F))
12632     .addImm(0).addReg(0)
12633     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12634                       MI->getOperand(3).getTargetFlags())
12635     .addReg(0);
12636     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12637     addDirectMem(MIB, X86::EAX);
12638     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12639   }
12640
12641   MI->eraseFromParent(); // The pseudo instruction is gone now.
12642   return BB;
12643 }
12644
12645 MachineBasicBlock *
12646 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12647                                                MachineBasicBlock *BB) const {
12648   switch (MI->getOpcode()) {
12649   default: llvm_unreachable("Unexpected instr type to insert");
12650   case X86::TAILJMPd64:
12651   case X86::TAILJMPr64:
12652   case X86::TAILJMPm64:
12653     llvm_unreachable("TAILJMP64 would not be touched here.");
12654   case X86::TCRETURNdi64:
12655   case X86::TCRETURNri64:
12656   case X86::TCRETURNmi64:
12657     return BB;
12658   case X86::WIN_ALLOCA:
12659     return EmitLoweredWinAlloca(MI, BB);
12660   case X86::SEG_ALLOCA_32:
12661     return EmitLoweredSegAlloca(MI, BB, false);
12662   case X86::SEG_ALLOCA_64:
12663     return EmitLoweredSegAlloca(MI, BB, true);
12664   case X86::TLSCall_32:
12665   case X86::TLSCall_64:
12666     return EmitLoweredTLSCall(MI, BB);
12667   case X86::CMOV_GR8:
12668   case X86::CMOV_FR32:
12669   case X86::CMOV_FR64:
12670   case X86::CMOV_V4F32:
12671   case X86::CMOV_V2F64:
12672   case X86::CMOV_V2I64:
12673   case X86::CMOV_V8F32:
12674   case X86::CMOV_V4F64:
12675   case X86::CMOV_V4I64:
12676   case X86::CMOV_GR16:
12677   case X86::CMOV_GR32:
12678   case X86::CMOV_RFP32:
12679   case X86::CMOV_RFP64:
12680   case X86::CMOV_RFP80:
12681     return EmitLoweredSelect(MI, BB);
12682
12683   case X86::FP32_TO_INT16_IN_MEM:
12684   case X86::FP32_TO_INT32_IN_MEM:
12685   case X86::FP32_TO_INT64_IN_MEM:
12686   case X86::FP64_TO_INT16_IN_MEM:
12687   case X86::FP64_TO_INT32_IN_MEM:
12688   case X86::FP64_TO_INT64_IN_MEM:
12689   case X86::FP80_TO_INT16_IN_MEM:
12690   case X86::FP80_TO_INT32_IN_MEM:
12691   case X86::FP80_TO_INT64_IN_MEM: {
12692     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12693     DebugLoc DL = MI->getDebugLoc();
12694
12695     // Change the floating point control register to use "round towards zero"
12696     // mode when truncating to an integer value.
12697     MachineFunction *F = BB->getParent();
12698     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12699     addFrameReference(BuildMI(*BB, MI, DL,
12700                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12701
12702     // Load the old value of the high byte of the control word...
12703     unsigned OldCW =
12704       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12705     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12706                       CWFrameIdx);
12707
12708     // Set the high part to be round to zero...
12709     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12710       .addImm(0xC7F);
12711
12712     // Reload the modified control word now...
12713     addFrameReference(BuildMI(*BB, MI, DL,
12714                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12715
12716     // Restore the memory image of control word to original value
12717     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12718       .addReg(OldCW);
12719
12720     // Get the X86 opcode to use.
12721     unsigned Opc;
12722     switch (MI->getOpcode()) {
12723     default: llvm_unreachable("illegal opcode!");
12724     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12725     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12726     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12727     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12728     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12729     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12730     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12731     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12732     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12733     }
12734
12735     X86AddressMode AM;
12736     MachineOperand &Op = MI->getOperand(0);
12737     if (Op.isReg()) {
12738       AM.BaseType = X86AddressMode::RegBase;
12739       AM.Base.Reg = Op.getReg();
12740     } else {
12741       AM.BaseType = X86AddressMode::FrameIndexBase;
12742       AM.Base.FrameIndex = Op.getIndex();
12743     }
12744     Op = MI->getOperand(1);
12745     if (Op.isImm())
12746       AM.Scale = Op.getImm();
12747     Op = MI->getOperand(2);
12748     if (Op.isImm())
12749       AM.IndexReg = Op.getImm();
12750     Op = MI->getOperand(3);
12751     if (Op.isGlobal()) {
12752       AM.GV = Op.getGlobal();
12753     } else {
12754       AM.Disp = Op.getImm();
12755     }
12756     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12757                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12758
12759     // Reload the original control word now.
12760     addFrameReference(BuildMI(*BB, MI, DL,
12761                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12762
12763     MI->eraseFromParent();   // The pseudo instruction is gone now.
12764     return BB;
12765   }
12766     // String/text processing lowering.
12767   case X86::PCMPISTRM128REG:
12768   case X86::VPCMPISTRM128REG:
12769     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12770   case X86::PCMPISTRM128MEM:
12771   case X86::VPCMPISTRM128MEM:
12772     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12773   case X86::PCMPESTRM128REG:
12774   case X86::VPCMPESTRM128REG:
12775     return EmitPCMP(MI, BB, 5, false /* in mem */);
12776   case X86::PCMPESTRM128MEM:
12777   case X86::VPCMPESTRM128MEM:
12778     return EmitPCMP(MI, BB, 5, true /* in mem */);
12779
12780     // Thread synchronization.
12781   case X86::MONITOR:
12782     return EmitMonitor(MI, BB);
12783   case X86::MWAIT:
12784     return EmitMwait(MI, BB);
12785
12786     // Atomic Lowering.
12787   case X86::ATOMAND32:
12788     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12789                                                X86::AND32ri, X86::MOV32rm,
12790                                                X86::LCMPXCHG32,
12791                                                X86::NOT32r, X86::EAX,
12792                                                &X86::GR32RegClass);
12793   case X86::ATOMOR32:
12794     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12795                                                X86::OR32ri, X86::MOV32rm,
12796                                                X86::LCMPXCHG32,
12797                                                X86::NOT32r, X86::EAX,
12798                                                &X86::GR32RegClass);
12799   case X86::ATOMXOR32:
12800     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12801                                                X86::XOR32ri, X86::MOV32rm,
12802                                                X86::LCMPXCHG32,
12803                                                X86::NOT32r, X86::EAX,
12804                                                &X86::GR32RegClass);
12805   case X86::ATOMNAND32:
12806     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12807                                                X86::AND32ri, X86::MOV32rm,
12808                                                X86::LCMPXCHG32,
12809                                                X86::NOT32r, X86::EAX,
12810                                                &X86::GR32RegClass, true);
12811   case X86::ATOMMIN32:
12812     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12813   case X86::ATOMMAX32:
12814     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12815   case X86::ATOMUMIN32:
12816     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12817   case X86::ATOMUMAX32:
12818     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12819
12820   case X86::ATOMAND16:
12821     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12822                                                X86::AND16ri, X86::MOV16rm,
12823                                                X86::LCMPXCHG16,
12824                                                X86::NOT16r, X86::AX,
12825                                                &X86::GR16RegClass);
12826   case X86::ATOMOR16:
12827     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12828                                                X86::OR16ri, X86::MOV16rm,
12829                                                X86::LCMPXCHG16,
12830                                                X86::NOT16r, X86::AX,
12831                                                &X86::GR16RegClass);
12832   case X86::ATOMXOR16:
12833     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12834                                                X86::XOR16ri, X86::MOV16rm,
12835                                                X86::LCMPXCHG16,
12836                                                X86::NOT16r, X86::AX,
12837                                                &X86::GR16RegClass);
12838   case X86::ATOMNAND16:
12839     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12840                                                X86::AND16ri, X86::MOV16rm,
12841                                                X86::LCMPXCHG16,
12842                                                X86::NOT16r, X86::AX,
12843                                                &X86::GR16RegClass, true);
12844   case X86::ATOMMIN16:
12845     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12846   case X86::ATOMMAX16:
12847     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12848   case X86::ATOMUMIN16:
12849     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12850   case X86::ATOMUMAX16:
12851     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12852
12853   case X86::ATOMAND8:
12854     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12855                                                X86::AND8ri, X86::MOV8rm,
12856                                                X86::LCMPXCHG8,
12857                                                X86::NOT8r, X86::AL,
12858                                                &X86::GR8RegClass);
12859   case X86::ATOMOR8:
12860     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12861                                                X86::OR8ri, X86::MOV8rm,
12862                                                X86::LCMPXCHG8,
12863                                                X86::NOT8r, X86::AL,
12864                                                &X86::GR8RegClass);
12865   case X86::ATOMXOR8:
12866     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12867                                                X86::XOR8ri, X86::MOV8rm,
12868                                                X86::LCMPXCHG8,
12869                                                X86::NOT8r, X86::AL,
12870                                                &X86::GR8RegClass);
12871   case X86::ATOMNAND8:
12872     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12873                                                X86::AND8ri, X86::MOV8rm,
12874                                                X86::LCMPXCHG8,
12875                                                X86::NOT8r, X86::AL,
12876                                                &X86::GR8RegClass, true);
12877   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12878   // This group is for 64-bit host.
12879   case X86::ATOMAND64:
12880     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12881                                                X86::AND64ri32, X86::MOV64rm,
12882                                                X86::LCMPXCHG64,
12883                                                X86::NOT64r, X86::RAX,
12884                                                &X86::GR64RegClass);
12885   case X86::ATOMOR64:
12886     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12887                                                X86::OR64ri32, X86::MOV64rm,
12888                                                X86::LCMPXCHG64,
12889                                                X86::NOT64r, X86::RAX,
12890                                                &X86::GR64RegClass);
12891   case X86::ATOMXOR64:
12892     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12893                                                X86::XOR64ri32, X86::MOV64rm,
12894                                                X86::LCMPXCHG64,
12895                                                X86::NOT64r, X86::RAX,
12896                                                &X86::GR64RegClass);
12897   case X86::ATOMNAND64:
12898     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12899                                                X86::AND64ri32, X86::MOV64rm,
12900                                                X86::LCMPXCHG64,
12901                                                X86::NOT64r, X86::RAX,
12902                                                &X86::GR64RegClass, true);
12903   case X86::ATOMMIN64:
12904     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12905   case X86::ATOMMAX64:
12906     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12907   case X86::ATOMUMIN64:
12908     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12909   case X86::ATOMUMAX64:
12910     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12911
12912   // This group does 64-bit operations on a 32-bit host.
12913   case X86::ATOMAND6432:
12914     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12915                                                X86::AND32rr, X86::AND32rr,
12916                                                X86::AND32ri, X86::AND32ri,
12917                                                false);
12918   case X86::ATOMOR6432:
12919     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12920                                                X86::OR32rr, X86::OR32rr,
12921                                                X86::OR32ri, X86::OR32ri,
12922                                                false);
12923   case X86::ATOMXOR6432:
12924     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12925                                                X86::XOR32rr, X86::XOR32rr,
12926                                                X86::XOR32ri, X86::XOR32ri,
12927                                                false);
12928   case X86::ATOMNAND6432:
12929     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12930                                                X86::AND32rr, X86::AND32rr,
12931                                                X86::AND32ri, X86::AND32ri,
12932                                                true);
12933   case X86::ATOMADD6432:
12934     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12935                                                X86::ADD32rr, X86::ADC32rr,
12936                                                X86::ADD32ri, X86::ADC32ri,
12937                                                false);
12938   case X86::ATOMSUB6432:
12939     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12940                                                X86::SUB32rr, X86::SBB32rr,
12941                                                X86::SUB32ri, X86::SBB32ri,
12942                                                false);
12943   case X86::ATOMSWAP6432:
12944     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12945                                                X86::MOV32rr, X86::MOV32rr,
12946                                                X86::MOV32ri, X86::MOV32ri,
12947                                                false);
12948   case X86::VASTART_SAVE_XMM_REGS:
12949     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12950
12951   case X86::VAARG_64:
12952     return EmitVAARG64WithCustomInserter(MI, BB);
12953   }
12954 }
12955
12956 //===----------------------------------------------------------------------===//
12957 //                           X86 Optimization Hooks
12958 //===----------------------------------------------------------------------===//
12959
12960 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12961                                                        APInt &KnownZero,
12962                                                        APInt &KnownOne,
12963                                                        const SelectionDAG &DAG,
12964                                                        unsigned Depth) const {
12965   unsigned BitWidth = KnownZero.getBitWidth();
12966   unsigned Opc = Op.getOpcode();
12967   assert((Opc >= ISD::BUILTIN_OP_END ||
12968           Opc == ISD::INTRINSIC_WO_CHAIN ||
12969           Opc == ISD::INTRINSIC_W_CHAIN ||
12970           Opc == ISD::INTRINSIC_VOID) &&
12971          "Should use MaskedValueIsZero if you don't know whether Op"
12972          " is a target node!");
12973
12974   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
12975   switch (Opc) {
12976   default: break;
12977   case X86ISD::ADD:
12978   case X86ISD::SUB:
12979   case X86ISD::ADC:
12980   case X86ISD::SBB:
12981   case X86ISD::SMUL:
12982   case X86ISD::UMUL:
12983   case X86ISD::INC:
12984   case X86ISD::DEC:
12985   case X86ISD::OR:
12986   case X86ISD::XOR:
12987   case X86ISD::AND:
12988     // These nodes' second result is a boolean.
12989     if (Op.getResNo() == 0)
12990       break;
12991     // Fallthrough
12992   case X86ISD::SETCC:
12993     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12994     break;
12995   case ISD::INTRINSIC_WO_CHAIN: {
12996     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12997     unsigned NumLoBits = 0;
12998     switch (IntId) {
12999     default: break;
13000     case Intrinsic::x86_sse_movmsk_ps:
13001     case Intrinsic::x86_avx_movmsk_ps_256:
13002     case Intrinsic::x86_sse2_movmsk_pd:
13003     case Intrinsic::x86_avx_movmsk_pd_256:
13004     case Intrinsic::x86_mmx_pmovmskb:
13005     case Intrinsic::x86_sse2_pmovmskb_128:
13006     case Intrinsic::x86_avx2_pmovmskb: {
13007       // High bits of movmskp{s|d}, pmovmskb are known zero.
13008       switch (IntId) {
13009         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13010         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13011         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13012         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13013         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13014         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13015         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13016         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13017       }
13018       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13019       break;
13020     }
13021     }
13022     break;
13023   }
13024   }
13025 }
13026
13027 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13028                                                          unsigned Depth) const {
13029   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13030   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13031     return Op.getValueType().getScalarType().getSizeInBits();
13032
13033   // Fallback case.
13034   return 1;
13035 }
13036
13037 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13038 /// node is a GlobalAddress + offset.
13039 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13040                                        const GlobalValue* &GA,
13041                                        int64_t &Offset) const {
13042   if (N->getOpcode() == X86ISD::Wrapper) {
13043     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13044       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13045       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13046       return true;
13047     }
13048   }
13049   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13050 }
13051
13052 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13053 /// same as extracting the high 128-bit part of 256-bit vector and then
13054 /// inserting the result into the low part of a new 256-bit vector
13055 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13056   EVT VT = SVOp->getValueType(0);
13057   unsigned NumElems = VT.getVectorNumElements();
13058
13059   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13060   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13061     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13062         SVOp->getMaskElt(j) >= 0)
13063       return false;
13064
13065   return true;
13066 }
13067
13068 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13069 /// same as extracting the low 128-bit part of 256-bit vector and then
13070 /// inserting the result into the high part of a new 256-bit vector
13071 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13072   EVT VT = SVOp->getValueType(0);
13073   unsigned NumElems = VT.getVectorNumElements();
13074
13075   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13076   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13077     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13078         SVOp->getMaskElt(j) >= 0)
13079       return false;
13080
13081   return true;
13082 }
13083
13084 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13085 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13086                                         TargetLowering::DAGCombinerInfo &DCI,
13087                                         const X86Subtarget* Subtarget) {
13088   DebugLoc dl = N->getDebugLoc();
13089   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13090   SDValue V1 = SVOp->getOperand(0);
13091   SDValue V2 = SVOp->getOperand(1);
13092   EVT VT = SVOp->getValueType(0);
13093   unsigned NumElems = VT.getVectorNumElements();
13094
13095   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13096       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13097     //
13098     //                   0,0,0,...
13099     //                      |
13100     //    V      UNDEF    BUILD_VECTOR    UNDEF
13101     //     \      /           \           /
13102     //  CONCAT_VECTOR         CONCAT_VECTOR
13103     //         \                  /
13104     //          \                /
13105     //          RESULT: V + zero extended
13106     //
13107     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13108         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13109         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13110       return SDValue();
13111
13112     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13113       return SDValue();
13114
13115     // To match the shuffle mask, the first half of the mask should
13116     // be exactly the first vector, and all the rest a splat with the
13117     // first element of the second one.
13118     for (unsigned i = 0; i != NumElems/2; ++i)
13119       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13120           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13121         return SDValue();
13122
13123     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13124     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13125       if (Ld->hasNUsesOfValue(1, 0)) {
13126         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13127         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13128         SDValue ResNode =
13129           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13130                                   Ld->getMemoryVT(),
13131                                   Ld->getPointerInfo(),
13132                                   Ld->getAlignment(),
13133                                   false/*isVolatile*/, true/*ReadMem*/,
13134                                   false/*WriteMem*/);
13135         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13136       }
13137     } 
13138
13139     // Emit a zeroed vector and insert the desired subvector on its
13140     // first half.
13141     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13142     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13143     return DCI.CombineTo(N, InsV);
13144   }
13145
13146   //===--------------------------------------------------------------------===//
13147   // Combine some shuffles into subvector extracts and inserts:
13148   //
13149
13150   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13151   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13152     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13153     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13154     return DCI.CombineTo(N, InsV);
13155   }
13156
13157   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13158   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13159     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13160     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13161     return DCI.CombineTo(N, InsV);
13162   }
13163
13164   return SDValue();
13165 }
13166
13167 /// PerformShuffleCombine - Performs several different shuffle combines.
13168 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13169                                      TargetLowering::DAGCombinerInfo &DCI,
13170                                      const X86Subtarget *Subtarget) {
13171   DebugLoc dl = N->getDebugLoc();
13172   EVT VT = N->getValueType(0);
13173
13174   // Don't create instructions with illegal types after legalize types has run.
13175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13176   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13177     return SDValue();
13178
13179   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13180   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13181       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13182     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13183
13184   // Only handle 128 wide vector from here on.
13185   if (VT.getSizeInBits() != 128)
13186     return SDValue();
13187
13188   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13189   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13190   // consecutive, non-overlapping, and in the right order.
13191   SmallVector<SDValue, 16> Elts;
13192   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13193     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13194
13195   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13196 }
13197
13198
13199 /// DCI, PerformTruncateCombine - Converts truncate operation to
13200 /// a sequence of vector shuffle operations.
13201 /// It is possible when we truncate 256-bit vector to 128-bit vector
13202
13203 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG, 
13204                                                   DAGCombinerInfo &DCI) const {
13205   if (!DCI.isBeforeLegalizeOps())
13206     return SDValue();
13207
13208   if (!Subtarget->hasAVX())
13209     return SDValue();
13210
13211   EVT VT = N->getValueType(0);
13212   SDValue Op = N->getOperand(0);
13213   EVT OpVT = Op.getValueType();
13214   DebugLoc dl = N->getDebugLoc();
13215
13216   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13217
13218     if (Subtarget->hasAVX2()) {
13219       // AVX2: v4i64 -> v4i32
13220
13221       // VPERMD
13222       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13223
13224       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13225       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13226                                 ShufMask);
13227
13228       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13229                          DAG.getIntPtrConstant(0));
13230     }
13231
13232     // AVX: v4i64 -> v4i32
13233     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13234                                DAG.getIntPtrConstant(0));
13235
13236     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13237                                DAG.getIntPtrConstant(2));
13238
13239     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13240     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13241
13242     // PSHUFD
13243     static const int ShufMask1[] = {0, 2, 0, 0};
13244
13245     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13246     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13247
13248     // MOVLHPS
13249     static const int ShufMask2[] = {0, 1, 4, 5};
13250
13251     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13252   }
13253
13254   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13255
13256     if (Subtarget->hasAVX2()) {
13257       // AVX2: v8i32 -> v8i16
13258
13259       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13260
13261       // PSHUFB
13262       SmallVector<SDValue,32> pshufbMask;
13263       for (unsigned i = 0; i < 2; ++i) {
13264         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13265         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13266         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13267         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13268         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13269         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13270         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13271         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13272         for (unsigned j = 0; j < 8; ++j)
13273           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13274       }
13275       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13276                                &pshufbMask[0], 32);
13277       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13278
13279       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13280
13281       static const int ShufMask[] = {0,  2,  -1,  -1};
13282       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13283                                 &ShufMask[0]);
13284
13285       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13286                        DAG.getIntPtrConstant(0));
13287
13288       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13289     }
13290
13291     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13292                                DAG.getIntPtrConstant(0));
13293
13294     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13295                                DAG.getIntPtrConstant(4));
13296
13297     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13298     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13299
13300     // PSHUFB
13301     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13302                                    -1, -1, -1, -1, -1, -1, -1, -1};
13303
13304     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13305                                 ShufMask1);
13306     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13307                                 ShufMask1);
13308
13309     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13310     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13311
13312     // MOVLHPS
13313     static const int ShufMask2[] = {0, 1, 4, 5};
13314
13315     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13316     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13317   }
13318
13319   return SDValue();
13320 }
13321
13322 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13323 /// specific shuffle of a load can be folded into a single element load.
13324 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13325 /// shuffles have been customed lowered so we need to handle those here.
13326 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13327                                          TargetLowering::DAGCombinerInfo &DCI) {
13328   if (DCI.isBeforeLegalizeOps())
13329     return SDValue();
13330
13331   SDValue InVec = N->getOperand(0);
13332   SDValue EltNo = N->getOperand(1);
13333
13334   if (!isa<ConstantSDNode>(EltNo))
13335     return SDValue();
13336
13337   EVT VT = InVec.getValueType();
13338
13339   bool HasShuffleIntoBitcast = false;
13340   if (InVec.getOpcode() == ISD::BITCAST) {
13341     // Don't duplicate a load with other uses.
13342     if (!InVec.hasOneUse())
13343       return SDValue();
13344     EVT BCVT = InVec.getOperand(0).getValueType();
13345     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13346       return SDValue();
13347     InVec = InVec.getOperand(0);
13348     HasShuffleIntoBitcast = true;
13349   }
13350
13351   if (!isTargetShuffle(InVec.getOpcode()))
13352     return SDValue();
13353
13354   // Don't duplicate a load with other uses.
13355   if (!InVec.hasOneUse())
13356     return SDValue();
13357
13358   SmallVector<int, 16> ShuffleMask;
13359   bool UnaryShuffle;
13360   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13361                             UnaryShuffle))
13362     return SDValue();
13363
13364   // Select the input vector, guarding against out of range extract vector.
13365   unsigned NumElems = VT.getVectorNumElements();
13366   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13367   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13368   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13369                                          : InVec.getOperand(1);
13370
13371   // If inputs to shuffle are the same for both ops, then allow 2 uses
13372   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13373
13374   if (LdNode.getOpcode() == ISD::BITCAST) {
13375     // Don't duplicate a load with other uses.
13376     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13377       return SDValue();
13378
13379     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13380     LdNode = LdNode.getOperand(0);
13381   }
13382
13383   if (!ISD::isNormalLoad(LdNode.getNode()))
13384     return SDValue();
13385
13386   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13387
13388   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13389     return SDValue();
13390
13391   if (HasShuffleIntoBitcast) {
13392     // If there's a bitcast before the shuffle, check if the load type and
13393     // alignment is valid.
13394     unsigned Align = LN0->getAlignment();
13395     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13396     unsigned NewAlign = TLI.getTargetData()->
13397       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13398
13399     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13400       return SDValue();
13401   }
13402
13403   // All checks match so transform back to vector_shuffle so that DAG combiner
13404   // can finish the job
13405   DebugLoc dl = N->getDebugLoc();
13406
13407   // Create shuffle node taking into account the case that its a unary shuffle
13408   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13409   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13410                                  InVec.getOperand(0), Shuffle,
13411                                  &ShuffleMask[0]);
13412   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13413   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13414                      EltNo);
13415 }
13416
13417 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13418 /// generation and convert it from being a bunch of shuffles and extracts
13419 /// to a simple store and scalar loads to extract the elements.
13420 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13421                                          TargetLowering::DAGCombinerInfo &DCI) {
13422   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13423   if (NewOp.getNode())
13424     return NewOp;
13425
13426   SDValue InputVector = N->getOperand(0);
13427
13428   // Only operate on vectors of 4 elements, where the alternative shuffling
13429   // gets to be more expensive.
13430   if (InputVector.getValueType() != MVT::v4i32)
13431     return SDValue();
13432
13433   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13434   // single use which is a sign-extend or zero-extend, and all elements are
13435   // used.
13436   SmallVector<SDNode *, 4> Uses;
13437   unsigned ExtractedElements = 0;
13438   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13439        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13440     if (UI.getUse().getResNo() != InputVector.getResNo())
13441       return SDValue();
13442
13443     SDNode *Extract = *UI;
13444     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13445       return SDValue();
13446
13447     if (Extract->getValueType(0) != MVT::i32)
13448       return SDValue();
13449     if (!Extract->hasOneUse())
13450       return SDValue();
13451     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13452         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13453       return SDValue();
13454     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13455       return SDValue();
13456
13457     // Record which element was extracted.
13458     ExtractedElements |=
13459       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13460
13461     Uses.push_back(Extract);
13462   }
13463
13464   // If not all the elements were used, this may not be worthwhile.
13465   if (ExtractedElements != 15)
13466     return SDValue();
13467
13468   // Ok, we've now decided to do the transformation.
13469   DebugLoc dl = InputVector.getDebugLoc();
13470
13471   // Store the value to a temporary stack slot.
13472   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13473   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13474                             MachinePointerInfo(), false, false, 0);
13475
13476   // Replace each use (extract) with a load of the appropriate element.
13477   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13478        UE = Uses.end(); UI != UE; ++UI) {
13479     SDNode *Extract = *UI;
13480
13481     // cOMpute the element's address.
13482     SDValue Idx = Extract->getOperand(1);
13483     unsigned EltSize =
13484         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13485     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13486     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13487     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13488
13489     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13490                                      StackPtr, OffsetVal);
13491
13492     // Load the scalar.
13493     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13494                                      ScalarAddr, MachinePointerInfo(),
13495                                      false, false, false, 0);
13496
13497     // Replace the exact with the load.
13498     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13499   }
13500
13501   // The replacement was made in place; don't return anything.
13502   return SDValue();
13503 }
13504
13505 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13506 /// nodes.
13507 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13508                                     TargetLowering::DAGCombinerInfo &DCI,
13509                                     const X86Subtarget *Subtarget) {
13510
13511
13512   DebugLoc DL = N->getDebugLoc();
13513   SDValue Cond = N->getOperand(0);
13514   // Get the LHS/RHS of the select.
13515   SDValue LHS = N->getOperand(1);
13516   SDValue RHS = N->getOperand(2);
13517   EVT VT = LHS.getValueType();
13518
13519   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13520   // instructions match the semantics of the common C idiom x<y?x:y but not
13521   // x<=y?x:y, because of how they handle negative zero (which can be
13522   // ignored in unsafe-math mode).
13523   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13524       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13525       (Subtarget->hasSSE2() ||
13526        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13527     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13528
13529     unsigned Opcode = 0;
13530     // Check for x CC y ? x : y.
13531     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13532         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13533       switch (CC) {
13534       default: break;
13535       case ISD::SETULT:
13536         // Converting this to a min would handle NaNs incorrectly, and swapping
13537         // the operands would cause it to handle comparisons between positive
13538         // and negative zero incorrectly.
13539         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13540           if (!DAG.getTarget().Options.UnsafeFPMath &&
13541               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13542             break;
13543           std::swap(LHS, RHS);
13544         }
13545         Opcode = X86ISD::FMIN;
13546         break;
13547       case ISD::SETOLE:
13548         // Converting this to a min would handle comparisons between positive
13549         // and negative zero incorrectly.
13550         if (!DAG.getTarget().Options.UnsafeFPMath &&
13551             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13552           break;
13553         Opcode = X86ISD::FMIN;
13554         break;
13555       case ISD::SETULE:
13556         // Converting this to a min would handle both negative zeros and NaNs
13557         // incorrectly, but we can swap the operands to fix both.
13558         std::swap(LHS, RHS);
13559       case ISD::SETOLT:
13560       case ISD::SETLT:
13561       case ISD::SETLE:
13562         Opcode = X86ISD::FMIN;
13563         break;
13564
13565       case ISD::SETOGE:
13566         // Converting this to a max would handle comparisons between positive
13567         // and negative zero incorrectly.
13568         if (!DAG.getTarget().Options.UnsafeFPMath &&
13569             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13570           break;
13571         Opcode = X86ISD::FMAX;
13572         break;
13573       case ISD::SETUGT:
13574         // Converting this to a max would handle NaNs incorrectly, and swapping
13575         // the operands would cause it to handle comparisons between positive
13576         // and negative zero incorrectly.
13577         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13578           if (!DAG.getTarget().Options.UnsafeFPMath &&
13579               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13580             break;
13581           std::swap(LHS, RHS);
13582         }
13583         Opcode = X86ISD::FMAX;
13584         break;
13585       case ISD::SETUGE:
13586         // Converting this to a max would handle both negative zeros and NaNs
13587         // incorrectly, but we can swap the operands to fix both.
13588         std::swap(LHS, RHS);
13589       case ISD::SETOGT:
13590       case ISD::SETGT:
13591       case ISD::SETGE:
13592         Opcode = X86ISD::FMAX;
13593         break;
13594       }
13595     // Check for x CC y ? y : x -- a min/max with reversed arms.
13596     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13597                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13598       switch (CC) {
13599       default: break;
13600       case ISD::SETOGE:
13601         // Converting this to a min would handle comparisons between positive
13602         // and negative zero incorrectly, and swapping the operands would
13603         // cause it to handle NaNs incorrectly.
13604         if (!DAG.getTarget().Options.UnsafeFPMath &&
13605             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13606           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13607             break;
13608           std::swap(LHS, RHS);
13609         }
13610         Opcode = X86ISD::FMIN;
13611         break;
13612       case ISD::SETUGT:
13613         // Converting this to a min would handle NaNs incorrectly.
13614         if (!DAG.getTarget().Options.UnsafeFPMath &&
13615             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13616           break;
13617         Opcode = X86ISD::FMIN;
13618         break;
13619       case ISD::SETUGE:
13620         // Converting this to a min would handle both negative zeros and NaNs
13621         // incorrectly, but we can swap the operands to fix both.
13622         std::swap(LHS, RHS);
13623       case ISD::SETOGT:
13624       case ISD::SETGT:
13625       case ISD::SETGE:
13626         Opcode = X86ISD::FMIN;
13627         break;
13628
13629       case ISD::SETULT:
13630         // Converting this to a max would handle NaNs incorrectly.
13631         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13632           break;
13633         Opcode = X86ISD::FMAX;
13634         break;
13635       case ISD::SETOLE:
13636         // Converting this to a max would handle comparisons between positive
13637         // and negative zero incorrectly, and swapping the operands would
13638         // cause it to handle NaNs incorrectly.
13639         if (!DAG.getTarget().Options.UnsafeFPMath &&
13640             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13641           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13642             break;
13643           std::swap(LHS, RHS);
13644         }
13645         Opcode = X86ISD::FMAX;
13646         break;
13647       case ISD::SETULE:
13648         // Converting this to a max would handle both negative zeros and NaNs
13649         // incorrectly, but we can swap the operands to fix both.
13650         std::swap(LHS, RHS);
13651       case ISD::SETOLT:
13652       case ISD::SETLT:
13653       case ISD::SETLE:
13654         Opcode = X86ISD::FMAX;
13655         break;
13656       }
13657     }
13658
13659     if (Opcode)
13660       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13661   }
13662
13663   // If this is a select between two integer constants, try to do some
13664   // optimizations.
13665   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13666     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13667       // Don't do this for crazy integer types.
13668       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13669         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13670         // so that TrueC (the true value) is larger than FalseC.
13671         bool NeedsCondInvert = false;
13672
13673         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13674             // Efficiently invertible.
13675             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13676              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13677               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13678           NeedsCondInvert = true;
13679           std::swap(TrueC, FalseC);
13680         }
13681
13682         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13683         if (FalseC->getAPIntValue() == 0 &&
13684             TrueC->getAPIntValue().isPowerOf2()) {
13685           if (NeedsCondInvert) // Invert the condition if needed.
13686             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13687                                DAG.getConstant(1, Cond.getValueType()));
13688
13689           // Zero extend the condition if needed.
13690           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13691
13692           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13693           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13694                              DAG.getConstant(ShAmt, MVT::i8));
13695         }
13696
13697         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13698         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13699           if (NeedsCondInvert) // Invert the condition if needed.
13700             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13701                                DAG.getConstant(1, Cond.getValueType()));
13702
13703           // Zero extend the condition if needed.
13704           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13705                              FalseC->getValueType(0), Cond);
13706           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13707                              SDValue(FalseC, 0));
13708         }
13709
13710         // Optimize cases that will turn into an LEA instruction.  This requires
13711         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13712         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13713           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13714           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13715
13716           bool isFastMultiplier = false;
13717           if (Diff < 10) {
13718             switch ((unsigned char)Diff) {
13719               default: break;
13720               case 1:  // result = add base, cond
13721               case 2:  // result = lea base(    , cond*2)
13722               case 3:  // result = lea base(cond, cond*2)
13723               case 4:  // result = lea base(    , cond*4)
13724               case 5:  // result = lea base(cond, cond*4)
13725               case 8:  // result = lea base(    , cond*8)
13726               case 9:  // result = lea base(cond, cond*8)
13727                 isFastMultiplier = true;
13728                 break;
13729             }
13730           }
13731
13732           if (isFastMultiplier) {
13733             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13734             if (NeedsCondInvert) // Invert the condition if needed.
13735               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13736                                  DAG.getConstant(1, Cond.getValueType()));
13737
13738             // Zero extend the condition if needed.
13739             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13740                                Cond);
13741             // Scale the condition by the difference.
13742             if (Diff != 1)
13743               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13744                                  DAG.getConstant(Diff, Cond.getValueType()));
13745
13746             // Add the base if non-zero.
13747             if (FalseC->getAPIntValue() != 0)
13748               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13749                                  SDValue(FalseC, 0));
13750             return Cond;
13751           }
13752         }
13753       }
13754   }
13755
13756   // Canonicalize max and min:
13757   // (x > y) ? x : y -> (x >= y) ? x : y
13758   // (x < y) ? x : y -> (x <= y) ? x : y
13759   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13760   // the need for an extra compare
13761   // against zero. e.g.
13762   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13763   // subl   %esi, %edi
13764   // testl  %edi, %edi
13765   // movl   $0, %eax
13766   // cmovgl %edi, %eax
13767   // =>
13768   // xorl   %eax, %eax
13769   // subl   %esi, $edi
13770   // cmovsl %eax, %edi
13771   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13772       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13773       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13774     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13775     switch (CC) {
13776     default: break;
13777     case ISD::SETLT:
13778     case ISD::SETGT: {
13779       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13780       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13781                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13782       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13783     }
13784     }
13785   }
13786
13787   // If we know that this node is legal then we know that it is going to be
13788   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13789   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13790   // to simplify previous instructions.
13791   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13792   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13793       !DCI.isBeforeLegalize() &&
13794       TLI.isOperationLegal(ISD::VSELECT, VT)) {
13795     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13796     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13797     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13798
13799     APInt KnownZero, KnownOne;
13800     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13801                                           DCI.isBeforeLegalizeOps());
13802     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13803         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13804       DCI.CommitTargetLoweringOpt(TLO);
13805   }
13806
13807   return SDValue();
13808 }
13809
13810 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13811 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13812                                   TargetLowering::DAGCombinerInfo &DCI) {
13813   DebugLoc DL = N->getDebugLoc();
13814
13815   // If the flag operand isn't dead, don't touch this CMOV.
13816   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13817     return SDValue();
13818
13819   SDValue FalseOp = N->getOperand(0);
13820   SDValue TrueOp = N->getOperand(1);
13821   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13822   SDValue Cond = N->getOperand(3);
13823   if (CC == X86::COND_E || CC == X86::COND_NE) {
13824     switch (Cond.getOpcode()) {
13825     default: break;
13826     case X86ISD::BSR:
13827     case X86ISD::BSF:
13828       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13829       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13830         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13831     }
13832   }
13833
13834   // If this is a select between two integer constants, try to do some
13835   // optimizations.  Note that the operands are ordered the opposite of SELECT
13836   // operands.
13837   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13838     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13839       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13840       // larger than FalseC (the false value).
13841       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13842         CC = X86::GetOppositeBranchCondition(CC);
13843         std::swap(TrueC, FalseC);
13844       }
13845
13846       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13847       // This is efficient for any integer data type (including i8/i16) and
13848       // shift amount.
13849       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13850         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13851                            DAG.getConstant(CC, MVT::i8), Cond);
13852
13853         // Zero extend the condition if needed.
13854         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13855
13856         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13857         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13858                            DAG.getConstant(ShAmt, MVT::i8));
13859         if (N->getNumValues() == 2)  // Dead flag value?
13860           return DCI.CombineTo(N, Cond, SDValue());
13861         return Cond;
13862       }
13863
13864       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13865       // for any integer data type, including i8/i16.
13866       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13867         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13868                            DAG.getConstant(CC, MVT::i8), Cond);
13869
13870         // Zero extend the condition if needed.
13871         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13872                            FalseC->getValueType(0), Cond);
13873         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13874                            SDValue(FalseC, 0));
13875
13876         if (N->getNumValues() == 2)  // Dead flag value?
13877           return DCI.CombineTo(N, Cond, SDValue());
13878         return Cond;
13879       }
13880
13881       // Optimize cases that will turn into an LEA instruction.  This requires
13882       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13883       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13884         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13885         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13886
13887         bool isFastMultiplier = false;
13888         if (Diff < 10) {
13889           switch ((unsigned char)Diff) {
13890           default: break;
13891           case 1:  // result = add base, cond
13892           case 2:  // result = lea base(    , cond*2)
13893           case 3:  // result = lea base(cond, cond*2)
13894           case 4:  // result = lea base(    , cond*4)
13895           case 5:  // result = lea base(cond, cond*4)
13896           case 8:  // result = lea base(    , cond*8)
13897           case 9:  // result = lea base(cond, cond*8)
13898             isFastMultiplier = true;
13899             break;
13900           }
13901         }
13902
13903         if (isFastMultiplier) {
13904           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13905           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13906                              DAG.getConstant(CC, MVT::i8), Cond);
13907           // Zero extend the condition if needed.
13908           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13909                              Cond);
13910           // Scale the condition by the difference.
13911           if (Diff != 1)
13912             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13913                                DAG.getConstant(Diff, Cond.getValueType()));
13914
13915           // Add the base if non-zero.
13916           if (FalseC->getAPIntValue() != 0)
13917             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13918                                SDValue(FalseC, 0));
13919           if (N->getNumValues() == 2)  // Dead flag value?
13920             return DCI.CombineTo(N, Cond, SDValue());
13921           return Cond;
13922         }
13923       }
13924     }
13925   }
13926   return SDValue();
13927 }
13928
13929
13930 /// PerformMulCombine - Optimize a single multiply with constant into two
13931 /// in order to implement it with two cheaper instructions, e.g.
13932 /// LEA + SHL, LEA + LEA.
13933 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13934                                  TargetLowering::DAGCombinerInfo &DCI) {
13935   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13936     return SDValue();
13937
13938   EVT VT = N->getValueType(0);
13939   if (VT != MVT::i64)
13940     return SDValue();
13941
13942   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13943   if (!C)
13944     return SDValue();
13945   uint64_t MulAmt = C->getZExtValue();
13946   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13947     return SDValue();
13948
13949   uint64_t MulAmt1 = 0;
13950   uint64_t MulAmt2 = 0;
13951   if ((MulAmt % 9) == 0) {
13952     MulAmt1 = 9;
13953     MulAmt2 = MulAmt / 9;
13954   } else if ((MulAmt % 5) == 0) {
13955     MulAmt1 = 5;
13956     MulAmt2 = MulAmt / 5;
13957   } else if ((MulAmt % 3) == 0) {
13958     MulAmt1 = 3;
13959     MulAmt2 = MulAmt / 3;
13960   }
13961   if (MulAmt2 &&
13962       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13963     DebugLoc DL = N->getDebugLoc();
13964
13965     if (isPowerOf2_64(MulAmt2) &&
13966         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13967       // If second multiplifer is pow2, issue it first. We want the multiply by
13968       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13969       // is an add.
13970       std::swap(MulAmt1, MulAmt2);
13971
13972     SDValue NewMul;
13973     if (isPowerOf2_64(MulAmt1))
13974       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13975                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13976     else
13977       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13978                            DAG.getConstant(MulAmt1, VT));
13979
13980     if (isPowerOf2_64(MulAmt2))
13981       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13982                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13983     else
13984       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13985                            DAG.getConstant(MulAmt2, VT));
13986
13987     // Do not add new nodes to DAG combiner worklist.
13988     DCI.CombineTo(N, NewMul, false);
13989   }
13990   return SDValue();
13991 }
13992
13993 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13994   SDValue N0 = N->getOperand(0);
13995   SDValue N1 = N->getOperand(1);
13996   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13997   EVT VT = N0.getValueType();
13998
13999   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14000   // since the result of setcc_c is all zero's or all ones.
14001   if (VT.isInteger() && !VT.isVector() &&
14002       N1C && N0.getOpcode() == ISD::AND &&
14003       N0.getOperand(1).getOpcode() == ISD::Constant) {
14004     SDValue N00 = N0.getOperand(0);
14005     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14006         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14007           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14008          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14009       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14010       APInt ShAmt = N1C->getAPIntValue();
14011       Mask = Mask.shl(ShAmt);
14012       if (Mask != 0)
14013         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14014                            N00, DAG.getConstant(Mask, VT));
14015     }
14016   }
14017
14018
14019   // Hardware support for vector shifts is sparse which makes us scalarize the
14020   // vector operations in many cases. Also, on sandybridge ADD is faster than
14021   // shl.
14022   // (shl V, 1) -> add V,V
14023   if (isSplatVector(N1.getNode())) {
14024     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14025     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14026     // We shift all of the values by one. In many cases we do not have
14027     // hardware support for this operation. This is better expressed as an ADD
14028     // of two values.
14029     if (N1C && (1 == N1C->getZExtValue())) {
14030       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14031     }
14032   }
14033
14034   return SDValue();
14035 }
14036
14037 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14038 ///                       when possible.
14039 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14040                                    TargetLowering::DAGCombinerInfo &DCI,
14041                                    const X86Subtarget *Subtarget) {
14042   EVT VT = N->getValueType(0);
14043   if (N->getOpcode() == ISD::SHL) {
14044     SDValue V = PerformSHLCombine(N, DAG);
14045     if (V.getNode()) return V;
14046   }
14047
14048   // On X86 with SSE2 support, we can transform this to a vector shift if
14049   // all elements are shifted by the same amount.  We can't do this in legalize
14050   // because the a constant vector is typically transformed to a constant pool
14051   // so we have no knowledge of the shift amount.
14052   if (!Subtarget->hasSSE2())
14053     return SDValue();
14054
14055   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14056       (!Subtarget->hasAVX2() ||
14057        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14058     return SDValue();
14059
14060   SDValue ShAmtOp = N->getOperand(1);
14061   EVT EltVT = VT.getVectorElementType();
14062   DebugLoc DL = N->getDebugLoc();
14063   SDValue BaseShAmt = SDValue();
14064   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14065     unsigned NumElts = VT.getVectorNumElements();
14066     unsigned i = 0;
14067     for (; i != NumElts; ++i) {
14068       SDValue Arg = ShAmtOp.getOperand(i);
14069       if (Arg.getOpcode() == ISD::UNDEF) continue;
14070       BaseShAmt = Arg;
14071       break;
14072     }
14073     // Handle the case where the build_vector is all undef
14074     // FIXME: Should DAG allow this?
14075     if (i == NumElts)
14076       return SDValue();
14077
14078     for (; i != NumElts; ++i) {
14079       SDValue Arg = ShAmtOp.getOperand(i);
14080       if (Arg.getOpcode() == ISD::UNDEF) continue;
14081       if (Arg != BaseShAmt) {
14082         return SDValue();
14083       }
14084     }
14085   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14086              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14087     SDValue InVec = ShAmtOp.getOperand(0);
14088     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14089       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14090       unsigned i = 0;
14091       for (; i != NumElts; ++i) {
14092         SDValue Arg = InVec.getOperand(i);
14093         if (Arg.getOpcode() == ISD::UNDEF) continue;
14094         BaseShAmt = Arg;
14095         break;
14096       }
14097     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14098        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14099          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14100          if (C->getZExtValue() == SplatIdx)
14101            BaseShAmt = InVec.getOperand(1);
14102        }
14103     }
14104     if (BaseShAmt.getNode() == 0) {
14105       // Don't create instructions with illegal types after legalize
14106       // types has run.
14107       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14108           !DCI.isBeforeLegalize())
14109         return SDValue();
14110
14111       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14112                               DAG.getIntPtrConstant(0));
14113     }
14114   } else
14115     return SDValue();
14116
14117   // The shift amount is an i32.
14118   if (EltVT.bitsGT(MVT::i32))
14119     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14120   else if (EltVT.bitsLT(MVT::i32))
14121     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14122
14123   // The shift amount is identical so we can do a vector shift.
14124   SDValue  ValOp = N->getOperand(0);
14125   switch (N->getOpcode()) {
14126   default:
14127     llvm_unreachable("Unknown shift opcode!");
14128   case ISD::SHL:
14129     switch (VT.getSimpleVT().SimpleTy) {
14130     default: return SDValue();
14131     case MVT::v2i64:
14132     case MVT::v4i32:
14133     case MVT::v8i16:
14134     case MVT::v4i64:
14135     case MVT::v8i32:
14136     case MVT::v16i16:
14137       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14138     }
14139   case ISD::SRA:
14140     switch (VT.getSimpleVT().SimpleTy) {
14141     default: return SDValue();
14142     case MVT::v4i32:
14143     case MVT::v8i16:
14144     case MVT::v8i32:
14145     case MVT::v16i16:
14146       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14147     }
14148   case ISD::SRL:
14149     switch (VT.getSimpleVT().SimpleTy) {
14150     default: return SDValue();
14151     case MVT::v2i64:
14152     case MVT::v4i32:
14153     case MVT::v8i16:
14154     case MVT::v4i64:
14155     case MVT::v8i32:
14156     case MVT::v16i16:
14157       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14158     }
14159   }
14160 }
14161
14162
14163 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14164 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14165 // and friends.  Likewise for OR -> CMPNEQSS.
14166 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14167                             TargetLowering::DAGCombinerInfo &DCI,
14168                             const X86Subtarget *Subtarget) {
14169   unsigned opcode;
14170
14171   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14172   // we're requiring SSE2 for both.
14173   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14174     SDValue N0 = N->getOperand(0);
14175     SDValue N1 = N->getOperand(1);
14176     SDValue CMP0 = N0->getOperand(1);
14177     SDValue CMP1 = N1->getOperand(1);
14178     DebugLoc DL = N->getDebugLoc();
14179
14180     // The SETCCs should both refer to the same CMP.
14181     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14182       return SDValue();
14183
14184     SDValue CMP00 = CMP0->getOperand(0);
14185     SDValue CMP01 = CMP0->getOperand(1);
14186     EVT     VT    = CMP00.getValueType();
14187
14188     if (VT == MVT::f32 || VT == MVT::f64) {
14189       bool ExpectingFlags = false;
14190       // Check for any users that want flags:
14191       for (SDNode::use_iterator UI = N->use_begin(),
14192              UE = N->use_end();
14193            !ExpectingFlags && UI != UE; ++UI)
14194         switch (UI->getOpcode()) {
14195         default:
14196         case ISD::BR_CC:
14197         case ISD::BRCOND:
14198         case ISD::SELECT:
14199           ExpectingFlags = true;
14200           break;
14201         case ISD::CopyToReg:
14202         case ISD::SIGN_EXTEND:
14203         case ISD::ZERO_EXTEND:
14204         case ISD::ANY_EXTEND:
14205           break;
14206         }
14207
14208       if (!ExpectingFlags) {
14209         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14210         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14211
14212         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14213           X86::CondCode tmp = cc0;
14214           cc0 = cc1;
14215           cc1 = tmp;
14216         }
14217
14218         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14219             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14220           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14221           X86ISD::NodeType NTOperator = is64BitFP ?
14222             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14223           // FIXME: need symbolic constants for these magic numbers.
14224           // See X86ATTInstPrinter.cpp:printSSECC().
14225           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14226           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14227                                               DAG.getConstant(x86cc, MVT::i8));
14228           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14229                                               OnesOrZeroesF);
14230           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14231                                       DAG.getConstant(1, MVT::i32));
14232           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14233           return OneBitOfTruth;
14234         }
14235       }
14236     }
14237   }
14238   return SDValue();
14239 }
14240
14241 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14242 /// so it can be folded inside ANDNP.
14243 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14244   EVT VT = N->getValueType(0);
14245
14246   // Match direct AllOnes for 128 and 256-bit vectors
14247   if (ISD::isBuildVectorAllOnes(N))
14248     return true;
14249
14250   // Look through a bit convert.
14251   if (N->getOpcode() == ISD::BITCAST)
14252     N = N->getOperand(0).getNode();
14253
14254   // Sometimes the operand may come from a insert_subvector building a 256-bit
14255   // allones vector
14256   if (VT.getSizeInBits() == 256 &&
14257       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14258     SDValue V1 = N->getOperand(0);
14259     SDValue V2 = N->getOperand(1);
14260
14261     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14262         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14263         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14264         ISD::isBuildVectorAllOnes(V2.getNode()))
14265       return true;
14266   }
14267
14268   return false;
14269 }
14270
14271 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14272                                  TargetLowering::DAGCombinerInfo &DCI,
14273                                  const X86Subtarget *Subtarget) {
14274   if (DCI.isBeforeLegalizeOps())
14275     return SDValue();
14276
14277   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14278   if (R.getNode())
14279     return R;
14280
14281   EVT VT = N->getValueType(0);
14282
14283   // Create ANDN, BLSI, and BLSR instructions
14284   // BLSI is X & (-X)
14285   // BLSR is X & (X-1)
14286   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14287     SDValue N0 = N->getOperand(0);
14288     SDValue N1 = N->getOperand(1);
14289     DebugLoc DL = N->getDebugLoc();
14290
14291     // Check LHS for not
14292     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14293       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14294     // Check RHS for not
14295     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14296       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14297
14298     // Check LHS for neg
14299     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14300         isZero(N0.getOperand(0)))
14301       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14302
14303     // Check RHS for neg
14304     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14305         isZero(N1.getOperand(0)))
14306       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14307
14308     // Check LHS for X-1
14309     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14310         isAllOnes(N0.getOperand(1)))
14311       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14312
14313     // Check RHS for X-1
14314     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14315         isAllOnes(N1.getOperand(1)))
14316       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14317
14318     return SDValue();
14319   }
14320
14321   // Want to form ANDNP nodes:
14322   // 1) In the hopes of then easily combining them with OR and AND nodes
14323   //    to form PBLEND/PSIGN.
14324   // 2) To match ANDN packed intrinsics
14325   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14326     return SDValue();
14327
14328   SDValue N0 = N->getOperand(0);
14329   SDValue N1 = N->getOperand(1);
14330   DebugLoc DL = N->getDebugLoc();
14331
14332   // Check LHS for vnot
14333   if (N0.getOpcode() == ISD::XOR &&
14334       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14335       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14336     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14337
14338   // Check RHS for vnot
14339   if (N1.getOpcode() == ISD::XOR &&
14340       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14341       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14342     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14343
14344   return SDValue();
14345 }
14346
14347 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14348                                 TargetLowering::DAGCombinerInfo &DCI,
14349                                 const X86Subtarget *Subtarget) {
14350   if (DCI.isBeforeLegalizeOps())
14351     return SDValue();
14352
14353   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14354   if (R.getNode())
14355     return R;
14356
14357   EVT VT = N->getValueType(0);
14358
14359   SDValue N0 = N->getOperand(0);
14360   SDValue N1 = N->getOperand(1);
14361
14362   // look for psign/blend
14363   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14364     if (!Subtarget->hasSSSE3() ||
14365         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14366       return SDValue();
14367
14368     // Canonicalize pandn to RHS
14369     if (N0.getOpcode() == X86ISD::ANDNP)
14370       std::swap(N0, N1);
14371     // or (and (m, y), (pandn m, x))
14372     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14373       SDValue Mask = N1.getOperand(0);
14374       SDValue X    = N1.getOperand(1);
14375       SDValue Y;
14376       if (N0.getOperand(0) == Mask)
14377         Y = N0.getOperand(1);
14378       if (N0.getOperand(1) == Mask)
14379         Y = N0.getOperand(0);
14380
14381       // Check to see if the mask appeared in both the AND and ANDNP and
14382       if (!Y.getNode())
14383         return SDValue();
14384
14385       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14386       // Look through mask bitcast.
14387       if (Mask.getOpcode() == ISD::BITCAST)
14388         Mask = Mask.getOperand(0);
14389       if (X.getOpcode() == ISD::BITCAST)
14390         X = X.getOperand(0);
14391       if (Y.getOpcode() == ISD::BITCAST)
14392         Y = Y.getOperand(0);
14393
14394       EVT MaskVT = Mask.getValueType();
14395
14396       // Validate that the Mask operand is a vector sra node.
14397       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14398       // there is no psrai.b
14399       if (Mask.getOpcode() != X86ISD::VSRAI)
14400         return SDValue();
14401
14402       // Check that the SRA is all signbits.
14403       SDValue SraC = Mask.getOperand(1);
14404       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14405       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14406       if ((SraAmt + 1) != EltBits)
14407         return SDValue();
14408
14409       DebugLoc DL = N->getDebugLoc();
14410
14411       // Now we know we at least have a plendvb with the mask val.  See if
14412       // we can form a psignb/w/d.
14413       // psign = x.type == y.type == mask.type && y = sub(0, x);
14414       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14415           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14416           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14417         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14418                "Unsupported VT for PSIGN");
14419         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14420         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14421       }
14422       // PBLENDVB only available on SSE 4.1
14423       if (!Subtarget->hasSSE41())
14424         return SDValue();
14425
14426       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14427
14428       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14429       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14430       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14431       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14432       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14433     }
14434   }
14435
14436   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14437     return SDValue();
14438
14439   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14440   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14441     std::swap(N0, N1);
14442   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14443     return SDValue();
14444   if (!N0.hasOneUse() || !N1.hasOneUse())
14445     return SDValue();
14446
14447   SDValue ShAmt0 = N0.getOperand(1);
14448   if (ShAmt0.getValueType() != MVT::i8)
14449     return SDValue();
14450   SDValue ShAmt1 = N1.getOperand(1);
14451   if (ShAmt1.getValueType() != MVT::i8)
14452     return SDValue();
14453   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14454     ShAmt0 = ShAmt0.getOperand(0);
14455   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14456     ShAmt1 = ShAmt1.getOperand(0);
14457
14458   DebugLoc DL = N->getDebugLoc();
14459   unsigned Opc = X86ISD::SHLD;
14460   SDValue Op0 = N0.getOperand(0);
14461   SDValue Op1 = N1.getOperand(0);
14462   if (ShAmt0.getOpcode() == ISD::SUB) {
14463     Opc = X86ISD::SHRD;
14464     std::swap(Op0, Op1);
14465     std::swap(ShAmt0, ShAmt1);
14466   }
14467
14468   unsigned Bits = VT.getSizeInBits();
14469   if (ShAmt1.getOpcode() == ISD::SUB) {
14470     SDValue Sum = ShAmt1.getOperand(0);
14471     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14472       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14473       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14474         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14475       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14476         return DAG.getNode(Opc, DL, VT,
14477                            Op0, Op1,
14478                            DAG.getNode(ISD::TRUNCATE, DL,
14479                                        MVT::i8, ShAmt0));
14480     }
14481   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14482     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14483     if (ShAmt0C &&
14484         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14485       return DAG.getNode(Opc, DL, VT,
14486                          N0.getOperand(0), N1.getOperand(0),
14487                          DAG.getNode(ISD::TRUNCATE, DL,
14488                                        MVT::i8, ShAmt0));
14489   }
14490
14491   return SDValue();
14492 }
14493
14494 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14495 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14496                                  TargetLowering::DAGCombinerInfo &DCI,
14497                                  const X86Subtarget *Subtarget) {
14498   if (DCI.isBeforeLegalizeOps())
14499     return SDValue();
14500
14501   EVT VT = N->getValueType(0);
14502
14503   if (VT != MVT::i32 && VT != MVT::i64)
14504     return SDValue();
14505
14506   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14507
14508   // Create BLSMSK instructions by finding X ^ (X-1)
14509   SDValue N0 = N->getOperand(0);
14510   SDValue N1 = N->getOperand(1);
14511   DebugLoc DL = N->getDebugLoc();
14512
14513   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14514       isAllOnes(N0.getOperand(1)))
14515     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14516
14517   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14518       isAllOnes(N1.getOperand(1)))
14519     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14520
14521   return SDValue();
14522 }
14523
14524 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14525 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14526                                    const X86Subtarget *Subtarget) {
14527   LoadSDNode *Ld = cast<LoadSDNode>(N);
14528   EVT RegVT = Ld->getValueType(0);
14529   EVT MemVT = Ld->getMemoryVT();
14530   DebugLoc dl = Ld->getDebugLoc();
14531   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14532
14533   ISD::LoadExtType Ext = Ld->getExtensionType();
14534
14535   // If this is a vector EXT Load then attempt to optimize it using a
14536   // shuffle. We need SSE4 for the shuffles.
14537   // TODO: It is possible to support ZExt by zeroing the undef values
14538   // during the shuffle phase or after the shuffle.
14539   if (RegVT.isVector() && RegVT.isInteger() &&
14540       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14541     assert(MemVT != RegVT && "Cannot extend to the same type");
14542     assert(MemVT.isVector() && "Must load a vector from memory");
14543
14544     unsigned NumElems = RegVT.getVectorNumElements();
14545     unsigned RegSz = RegVT.getSizeInBits();
14546     unsigned MemSz = MemVT.getSizeInBits();
14547     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14548     // All sizes must be a power of two
14549     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14550
14551     // Attempt to load the original value using a single load op.
14552     // Find a scalar type which is equal to the loaded word size.
14553     MVT SclrLoadTy = MVT::i8;
14554     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14555          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14556       MVT Tp = (MVT::SimpleValueType)tp;
14557       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
14558         SclrLoadTy = Tp;
14559         break;
14560       }
14561     }
14562
14563     // Proceed if a load word is found.
14564     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14565
14566     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14567       RegSz/SclrLoadTy.getSizeInBits());
14568
14569     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14570                                   RegSz/MemVT.getScalarType().getSizeInBits());
14571     // Can't shuffle using an illegal type.
14572     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14573
14574     // Perform a single load.
14575     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14576                                   Ld->getBasePtr(),
14577                                   Ld->getPointerInfo(), Ld->isVolatile(),
14578                                   Ld->isNonTemporal(), Ld->isInvariant(),
14579                                   Ld->getAlignment());
14580
14581     // Insert the word loaded into a vector.
14582     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14583       LoadUnitVecVT, ScalarLoad);
14584
14585     // Bitcast the loaded value to a vector of the original element type, in
14586     // the size of the target vector type.
14587     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT,
14588                                     ScalarInVector);
14589     unsigned SizeRatio = RegSz/MemSz;
14590
14591     // Redistribute the loaded elements into the different locations.
14592     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14593     for (unsigned i = 0; i != NumElems; ++i)
14594       ShuffleVec[i*SizeRatio] = i;
14595
14596     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14597                                          DAG.getUNDEF(WideVecVT),
14598                                          &ShuffleVec[0]);
14599
14600     // Bitcast to the requested type.
14601     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14602     // Replace the original load with the new sequence
14603     // and return the new chain.
14604     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14605     return SDValue(ScalarLoad.getNode(), 1);
14606   }
14607
14608   return SDValue();
14609 }
14610
14611 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14612 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14613                                    const X86Subtarget *Subtarget) {
14614   StoreSDNode *St = cast<StoreSDNode>(N);
14615   EVT VT = St->getValue().getValueType();
14616   EVT StVT = St->getMemoryVT();
14617   DebugLoc dl = St->getDebugLoc();
14618   SDValue StoredVal = St->getOperand(1);
14619   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14620
14621   // If we are saving a concatenation of two XMM registers, perform two stores.
14622   // On Sandy Bridge, 256-bit memory operations are executed by two
14623   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14624   // memory  operation.
14625   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2() &&
14626       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14627       StoredVal.getNumOperands() == 2) {
14628     SDValue Value0 = StoredVal.getOperand(0);
14629     SDValue Value1 = StoredVal.getOperand(1);
14630
14631     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14632     SDValue Ptr0 = St->getBasePtr();
14633     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14634
14635     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14636                                 St->getPointerInfo(), St->isVolatile(),
14637                                 St->isNonTemporal(), St->getAlignment());
14638     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14639                                 St->getPointerInfo(), St->isVolatile(),
14640                                 St->isNonTemporal(), St->getAlignment());
14641     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14642   }
14643
14644   // Optimize trunc store (of multiple scalars) to shuffle and store.
14645   // First, pack all of the elements in one place. Next, store to memory
14646   // in fewer chunks.
14647   if (St->isTruncatingStore() && VT.isVector()) {
14648     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14649     unsigned NumElems = VT.getVectorNumElements();
14650     assert(StVT != VT && "Cannot truncate to the same type");
14651     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14652     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14653
14654     // From, To sizes and ElemCount must be pow of two
14655     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14656     // We are going to use the original vector elt for storing.
14657     // Accumulated smaller vector elements must be a multiple of the store size.
14658     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14659
14660     unsigned SizeRatio  = FromSz / ToSz;
14661
14662     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14663
14664     // Create a type on which we perform the shuffle
14665     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14666             StVT.getScalarType(), NumElems*SizeRatio);
14667
14668     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14669
14670     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14671     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14672     for (unsigned i = 0; i != NumElems; ++i)
14673       ShuffleVec[i] = i * SizeRatio;
14674
14675     // Can't shuffle using an illegal type
14676     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14677
14678     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14679                                          DAG.getUNDEF(WideVecVT),
14680                                          &ShuffleVec[0]);
14681     // At this point all of the data is stored at the bottom of the
14682     // register. We now need to save it to mem.
14683
14684     // Find the largest store unit
14685     MVT StoreType = MVT::i8;
14686     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14687          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14688       MVT Tp = (MVT::SimpleValueType)tp;
14689       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14690         StoreType = Tp;
14691     }
14692
14693     // Bitcast the original vector into a vector of store-size units
14694     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14695             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14696     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14697     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14698     SmallVector<SDValue, 8> Chains;
14699     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14700                                         TLI.getPointerTy());
14701     SDValue Ptr = St->getBasePtr();
14702
14703     // Perform one or more big stores into memory.
14704     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14705       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14706                                    StoreType, ShuffWide,
14707                                    DAG.getIntPtrConstant(i));
14708       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14709                                 St->getPointerInfo(), St->isVolatile(),
14710                                 St->isNonTemporal(), St->getAlignment());
14711       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14712       Chains.push_back(Ch);
14713     }
14714
14715     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14716                                Chains.size());
14717   }
14718
14719
14720   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14721   // the FP state in cases where an emms may be missing.
14722   // A preferable solution to the general problem is to figure out the right
14723   // places to insert EMMS.  This qualifies as a quick hack.
14724
14725   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14726   if (VT.getSizeInBits() != 64)
14727     return SDValue();
14728
14729   const Function *F = DAG.getMachineFunction().getFunction();
14730   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14731   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14732                      && Subtarget->hasSSE2();
14733   if ((VT.isVector() ||
14734        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14735       isa<LoadSDNode>(St->getValue()) &&
14736       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14737       St->getChain().hasOneUse() && !St->isVolatile()) {
14738     SDNode* LdVal = St->getValue().getNode();
14739     LoadSDNode *Ld = 0;
14740     int TokenFactorIndex = -1;
14741     SmallVector<SDValue, 8> Ops;
14742     SDNode* ChainVal = St->getChain().getNode();
14743     // Must be a store of a load.  We currently handle two cases:  the load
14744     // is a direct child, and it's under an intervening TokenFactor.  It is
14745     // possible to dig deeper under nested TokenFactors.
14746     if (ChainVal == LdVal)
14747       Ld = cast<LoadSDNode>(St->getChain());
14748     else if (St->getValue().hasOneUse() &&
14749              ChainVal->getOpcode() == ISD::TokenFactor) {
14750       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14751         if (ChainVal->getOperand(i).getNode() == LdVal) {
14752           TokenFactorIndex = i;
14753           Ld = cast<LoadSDNode>(St->getValue());
14754         } else
14755           Ops.push_back(ChainVal->getOperand(i));
14756       }
14757     }
14758
14759     if (!Ld || !ISD::isNormalLoad(Ld))
14760       return SDValue();
14761
14762     // If this is not the MMX case, i.e. we are just turning i64 load/store
14763     // into f64 load/store, avoid the transformation if there are multiple
14764     // uses of the loaded value.
14765     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14766       return SDValue();
14767
14768     DebugLoc LdDL = Ld->getDebugLoc();
14769     DebugLoc StDL = N->getDebugLoc();
14770     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14771     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14772     // pair instead.
14773     if (Subtarget->is64Bit() || F64IsLegal) {
14774       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14775       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14776                                   Ld->getPointerInfo(), Ld->isVolatile(),
14777                                   Ld->isNonTemporal(), Ld->isInvariant(),
14778                                   Ld->getAlignment());
14779       SDValue NewChain = NewLd.getValue(1);
14780       if (TokenFactorIndex != -1) {
14781         Ops.push_back(NewChain);
14782         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14783                                Ops.size());
14784       }
14785       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14786                           St->getPointerInfo(),
14787                           St->isVolatile(), St->isNonTemporal(),
14788                           St->getAlignment());
14789     }
14790
14791     // Otherwise, lower to two pairs of 32-bit loads / stores.
14792     SDValue LoAddr = Ld->getBasePtr();
14793     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14794                                  DAG.getConstant(4, MVT::i32));
14795
14796     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14797                                Ld->getPointerInfo(),
14798                                Ld->isVolatile(), Ld->isNonTemporal(),
14799                                Ld->isInvariant(), Ld->getAlignment());
14800     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14801                                Ld->getPointerInfo().getWithOffset(4),
14802                                Ld->isVolatile(), Ld->isNonTemporal(),
14803                                Ld->isInvariant(),
14804                                MinAlign(Ld->getAlignment(), 4));
14805
14806     SDValue NewChain = LoLd.getValue(1);
14807     if (TokenFactorIndex != -1) {
14808       Ops.push_back(LoLd);
14809       Ops.push_back(HiLd);
14810       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14811                              Ops.size());
14812     }
14813
14814     LoAddr = St->getBasePtr();
14815     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14816                          DAG.getConstant(4, MVT::i32));
14817
14818     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14819                                 St->getPointerInfo(),
14820                                 St->isVolatile(), St->isNonTemporal(),
14821                                 St->getAlignment());
14822     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14823                                 St->getPointerInfo().getWithOffset(4),
14824                                 St->isVolatile(),
14825                                 St->isNonTemporal(),
14826                                 MinAlign(St->getAlignment(), 4));
14827     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14828   }
14829   return SDValue();
14830 }
14831
14832 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14833 /// and return the operands for the horizontal operation in LHS and RHS.  A
14834 /// horizontal operation performs the binary operation on successive elements
14835 /// of its first operand, then on successive elements of its second operand,
14836 /// returning the resulting values in a vector.  For example, if
14837 ///   A = < float a0, float a1, float a2, float a3 >
14838 /// and
14839 ///   B = < float b0, float b1, float b2, float b3 >
14840 /// then the result of doing a horizontal operation on A and B is
14841 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14842 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14843 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14844 /// set to A, RHS to B, and the routine returns 'true'.
14845 /// Note that the binary operation should have the property that if one of the
14846 /// operands is UNDEF then the result is UNDEF.
14847 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14848   // Look for the following pattern: if
14849   //   A = < float a0, float a1, float a2, float a3 >
14850   //   B = < float b0, float b1, float b2, float b3 >
14851   // and
14852   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14853   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14854   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14855   // which is A horizontal-op B.
14856
14857   // At least one of the operands should be a vector shuffle.
14858   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14859       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14860     return false;
14861
14862   EVT VT = LHS.getValueType();
14863
14864   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14865          "Unsupported vector type for horizontal add/sub");
14866
14867   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14868   // operate independently on 128-bit lanes.
14869   unsigned NumElts = VT.getVectorNumElements();
14870   unsigned NumLanes = VT.getSizeInBits()/128;
14871   unsigned NumLaneElts = NumElts / NumLanes;
14872   assert((NumLaneElts % 2 == 0) &&
14873          "Vector type should have an even number of elements in each lane");
14874   unsigned HalfLaneElts = NumLaneElts/2;
14875
14876   // View LHS in the form
14877   //   LHS = VECTOR_SHUFFLE A, B, LMask
14878   // If LHS is not a shuffle then pretend it is the shuffle
14879   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14880   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14881   // type VT.
14882   SDValue A, B;
14883   SmallVector<int, 16> LMask(NumElts);
14884   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14885     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14886       A = LHS.getOperand(0);
14887     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14888       B = LHS.getOperand(1);
14889     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
14890     std::copy(Mask.begin(), Mask.end(), LMask.begin());
14891   } else {
14892     if (LHS.getOpcode() != ISD::UNDEF)
14893       A = LHS;
14894     for (unsigned i = 0; i != NumElts; ++i)
14895       LMask[i] = i;
14896   }
14897
14898   // Likewise, view RHS in the form
14899   //   RHS = VECTOR_SHUFFLE C, D, RMask
14900   SDValue C, D;
14901   SmallVector<int, 16> RMask(NumElts);
14902   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14903     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14904       C = RHS.getOperand(0);
14905     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14906       D = RHS.getOperand(1);
14907     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
14908     std::copy(Mask.begin(), Mask.end(), RMask.begin());
14909   } else {
14910     if (RHS.getOpcode() != ISD::UNDEF)
14911       C = RHS;
14912     for (unsigned i = 0; i != NumElts; ++i)
14913       RMask[i] = i;
14914   }
14915
14916   // Check that the shuffles are both shuffling the same vectors.
14917   if (!(A == C && B == D) && !(A == D && B == C))
14918     return false;
14919
14920   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14921   if (!A.getNode() && !B.getNode())
14922     return false;
14923
14924   // If A and B occur in reverse order in RHS, then "swap" them (which means
14925   // rewriting the mask).
14926   if (A != C)
14927     CommuteVectorShuffleMask(RMask, NumElts);
14928
14929   // At this point LHS and RHS are equivalent to
14930   //   LHS = VECTOR_SHUFFLE A, B, LMask
14931   //   RHS = VECTOR_SHUFFLE A, B, RMask
14932   // Check that the masks correspond to performing a horizontal operation.
14933   for (unsigned i = 0; i != NumElts; ++i) {
14934     int LIdx = LMask[i], RIdx = RMask[i];
14935
14936     // Ignore any UNDEF components.
14937     if (LIdx < 0 || RIdx < 0 ||
14938         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14939         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14940       continue;
14941
14942     // Check that successive elements are being operated on.  If not, this is
14943     // not a horizontal operation.
14944     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14945     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14946     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14947     if (!(LIdx == Index && RIdx == Index + 1) &&
14948         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14949       return false;
14950   }
14951
14952   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14953   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14954   return true;
14955 }
14956
14957 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14958 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14959                                   const X86Subtarget *Subtarget) {
14960   EVT VT = N->getValueType(0);
14961   SDValue LHS = N->getOperand(0);
14962   SDValue RHS = N->getOperand(1);
14963
14964   // Try to synthesize horizontal adds from adds of shuffles.
14965   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14966        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14967       isHorizontalBinOp(LHS, RHS, true))
14968     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14969   return SDValue();
14970 }
14971
14972 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14973 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14974                                   const X86Subtarget *Subtarget) {
14975   EVT VT = N->getValueType(0);
14976   SDValue LHS = N->getOperand(0);
14977   SDValue RHS = N->getOperand(1);
14978
14979   // Try to synthesize horizontal subs from subs of shuffles.
14980   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14981        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14982       isHorizontalBinOp(LHS, RHS, false))
14983     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14984   return SDValue();
14985 }
14986
14987 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14988 /// X86ISD::FXOR nodes.
14989 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14990   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14991   // F[X]OR(0.0, x) -> x
14992   // F[X]OR(x, 0.0) -> x
14993   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14994     if (C->getValueAPF().isPosZero())
14995       return N->getOperand(1);
14996   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14997     if (C->getValueAPF().isPosZero())
14998       return N->getOperand(0);
14999   return SDValue();
15000 }
15001
15002 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15003 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15004   // FAND(0.0, x) -> 0.0
15005   // FAND(x, 0.0) -> 0.0
15006   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15007     if (C->getValueAPF().isPosZero())
15008       return N->getOperand(0);
15009   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15010     if (C->getValueAPF().isPosZero())
15011       return N->getOperand(1);
15012   return SDValue();
15013 }
15014
15015 static SDValue PerformBTCombine(SDNode *N,
15016                                 SelectionDAG &DAG,
15017                                 TargetLowering::DAGCombinerInfo &DCI) {
15018   // BT ignores high bits in the bit index operand.
15019   SDValue Op1 = N->getOperand(1);
15020   if (Op1.hasOneUse()) {
15021     unsigned BitWidth = Op1.getValueSizeInBits();
15022     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15023     APInt KnownZero, KnownOne;
15024     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15025                                           !DCI.isBeforeLegalizeOps());
15026     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15027     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15028         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15029       DCI.CommitTargetLoweringOpt(TLO);
15030   }
15031   return SDValue();
15032 }
15033
15034 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15035   SDValue Op = N->getOperand(0);
15036   if (Op.getOpcode() == ISD::BITCAST)
15037     Op = Op.getOperand(0);
15038   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15039   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15040       VT.getVectorElementType().getSizeInBits() ==
15041       OpVT.getVectorElementType().getSizeInBits()) {
15042     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15043   }
15044   return SDValue();
15045 }
15046
15047 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15048                                   TargetLowering::DAGCombinerInfo &DCI,
15049                                   const X86Subtarget *Subtarget) {
15050   if (!DCI.isBeforeLegalizeOps())
15051     return SDValue();
15052
15053   if (!Subtarget->hasAVX())
15054     return SDValue();
15055
15056   EVT VT = N->getValueType(0);
15057   SDValue Op = N->getOperand(0);
15058   EVT OpVT = Op.getValueType();
15059   DebugLoc dl = N->getDebugLoc();
15060
15061   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15062       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15063
15064     if (Subtarget->hasAVX2())
15065       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15066
15067     // Optimize vectors in AVX mode
15068     // Sign extend  v8i16 to v8i32 and
15069     //              v4i32 to v4i64
15070     //
15071     // Divide input vector into two parts
15072     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15073     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15074     // concat the vectors to original VT
15075
15076     unsigned NumElems = OpVT.getVectorNumElements();
15077     SmallVector<int,8> ShufMask1(NumElems, -1);
15078     for (unsigned i = 0; i != NumElems/2; ++i)
15079       ShufMask1[i] = i;
15080
15081     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15082                                         &ShufMask1[0]);
15083
15084     SmallVector<int,8> ShufMask2(NumElems, -1);
15085     for (unsigned i = 0; i != NumElems/2; ++i)
15086       ShufMask2[i] = i + NumElems/2;
15087
15088     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15089                                         &ShufMask2[0]);
15090
15091     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15092                                   VT.getVectorNumElements()/2);
15093
15094     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15095     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15096
15097     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15098   }
15099   return SDValue();
15100 }
15101
15102 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15103                                   TargetLowering::DAGCombinerInfo &DCI,
15104                                   const X86Subtarget *Subtarget) {
15105   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15106   //           (and (i32 x86isd::setcc_carry), 1)
15107   // This eliminates the zext. This transformation is necessary because
15108   // ISD::SETCC is always legalized to i8.
15109   DebugLoc dl = N->getDebugLoc();
15110   SDValue N0 = N->getOperand(0);
15111   EVT VT = N->getValueType(0);
15112   EVT OpVT = N0.getValueType();
15113
15114   if (N0.getOpcode() == ISD::AND &&
15115       N0.hasOneUse() &&
15116       N0.getOperand(0).hasOneUse()) {
15117     SDValue N00 = N0.getOperand(0);
15118     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15119       return SDValue();
15120     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15121     if (!C || C->getZExtValue() != 1)
15122       return SDValue();
15123     return DAG.getNode(ISD::AND, dl, VT,
15124                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15125                                    N00.getOperand(0), N00.getOperand(1)),
15126                        DAG.getConstant(1, VT));
15127   }
15128
15129   // Optimize vectors in AVX mode:
15130   //
15131   //   v8i16 -> v8i32
15132   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15133   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15134   //   Concat upper and lower parts.
15135   //
15136   //   v4i32 -> v4i64
15137   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15138   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15139   //   Concat upper and lower parts.
15140   //
15141   if (!DCI.isBeforeLegalizeOps())
15142     return SDValue();
15143
15144   if (!Subtarget->hasAVX())
15145     return SDValue();
15146
15147   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15148       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15149
15150     if (Subtarget->hasAVX2())
15151       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15152
15153     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15154     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15155     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15156
15157     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15158                                VT.getVectorNumElements()/2);
15159
15160     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15161     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15162
15163     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15164   }
15165
15166   return SDValue();
15167 }
15168
15169 // Optimize x == -y --> x+y == 0
15170 //          x != -y --> x+y != 0
15171 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15172   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15173   SDValue LHS = N->getOperand(0);
15174   SDValue RHS = N->getOperand(1); 
15175
15176   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15177     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15178       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15179         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15180                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15181         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15182                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15183       }
15184   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15185     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15186       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15187         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15188                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15189         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15190                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15191       }
15192   return SDValue();
15193 }
15194
15195 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15196 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15197   unsigned X86CC = N->getConstantOperandVal(0);
15198   SDValue EFLAG = N->getOperand(1);
15199   DebugLoc DL = N->getDebugLoc();
15200
15201   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15202   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15203   // cases.
15204   if (X86CC == X86::COND_B)
15205     return DAG.getNode(ISD::AND, DL, MVT::i8,
15206                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15207                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
15208                        DAG.getConstant(1, MVT::i8));
15209
15210   return SDValue();
15211 }
15212
15213 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15214   SDValue Op0 = N->getOperand(0);
15215   EVT InVT = Op0->getValueType(0);
15216
15217   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15218   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15219     DebugLoc dl = N->getDebugLoc();
15220     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15221     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15222     // Notice that we use SINT_TO_FP because we know that the high bits
15223     // are zero and SINT_TO_FP is better supported by the hardware.
15224     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15225   }
15226
15227   return SDValue();
15228 }
15229
15230 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15231                                         const X86TargetLowering *XTLI) {
15232   SDValue Op0 = N->getOperand(0);
15233   EVT InVT = Op0->getValueType(0);
15234
15235   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15236   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15237     DebugLoc dl = N->getDebugLoc();
15238     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15239     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15240     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15241   }
15242
15243   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15244   // a 32-bit target where SSE doesn't support i64->FP operations.
15245   if (Op0.getOpcode() == ISD::LOAD) {
15246     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15247     EVT VT = Ld->getValueType(0);
15248     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15249         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15250         !XTLI->getSubtarget()->is64Bit() &&
15251         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15252       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15253                                           Ld->getChain(), Op0, DAG);
15254       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15255       return FILDChain;
15256     }
15257   }
15258   return SDValue();
15259 }
15260
15261 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15262   EVT VT = N->getValueType(0);
15263
15264   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15265   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15266     DebugLoc dl = N->getDebugLoc();
15267     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15268     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15269     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15270   }
15271
15272   return SDValue();
15273 }
15274
15275 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15276 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15277                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15278   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15279   // the result is either zero or one (depending on the input carry bit).
15280   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15281   if (X86::isZeroNode(N->getOperand(0)) &&
15282       X86::isZeroNode(N->getOperand(1)) &&
15283       // We don't have a good way to replace an EFLAGS use, so only do this when
15284       // dead right now.
15285       SDValue(N, 1).use_empty()) {
15286     DebugLoc DL = N->getDebugLoc();
15287     EVT VT = N->getValueType(0);
15288     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15289     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15290                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15291                                            DAG.getConstant(X86::COND_B,MVT::i8),
15292                                            N->getOperand(2)),
15293                                DAG.getConstant(1, VT));
15294     return DCI.CombineTo(N, Res1, CarryOut);
15295   }
15296
15297   return SDValue();
15298 }
15299
15300 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15301 //      (add Y, (setne X, 0)) -> sbb -1, Y
15302 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15303 //      (sub (setne X, 0), Y) -> adc -1, Y
15304 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15305   DebugLoc DL = N->getDebugLoc();
15306
15307   // Look through ZExts.
15308   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15309   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15310     return SDValue();
15311
15312   SDValue SetCC = Ext.getOperand(0);
15313   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15314     return SDValue();
15315
15316   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15317   if (CC != X86::COND_E && CC != X86::COND_NE)
15318     return SDValue();
15319
15320   SDValue Cmp = SetCC.getOperand(1);
15321   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15322       !X86::isZeroNode(Cmp.getOperand(1)) ||
15323       !Cmp.getOperand(0).getValueType().isInteger())
15324     return SDValue();
15325
15326   SDValue CmpOp0 = Cmp.getOperand(0);
15327   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15328                                DAG.getConstant(1, CmpOp0.getValueType()));
15329
15330   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15331   if (CC == X86::COND_NE)
15332     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15333                        DL, OtherVal.getValueType(), OtherVal,
15334                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15335   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15336                      DL, OtherVal.getValueType(), OtherVal,
15337                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15338 }
15339
15340 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15341 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15342                                  const X86Subtarget *Subtarget) {
15343   EVT VT = N->getValueType(0);
15344   SDValue Op0 = N->getOperand(0);
15345   SDValue Op1 = N->getOperand(1);
15346
15347   // Try to synthesize horizontal adds from adds of shuffles.
15348   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15349        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15350       isHorizontalBinOp(Op0, Op1, true))
15351     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15352
15353   return OptimizeConditionalInDecrement(N, DAG);
15354 }
15355
15356 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15357                                  const X86Subtarget *Subtarget) {
15358   SDValue Op0 = N->getOperand(0);
15359   SDValue Op1 = N->getOperand(1);
15360
15361   // X86 can't encode an immediate LHS of a sub. See if we can push the
15362   // negation into a preceding instruction.
15363   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15364     // If the RHS of the sub is a XOR with one use and a constant, invert the
15365     // immediate. Then add one to the LHS of the sub so we can turn
15366     // X-Y -> X+~Y+1, saving one register.
15367     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15368         isa<ConstantSDNode>(Op1.getOperand(1))) {
15369       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15370       EVT VT = Op0.getValueType();
15371       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15372                                    Op1.getOperand(0),
15373                                    DAG.getConstant(~XorC, VT));
15374       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15375                          DAG.getConstant(C->getAPIntValue()+1, VT));
15376     }
15377   }
15378
15379   // Try to synthesize horizontal adds from adds of shuffles.
15380   EVT VT = N->getValueType(0);
15381   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15382        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15383       isHorizontalBinOp(Op0, Op1, true))
15384     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15385
15386   return OptimizeConditionalInDecrement(N, DAG);
15387 }
15388
15389 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15390                                              DAGCombinerInfo &DCI) const {
15391   SelectionDAG &DAG = DCI.DAG;
15392   switch (N->getOpcode()) {
15393   default: break;
15394   case ISD::EXTRACT_VECTOR_ELT:
15395     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15396   case ISD::VSELECT:
15397   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15398   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
15399   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15400   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15401   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
15402   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
15403   case ISD::SHL:
15404   case ISD::SRA:
15405   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
15406   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
15407   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
15408   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
15409   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
15410   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
15411   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
15412   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
15413   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
15414   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
15415   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
15416   case X86ISD::FXOR:
15417   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
15418   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
15419   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
15420   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
15421   case ISD::ANY_EXTEND:
15422   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
15423   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
15424   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
15425   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
15426   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
15427   case X86ISD::SHUFP:       // Handle all target specific shuffles
15428   case X86ISD::PALIGN:
15429   case X86ISD::UNPCKH:
15430   case X86ISD::UNPCKL:
15431   case X86ISD::MOVHLPS:
15432   case X86ISD::MOVLHPS:
15433   case X86ISD::PSHUFD:
15434   case X86ISD::PSHUFHW:
15435   case X86ISD::PSHUFLW:
15436   case X86ISD::MOVSS:
15437   case X86ISD::MOVSD:
15438   case X86ISD::VPERMILP:
15439   case X86ISD::VPERM2X128:
15440   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15441   }
15442
15443   return SDValue();
15444 }
15445
15446 /// isTypeDesirableForOp - Return true if the target has native support for
15447 /// the specified value type and it is 'desirable' to use the type for the
15448 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15449 /// instruction encodings are longer and some i16 instructions are slow.
15450 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15451   if (!isTypeLegal(VT))
15452     return false;
15453   if (VT != MVT::i16)
15454     return true;
15455
15456   switch (Opc) {
15457   default:
15458     return true;
15459   case ISD::LOAD:
15460   case ISD::SIGN_EXTEND:
15461   case ISD::ZERO_EXTEND:
15462   case ISD::ANY_EXTEND:
15463   case ISD::SHL:
15464   case ISD::SRL:
15465   case ISD::SUB:
15466   case ISD::ADD:
15467   case ISD::MUL:
15468   case ISD::AND:
15469   case ISD::OR:
15470   case ISD::XOR:
15471     return false;
15472   }
15473 }
15474
15475 /// IsDesirableToPromoteOp - This method query the target whether it is
15476 /// beneficial for dag combiner to promote the specified node. If true, it
15477 /// should return the desired promotion type by reference.
15478 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15479   EVT VT = Op.getValueType();
15480   if (VT != MVT::i16)
15481     return false;
15482
15483   bool Promote = false;
15484   bool Commute = false;
15485   switch (Op.getOpcode()) {
15486   default: break;
15487   case ISD::LOAD: {
15488     LoadSDNode *LD = cast<LoadSDNode>(Op);
15489     // If the non-extending load has a single use and it's not live out, then it
15490     // might be folded.
15491     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15492                                                      Op.hasOneUse()*/) {
15493       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15494              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15495         // The only case where we'd want to promote LOAD (rather then it being
15496         // promoted as an operand is when it's only use is liveout.
15497         if (UI->getOpcode() != ISD::CopyToReg)
15498           return false;
15499       }
15500     }
15501     Promote = true;
15502     break;
15503   }
15504   case ISD::SIGN_EXTEND:
15505   case ISD::ZERO_EXTEND:
15506   case ISD::ANY_EXTEND:
15507     Promote = true;
15508     break;
15509   case ISD::SHL:
15510   case ISD::SRL: {
15511     SDValue N0 = Op.getOperand(0);
15512     // Look out for (store (shl (load), x)).
15513     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15514       return false;
15515     Promote = true;
15516     break;
15517   }
15518   case ISD::ADD:
15519   case ISD::MUL:
15520   case ISD::AND:
15521   case ISD::OR:
15522   case ISD::XOR:
15523     Commute = true;
15524     // fallthrough
15525   case ISD::SUB: {
15526     SDValue N0 = Op.getOperand(0);
15527     SDValue N1 = Op.getOperand(1);
15528     if (!Commute && MayFoldLoad(N1))
15529       return false;
15530     // Avoid disabling potential load folding opportunities.
15531     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15532       return false;
15533     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15534       return false;
15535     Promote = true;
15536   }
15537   }
15538
15539   PVT = MVT::i32;
15540   return Promote;
15541 }
15542
15543 //===----------------------------------------------------------------------===//
15544 //                           X86 Inline Assembly Support
15545 //===----------------------------------------------------------------------===//
15546
15547 namespace {
15548   // Helper to match a string separated by whitespace.
15549   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15550     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15551
15552     for (unsigned i = 0, e = args.size(); i != e; ++i) {
15553       StringRef piece(*args[i]);
15554       if (!s.startswith(piece)) // Check if the piece matches.
15555         return false;
15556
15557       s = s.substr(piece.size());
15558       StringRef::size_type pos = s.find_first_not_of(" \t");
15559       if (pos == 0) // We matched a prefix.
15560         return false;
15561
15562       s = s.substr(pos);
15563     }
15564
15565     return s.empty();
15566   }
15567   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15568 }
15569
15570 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15571   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15572
15573   std::string AsmStr = IA->getAsmString();
15574
15575   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15576   if (!Ty || Ty->getBitWidth() % 16 != 0)
15577     return false;
15578
15579   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15580   SmallVector<StringRef, 4> AsmPieces;
15581   SplitString(AsmStr, AsmPieces, ";\n");
15582
15583   switch (AsmPieces.size()) {
15584   default: return false;
15585   case 1:
15586     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15587     // we will turn this bswap into something that will be lowered to logical
15588     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
15589     // lower so don't worry about this.
15590     // bswap $0
15591     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15592         matchAsm(AsmPieces[0], "bswapl", "$0") ||
15593         matchAsm(AsmPieces[0], "bswapq", "$0") ||
15594         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15595         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15596         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15597       // No need to check constraints, nothing other than the equivalent of
15598       // "=r,0" would be valid here.
15599       return IntrinsicLowering::LowerToByteSwap(CI);
15600     }
15601
15602     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15603     if (CI->getType()->isIntegerTy(16) &&
15604         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15605         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15606          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15607       AsmPieces.clear();
15608       const std::string &ConstraintsStr = IA->getConstraintString();
15609       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15610       std::sort(AsmPieces.begin(), AsmPieces.end());
15611       if (AsmPieces.size() == 4 &&
15612           AsmPieces[0] == "~{cc}" &&
15613           AsmPieces[1] == "~{dirflag}" &&
15614           AsmPieces[2] == "~{flags}" &&
15615           AsmPieces[3] == "~{fpsr}")
15616       return IntrinsicLowering::LowerToByteSwap(CI);
15617     }
15618     break;
15619   case 3:
15620     if (CI->getType()->isIntegerTy(32) &&
15621         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15622         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15623         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15624         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15625       AsmPieces.clear();
15626       const std::string &ConstraintsStr = IA->getConstraintString();
15627       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15628       std::sort(AsmPieces.begin(), AsmPieces.end());
15629       if (AsmPieces.size() == 4 &&
15630           AsmPieces[0] == "~{cc}" &&
15631           AsmPieces[1] == "~{dirflag}" &&
15632           AsmPieces[2] == "~{flags}" &&
15633           AsmPieces[3] == "~{fpsr}")
15634         return IntrinsicLowering::LowerToByteSwap(CI);
15635     }
15636
15637     if (CI->getType()->isIntegerTy(64)) {
15638       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15639       if (Constraints.size() >= 2 &&
15640           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15641           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15642         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15643         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15644             matchAsm(AsmPieces[1], "bswap", "%edx") &&
15645             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15646           return IntrinsicLowering::LowerToByteSwap(CI);
15647       }
15648     }
15649     break;
15650   }
15651   return false;
15652 }
15653
15654
15655
15656 /// getConstraintType - Given a constraint letter, return the type of
15657 /// constraint it is for this target.
15658 X86TargetLowering::ConstraintType
15659 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15660   if (Constraint.size() == 1) {
15661     switch (Constraint[0]) {
15662     case 'R':
15663     case 'q':
15664     case 'Q':
15665     case 'f':
15666     case 't':
15667     case 'u':
15668     case 'y':
15669     case 'x':
15670     case 'Y':
15671     case 'l':
15672       return C_RegisterClass;
15673     case 'a':
15674     case 'b':
15675     case 'c':
15676     case 'd':
15677     case 'S':
15678     case 'D':
15679     case 'A':
15680       return C_Register;
15681     case 'I':
15682     case 'J':
15683     case 'K':
15684     case 'L':
15685     case 'M':
15686     case 'N':
15687     case 'G':
15688     case 'C':
15689     case 'e':
15690     case 'Z':
15691       return C_Other;
15692     default:
15693       break;
15694     }
15695   }
15696   return TargetLowering::getConstraintType(Constraint);
15697 }
15698
15699 /// Examine constraint type and operand type and determine a weight value.
15700 /// This object must already have been set up with the operand type
15701 /// and the current alternative constraint selected.
15702 TargetLowering::ConstraintWeight
15703   X86TargetLowering::getSingleConstraintMatchWeight(
15704     AsmOperandInfo &info, const char *constraint) const {
15705   ConstraintWeight weight = CW_Invalid;
15706   Value *CallOperandVal = info.CallOperandVal;
15707     // If we don't have a value, we can't do a match,
15708     // but allow it at the lowest weight.
15709   if (CallOperandVal == NULL)
15710     return CW_Default;
15711   Type *type = CallOperandVal->getType();
15712   // Look at the constraint type.
15713   switch (*constraint) {
15714   default:
15715     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15716   case 'R':
15717   case 'q':
15718   case 'Q':
15719   case 'a':
15720   case 'b':
15721   case 'c':
15722   case 'd':
15723   case 'S':
15724   case 'D':
15725   case 'A':
15726     if (CallOperandVal->getType()->isIntegerTy())
15727       weight = CW_SpecificReg;
15728     break;
15729   case 'f':
15730   case 't':
15731   case 'u':
15732       if (type->isFloatingPointTy())
15733         weight = CW_SpecificReg;
15734       break;
15735   case 'y':
15736       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15737         weight = CW_SpecificReg;
15738       break;
15739   case 'x':
15740   case 'Y':
15741     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15742         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15743       weight = CW_Register;
15744     break;
15745   case 'I':
15746     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15747       if (C->getZExtValue() <= 31)
15748         weight = CW_Constant;
15749     }
15750     break;
15751   case 'J':
15752     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15753       if (C->getZExtValue() <= 63)
15754         weight = CW_Constant;
15755     }
15756     break;
15757   case 'K':
15758     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15759       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15760         weight = CW_Constant;
15761     }
15762     break;
15763   case 'L':
15764     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15765       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15766         weight = CW_Constant;
15767     }
15768     break;
15769   case 'M':
15770     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15771       if (C->getZExtValue() <= 3)
15772         weight = CW_Constant;
15773     }
15774     break;
15775   case 'N':
15776     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15777       if (C->getZExtValue() <= 0xff)
15778         weight = CW_Constant;
15779     }
15780     break;
15781   case 'G':
15782   case 'C':
15783     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15784       weight = CW_Constant;
15785     }
15786     break;
15787   case 'e':
15788     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15789       if ((C->getSExtValue() >= -0x80000000LL) &&
15790           (C->getSExtValue() <= 0x7fffffffLL))
15791         weight = CW_Constant;
15792     }
15793     break;
15794   case 'Z':
15795     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15796       if (C->getZExtValue() <= 0xffffffff)
15797         weight = CW_Constant;
15798     }
15799     break;
15800   }
15801   return weight;
15802 }
15803
15804 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15805 /// with another that has more specific requirements based on the type of the
15806 /// corresponding operand.
15807 const char *X86TargetLowering::
15808 LowerXConstraint(EVT ConstraintVT) const {
15809   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15810   // 'f' like normal targets.
15811   if (ConstraintVT.isFloatingPoint()) {
15812     if (Subtarget->hasSSE2())
15813       return "Y";
15814     if (Subtarget->hasSSE1())
15815       return "x";
15816   }
15817
15818   return TargetLowering::LowerXConstraint(ConstraintVT);
15819 }
15820
15821 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15822 /// vector.  If it is invalid, don't add anything to Ops.
15823 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15824                                                      std::string &Constraint,
15825                                                      std::vector<SDValue>&Ops,
15826                                                      SelectionDAG &DAG) const {
15827   SDValue Result(0, 0);
15828
15829   // Only support length 1 constraints for now.
15830   if (Constraint.length() > 1) return;
15831
15832   char ConstraintLetter = Constraint[0];
15833   switch (ConstraintLetter) {
15834   default: break;
15835   case 'I':
15836     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15837       if (C->getZExtValue() <= 31) {
15838         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15839         break;
15840       }
15841     }
15842     return;
15843   case 'J':
15844     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15845       if (C->getZExtValue() <= 63) {
15846         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15847         break;
15848       }
15849     }
15850     return;
15851   case 'K':
15852     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15853       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15854         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15855         break;
15856       }
15857     }
15858     return;
15859   case 'N':
15860     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15861       if (C->getZExtValue() <= 255) {
15862         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15863         break;
15864       }
15865     }
15866     return;
15867   case 'e': {
15868     // 32-bit signed value
15869     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15870       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15871                                            C->getSExtValue())) {
15872         // Widen to 64 bits here to get it sign extended.
15873         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15874         break;
15875       }
15876     // FIXME gcc accepts some relocatable values here too, but only in certain
15877     // memory models; it's complicated.
15878     }
15879     return;
15880   }
15881   case 'Z': {
15882     // 32-bit unsigned value
15883     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15884       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15885                                            C->getZExtValue())) {
15886         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15887         break;
15888       }
15889     }
15890     // FIXME gcc accepts some relocatable values here too, but only in certain
15891     // memory models; it's complicated.
15892     return;
15893   }
15894   case 'i': {
15895     // Literal immediates are always ok.
15896     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15897       // Widen to 64 bits here to get it sign extended.
15898       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15899       break;
15900     }
15901
15902     // In any sort of PIC mode addresses need to be computed at runtime by
15903     // adding in a register or some sort of table lookup.  These can't
15904     // be used as immediates.
15905     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15906       return;
15907
15908     // If we are in non-pic codegen mode, we allow the address of a global (with
15909     // an optional displacement) to be used with 'i'.
15910     GlobalAddressSDNode *GA = 0;
15911     int64_t Offset = 0;
15912
15913     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15914     while (1) {
15915       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15916         Offset += GA->getOffset();
15917         break;
15918       } else if (Op.getOpcode() == ISD::ADD) {
15919         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15920           Offset += C->getZExtValue();
15921           Op = Op.getOperand(0);
15922           continue;
15923         }
15924       } else if (Op.getOpcode() == ISD::SUB) {
15925         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15926           Offset += -C->getZExtValue();
15927           Op = Op.getOperand(0);
15928           continue;
15929         }
15930       }
15931
15932       // Otherwise, this isn't something we can handle, reject it.
15933       return;
15934     }
15935
15936     const GlobalValue *GV = GA->getGlobal();
15937     // If we require an extra load to get this address, as in PIC mode, we
15938     // can't accept it.
15939     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15940                                                         getTargetMachine())))
15941       return;
15942
15943     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15944                                         GA->getValueType(0), Offset);
15945     break;
15946   }
15947   }
15948
15949   if (Result.getNode()) {
15950     Ops.push_back(Result);
15951     return;
15952   }
15953   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15954 }
15955
15956 std::pair<unsigned, const TargetRegisterClass*>
15957 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15958                                                 EVT VT) const {
15959   // First, see if this is a constraint that directly corresponds to an LLVM
15960   // register class.
15961   if (Constraint.size() == 1) {
15962     // GCC Constraint Letters
15963     switch (Constraint[0]) {
15964     default: break;
15965       // TODO: Slight differences here in allocation order and leaving
15966       // RIP in the class. Do they matter any more here than they do
15967       // in the normal allocation?
15968     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15969       if (Subtarget->is64Bit()) {
15970         if (VT == MVT::i32 || VT == MVT::f32)
15971           return std::make_pair(0U, &X86::GR32RegClass);
15972         if (VT == MVT::i16)
15973           return std::make_pair(0U, &X86::GR16RegClass);
15974         if (VT == MVT::i8 || VT == MVT::i1)
15975           return std::make_pair(0U, &X86::GR8RegClass);
15976         if (VT == MVT::i64 || VT == MVT::f64)
15977           return std::make_pair(0U, &X86::GR64RegClass);
15978         break;
15979       }
15980       // 32-bit fallthrough
15981     case 'Q':   // Q_REGS
15982       if (VT == MVT::i32 || VT == MVT::f32)
15983         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
15984       if (VT == MVT::i16)
15985         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
15986       if (VT == MVT::i8 || VT == MVT::i1)
15987         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
15988       if (VT == MVT::i64)
15989         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
15990       break;
15991     case 'r':   // GENERAL_REGS
15992     case 'l':   // INDEX_REGS
15993       if (VT == MVT::i8 || VT == MVT::i1)
15994         return std::make_pair(0U, &X86::GR8RegClass);
15995       if (VT == MVT::i16)
15996         return std::make_pair(0U, &X86::GR16RegClass);
15997       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15998         return std::make_pair(0U, &X86::GR32RegClass);
15999       return std::make_pair(0U, &X86::GR64RegClass);
16000     case 'R':   // LEGACY_REGS
16001       if (VT == MVT::i8 || VT == MVT::i1)
16002         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16003       if (VT == MVT::i16)
16004         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16005       if (VT == MVT::i32 || !Subtarget->is64Bit())
16006         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16007       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16008     case 'f':  // FP Stack registers.
16009       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16010       // value to the correct fpstack register class.
16011       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16012         return std::make_pair(0U, &X86::RFP32RegClass);
16013       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16014         return std::make_pair(0U, &X86::RFP64RegClass);
16015       return std::make_pair(0U, &X86::RFP80RegClass);
16016     case 'y':   // MMX_REGS if MMX allowed.
16017       if (!Subtarget->hasMMX()) break;
16018       return std::make_pair(0U, &X86::VR64RegClass);
16019     case 'Y':   // SSE_REGS if SSE2 allowed
16020       if (!Subtarget->hasSSE2()) break;
16021       // FALL THROUGH.
16022     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16023       if (!Subtarget->hasSSE1()) break;
16024
16025       switch (VT.getSimpleVT().SimpleTy) {
16026       default: break;
16027       // Scalar SSE types.
16028       case MVT::f32:
16029       case MVT::i32:
16030         return std::make_pair(0U, &X86::FR32RegClass);
16031       case MVT::f64:
16032       case MVT::i64:
16033         return std::make_pair(0U, &X86::FR64RegClass);
16034       // Vector types.
16035       case MVT::v16i8:
16036       case MVT::v8i16:
16037       case MVT::v4i32:
16038       case MVT::v2i64:
16039       case MVT::v4f32:
16040       case MVT::v2f64:
16041         return std::make_pair(0U, &X86::VR128RegClass);
16042       // AVX types.
16043       case MVT::v32i8:
16044       case MVT::v16i16:
16045       case MVT::v8i32:
16046       case MVT::v4i64:
16047       case MVT::v8f32:
16048       case MVT::v4f64:
16049         return std::make_pair(0U, &X86::VR256RegClass);
16050       }
16051       break;
16052     }
16053   }
16054
16055   // Use the default implementation in TargetLowering to convert the register
16056   // constraint into a member of a register class.
16057   std::pair<unsigned, const TargetRegisterClass*> Res;
16058   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16059
16060   // Not found as a standard register?
16061   if (Res.second == 0) {
16062     // Map st(0) -> st(7) -> ST0
16063     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16064         tolower(Constraint[1]) == 's' &&
16065         tolower(Constraint[2]) == 't' &&
16066         Constraint[3] == '(' &&
16067         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16068         Constraint[5] == ')' &&
16069         Constraint[6] == '}') {
16070
16071       Res.first = X86::ST0+Constraint[4]-'0';
16072       Res.second = &X86::RFP80RegClass;
16073       return Res;
16074     }
16075
16076     // GCC allows "st(0)" to be called just plain "st".
16077     if (StringRef("{st}").equals_lower(Constraint)) {
16078       Res.first = X86::ST0;
16079       Res.second = &X86::RFP80RegClass;
16080       return Res;
16081     }
16082
16083     // flags -> EFLAGS
16084     if (StringRef("{flags}").equals_lower(Constraint)) {
16085       Res.first = X86::EFLAGS;
16086       Res.second = &X86::CCRRegClass;
16087       return Res;
16088     }
16089
16090     // 'A' means EAX + EDX.
16091     if (Constraint == "A") {
16092       Res.first = X86::EAX;
16093       Res.second = &X86::GR32_ADRegClass;
16094       return Res;
16095     }
16096     return Res;
16097   }
16098
16099   // Otherwise, check to see if this is a register class of the wrong value
16100   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16101   // turn into {ax},{dx}.
16102   if (Res.second->hasType(VT))
16103     return Res;   // Correct type already, nothing to do.
16104
16105   // All of the single-register GCC register classes map their values onto
16106   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16107   // really want an 8-bit or 32-bit register, map to the appropriate register
16108   // class and return the appropriate register.
16109   if (Res.second == &X86::GR16RegClass) {
16110     if (VT == MVT::i8) {
16111       unsigned DestReg = 0;
16112       switch (Res.first) {
16113       default: break;
16114       case X86::AX: DestReg = X86::AL; break;
16115       case X86::DX: DestReg = X86::DL; break;
16116       case X86::CX: DestReg = X86::CL; break;
16117       case X86::BX: DestReg = X86::BL; break;
16118       }
16119       if (DestReg) {
16120         Res.first = DestReg;
16121         Res.second = &X86::GR8RegClass;
16122       }
16123     } else if (VT == MVT::i32) {
16124       unsigned DestReg = 0;
16125       switch (Res.first) {
16126       default: break;
16127       case X86::AX: DestReg = X86::EAX; break;
16128       case X86::DX: DestReg = X86::EDX; break;
16129       case X86::CX: DestReg = X86::ECX; break;
16130       case X86::BX: DestReg = X86::EBX; break;
16131       case X86::SI: DestReg = X86::ESI; break;
16132       case X86::DI: DestReg = X86::EDI; break;
16133       case X86::BP: DestReg = X86::EBP; break;
16134       case X86::SP: DestReg = X86::ESP; break;
16135       }
16136       if (DestReg) {
16137         Res.first = DestReg;
16138         Res.second = &X86::GR32RegClass;
16139       }
16140     } else if (VT == MVT::i64) {
16141       unsigned DestReg = 0;
16142       switch (Res.first) {
16143       default: break;
16144       case X86::AX: DestReg = X86::RAX; break;
16145       case X86::DX: DestReg = X86::RDX; break;
16146       case X86::CX: DestReg = X86::RCX; break;
16147       case X86::BX: DestReg = X86::RBX; break;
16148       case X86::SI: DestReg = X86::RSI; break;
16149       case X86::DI: DestReg = X86::RDI; break;
16150       case X86::BP: DestReg = X86::RBP; break;
16151       case X86::SP: DestReg = X86::RSP; break;
16152       }
16153       if (DestReg) {
16154         Res.first = DestReg;
16155         Res.second = &X86::GR64RegClass;
16156       }
16157     }
16158   } else if (Res.second == &X86::FR32RegClass ||
16159              Res.second == &X86::FR64RegClass ||
16160              Res.second == &X86::VR128RegClass) {
16161     // Handle references to XMM physical registers that got mapped into the
16162     // wrong class.  This can happen with constraints like {xmm0} where the
16163     // target independent register mapper will just pick the first match it can
16164     // find, ignoring the required type.
16165     if (VT == MVT::f32)
16166       Res.second = &X86::FR32RegClass;
16167     else if (VT == MVT::f64)
16168       Res.second = &X86::FR64RegClass;
16169     else if (X86::VR128RegClass.hasType(VT))
16170       Res.second = &X86::VR128RegClass;
16171   }
16172
16173   return Res;
16174 }