Generic Bypass Slow Div
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "X86.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
59                        SDValue V2);
60
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference.  Idx is an index in the 128 bits we
64 /// want.  It need not be aligned to a 128-bit bounday.  That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67                                    SelectionDAG &DAG, DebugLoc dl) {
68   EVT VT = Vec.getValueType();
69   assert(VT.is256BitVector() && "Unexpected vector size!");
70   EVT ElVT = VT.getVectorElementType();
71   unsigned Factor = VT.getSizeInBits()/128;
72   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73                                   VT.getVectorNumElements()/Factor);
74
75   // Extract from UNDEF is UNDEF.
76   if (Vec.getOpcode() == ISD::UNDEF)
77     return DAG.getUNDEF(ResultVT);
78
79   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
80   // we can match to VEXTRACTF128.
81   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82
83   // This is the index of the first element of the 128-bit chunk
84   // we want.
85   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
86                                * ElemsPerChunk);
87
88   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
89   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
90                                VecIdx);
91
92   return Result;
93 }
94
95 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference.  Idx is an index in the 128 bits
98 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101                                   unsigned IdxVal, SelectionDAG &DAG,
102                                   DebugLoc dl) {
103   // Inserting UNDEF is Result
104   if (Vec.getOpcode() == ISD::UNDEF)
105     return Result;
106
107   EVT VT = Vec.getValueType();
108   assert(VT.is128BitVector() && "Unexpected vector size!");
109
110   EVT ElVT = VT.getVectorElementType();
111   EVT ResultVT = Result.getValueType();
112
113   // Insert the relevant 128 bits.
114   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
115
116   // This is the index of the first element of the 128-bit chunk
117   // we want.
118   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
119                                * ElemsPerChunk);
120
121   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
122   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
123                      VecIdx);
124 }
125
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131                                    unsigned NumElems, SelectionDAG &DAG,
132                                    DebugLoc dl) {
133   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
135 }
136
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139   bool is64Bit = Subtarget->is64Bit();
140
141   if (Subtarget->isTargetEnvMacho()) {
142     if (is64Bit)
143       return new X86_64MachoTargetObjectFile();
144     return new TargetLoweringObjectFileMachO();
145   }
146
147   if (Subtarget->isTargetLinux())
148     return new X86LinuxTargetObjectFile();
149   if (Subtarget->isTargetELF())
150     return new TargetLoweringObjectFileELF();
151   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152     return new TargetLoweringObjectFileCOFF();
153   llvm_unreachable("unknown subtarget type");
154 }
155
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157   : TargetLowering(TM, createTLOF(TM)) {
158   Subtarget = &TM.getSubtarget<X86Subtarget>();
159   X86ScalarSSEf64 = Subtarget->hasSSE2();
160   X86ScalarSSEf32 = Subtarget->hasSSE1();
161   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
162
163   RegInfo = TM.getRegisterInfo();
164   TD = getTargetData();
165
166   // Set up the TargetLowering object.
167   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168
169   // X86 is weird, it always uses i8 for shift amounts and setcc results.
170   setBooleanContents(ZeroOrOneBooleanContent);
171   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   // For 64-bit since we have so many registers use the ILP scheduler, for
175   // 32-bit code use the register pressure specific scheduling.
176   // For Atom, always use ILP scheduling.
177   if (Subtarget->isAtom())
178     setSchedulingPreference(Sched::ILP);
179   else if (Subtarget->is64Bit())
180     setSchedulingPreference(Sched::ILP);
181   else
182     setSchedulingPreference(Sched::RegPressure);
183   setStackPointerRegisterToSaveRestore(X86StackPtr);
184
185   // Bypass i32 with i8 on Atom when compiling with O2
186   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
187     addBypassSlowDivType(Type::getInt32Ty(getGlobalContext()), Type::getInt8Ty(getGlobalContext()));
188
189   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
190     // Setup Windows compiler runtime calls.
191     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
192     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
193     setLibcallName(RTLIB::SREM_I64, "_allrem");
194     setLibcallName(RTLIB::UREM_I64, "_aullrem");
195     setLibcallName(RTLIB::MUL_I64, "_allmul");
196     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
197     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
198     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
199     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
200     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
201
202     // The _ftol2 runtime function has an unusual calling conv, which
203     // is modeled by a special pseudo-instruction.
204     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
205     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
206     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
207     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
208   }
209
210   if (Subtarget->isTargetDarwin()) {
211     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212     setUseUnderscoreSetJmp(false);
213     setUseUnderscoreLongJmp(false);
214   } else if (Subtarget->isTargetMingw()) {
215     // MS runtime is weird: it exports _setjmp, but longjmp!
216     setUseUnderscoreSetJmp(true);
217     setUseUnderscoreLongJmp(false);
218   } else {
219     setUseUnderscoreSetJmp(true);
220     setUseUnderscoreLongJmp(true);
221   }
222
223   // Set up the register classes.
224   addRegisterClass(MVT::i8, &X86::GR8RegClass);
225   addRegisterClass(MVT::i16, &X86::GR16RegClass);
226   addRegisterClass(MVT::i32, &X86::GR32RegClass);
227   if (Subtarget->is64Bit())
228     addRegisterClass(MVT::i64, &X86::GR64RegClass);
229
230   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231
232   // We don't accept any truncstore of integer registers.
233   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
239
240   // SETOEQ and SETUNE require checking two conditions.
241   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247
248   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249   // operation.
250   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
251   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
252   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
253
254   if (Subtarget->is64Bit()) {
255     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
256     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
257   } else if (!TM.Options.UseSoftFloat) {
258     // We have an algorithm for SSE2->double, and we turn this into a
259     // 64-bit FILD followed by conditional FADD for other targets.
260     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
261     // We have an algorithm for SSE2, and we turn this into a 64-bit
262     // FILD for other targets.
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
264   }
265
266   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267   // this operation.
268   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
269   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
270
271   if (!TM.Options.UseSoftFloat) {
272     // SSE has no i16 to fp conversion, only i32
273     if (X86ScalarSSEf32) {
274       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
275       // f32 and f64 cases are Legal, f80 case is not
276       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
277     } else {
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280     }
281   } else {
282     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
283     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
284   }
285
286   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
287   // are Legal, f80 is custom lowered.
288   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
289   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
290
291   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292   // this operation.
293   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
294   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
295
296   if (X86ScalarSSEf32) {
297     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
298     // f32 and f64 cases are Legal, f80 case is not
299     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
300   } else {
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303   }
304
305   // Handle FP_TO_UINT by promoting the destination to a larger signed
306   // conversion.
307   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
308   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
309   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
310
311   if (Subtarget->is64Bit()) {
312     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
313     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
314   } else if (!TM.Options.UseSoftFloat) {
315     // Since AVX is a superset of SSE3, only check for SSE here.
316     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
317       // Expand FP_TO_UINT into a select.
318       // FIXME: We would like to use a Custom expander here eventually to do
319       // the optimal thing for SSE vs. the default expansion in the legalizer.
320       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
321     else
322       // With SSE3 we can use fisttpll to convert to a signed i64; without
323       // SSE, we're stuck with a fistpll.
324       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
325   }
326
327   if (isTargetFTOL()) {
328     // Use the _ftol2 runtime function, which has a pseudo-instruction
329     // to handle its weird calling convention.
330     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
331   }
332
333   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
334   if (!X86ScalarSSEf64) {
335     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
336     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
337     if (Subtarget->is64Bit()) {
338       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
339       // Without SSE, i64->f64 goes through memory.
340       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
341     }
342   }
343
344   // Scalar integer divide and remainder are lowered to use operations that
345   // produce two results, to match the available instructions. This exposes
346   // the two-result form to trivial CSE, which is able to combine x/y and x%y
347   // into a single instruction.
348   //
349   // Scalar integer multiply-high is also lowered to use two-result
350   // operations, to match the available instructions. However, plain multiply
351   // (low) operations are left as Legal, as there are single-result
352   // instructions for this in x86. Using the two-result multiply instructions
353   // when both high and low results are needed must be arranged by dagcombine.
354   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
355     MVT VT = IntVTs[i];
356     setOperationAction(ISD::MULHS, VT, Expand);
357     setOperationAction(ISD::MULHU, VT, Expand);
358     setOperationAction(ISD::SDIV, VT, Expand);
359     setOperationAction(ISD::UDIV, VT, Expand);
360     setOperationAction(ISD::SREM, VT, Expand);
361     setOperationAction(ISD::UREM, VT, Expand);
362
363     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
364     setOperationAction(ISD::ADDC, VT, Custom);
365     setOperationAction(ISD::ADDE, VT, Custom);
366     setOperationAction(ISD::SUBC, VT, Custom);
367     setOperationAction(ISD::SUBE, VT, Custom);
368   }
369
370   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
371   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
372   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
373   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
374   if (Subtarget->is64Bit())
375     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
376   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
377   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
378   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
379   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
380   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
381   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
382   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
383   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
384
385   // Promote the i8 variants and force them on up to i32 which has a shorter
386   // encoding.
387   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
388   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
389   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
390   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
391   if (Subtarget->hasBMI()) {
392     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
393     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
394     if (Subtarget->is64Bit())
395       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
396   } else {
397     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
398     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
399     if (Subtarget->is64Bit())
400       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
401   }
402
403   if (Subtarget->hasLZCNT()) {
404     // When promoting the i8 variants, force them to i32 for a shorter
405     // encoding.
406     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
407     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
408     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
409     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
411     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
412     if (Subtarget->is64Bit())
413       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
414   } else {
415     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
416     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
417     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
418     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
419     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
420     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
421     if (Subtarget->is64Bit()) {
422       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
423       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
424     }
425   }
426
427   if (Subtarget->hasPOPCNT()) {
428     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
429   } else {
430     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
431     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
432     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
433     if (Subtarget->is64Bit())
434       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
435   }
436
437   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
438   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
439
440   // These should be promoted to a larger select which is supported.
441   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
442   // X86 wants to expand cmov itself.
443   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
444   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
445   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
446   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
447   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
448   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
449   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
450   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
451   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
452   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
453   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
454   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
455   if (Subtarget->is64Bit()) {
456     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
457     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
458   }
459   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
460
461   // Darwin ABI issue.
462   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
463   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
464   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
465   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
466   if (Subtarget->is64Bit())
467     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
468   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
469   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
470   if (Subtarget->is64Bit()) {
471     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
472     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
473     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
474     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
475     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
476   }
477   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
478   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
479   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
480   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
481   if (Subtarget->is64Bit()) {
482     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
483     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
484     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
485   }
486
487   if (Subtarget->hasSSE1())
488     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
489
490   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
491   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
492
493   // On X86 and X86-64, atomic operations are lowered to locked instructions.
494   // Locked instructions, in turn, have implicit fence semantics (all memory
495   // operations are flushed before issuing the locked instruction, and they
496   // are not buffered), so we can fold away the common pattern of
497   // fence-atomic-fence.
498   setShouldFoldAtomicFences(true);
499
500   // Expand certain atomics
501   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
502     MVT VT = IntVTs[i];
503     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
505     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
506   }
507
508   if (!Subtarget->is64Bit()) {
509     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
510     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
511     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
512     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
513     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
514     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
515     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
516     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
517   }
518
519   if (Subtarget->hasCmpxchg16b()) {
520     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
521   }
522
523   // FIXME - use subtarget debug flags
524   if (!Subtarget->isTargetDarwin() &&
525       !Subtarget->isTargetELF() &&
526       !Subtarget->isTargetCygMing()) {
527     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
528   }
529
530   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
531   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
532   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
533   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
534   if (Subtarget->is64Bit()) {
535     setExceptionPointerRegister(X86::RAX);
536     setExceptionSelectorRegister(X86::RDX);
537   } else {
538     setExceptionPointerRegister(X86::EAX);
539     setExceptionSelectorRegister(X86::EDX);
540   }
541   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
542   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
543
544   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
545   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
546
547   setOperationAction(ISD::TRAP, MVT::Other, Legal);
548
549   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
550   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
551   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
552   if (Subtarget->is64Bit()) {
553     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
554     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
555   } else {
556     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
557     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
558   }
559
560   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
561   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
562
563   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
564     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
565                        MVT::i64 : MVT::i32, Custom);
566   else if (TM.Options.EnableSegmentedStacks)
567     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
568                        MVT::i64 : MVT::i32, Custom);
569   else
570     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
571                        MVT::i64 : MVT::i32, Expand);
572
573   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
574     // f32 and f64 use SSE.
575     // Set up the FP register classes.
576     addRegisterClass(MVT::f32, &X86::FR32RegClass);
577     addRegisterClass(MVT::f64, &X86::FR64RegClass);
578
579     // Use ANDPD to simulate FABS.
580     setOperationAction(ISD::FABS , MVT::f64, Custom);
581     setOperationAction(ISD::FABS , MVT::f32, Custom);
582
583     // Use XORP to simulate FNEG.
584     setOperationAction(ISD::FNEG , MVT::f64, Custom);
585     setOperationAction(ISD::FNEG , MVT::f32, Custom);
586
587     // Use ANDPD and ORPD to simulate FCOPYSIGN.
588     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
589     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
590
591     // Lower this to FGETSIGNx86 plus an AND.
592     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
593     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
594
595     // We don't support sin/cos/fmod
596     setOperationAction(ISD::FSIN , MVT::f64, Expand);
597     setOperationAction(ISD::FCOS , MVT::f64, Expand);
598     setOperationAction(ISD::FSIN , MVT::f32, Expand);
599     setOperationAction(ISD::FCOS , MVT::f32, Expand);
600
601     // Expand FP immediates into loads from the stack, except for the special
602     // cases we handle.
603     addLegalFPImmediate(APFloat(+0.0)); // xorpd
604     addLegalFPImmediate(APFloat(+0.0f)); // xorps
605   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
606     // Use SSE for f32, x87 for f64.
607     // Set up the FP register classes.
608     addRegisterClass(MVT::f32, &X86::FR32RegClass);
609     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
610
611     // Use ANDPS to simulate FABS.
612     setOperationAction(ISD::FABS , MVT::f32, Custom);
613
614     // Use XORP to simulate FNEG.
615     setOperationAction(ISD::FNEG , MVT::f32, Custom);
616
617     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
618
619     // Use ANDPS and ORPS to simulate FCOPYSIGN.
620     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
622
623     // We don't support sin/cos/fmod
624     setOperationAction(ISD::FSIN , MVT::f32, Expand);
625     setOperationAction(ISD::FCOS , MVT::f32, Expand);
626
627     // Special cases we handle for FP constants.
628     addLegalFPImmediate(APFloat(+0.0f)); // xorps
629     addLegalFPImmediate(APFloat(+0.0)); // FLD0
630     addLegalFPImmediate(APFloat(+1.0)); // FLD1
631     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
632     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
633
634     if (!TM.Options.UnsafeFPMath) {
635       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
636       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
637     }
638   } else if (!TM.Options.UseSoftFloat) {
639     // f32 and f64 in x87.
640     // Set up the FP register classes.
641     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
642     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
643
644     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
645     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
646     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
647     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
648
649     if (!TM.Options.UnsafeFPMath) {
650       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
651       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
652     }
653     addLegalFPImmediate(APFloat(+0.0)); // FLD0
654     addLegalFPImmediate(APFloat(+1.0)); // FLD1
655     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
656     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
657     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
658     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
659     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
660     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
661   }
662
663   // We don't support FMA.
664   setOperationAction(ISD::FMA, MVT::f64, Expand);
665   setOperationAction(ISD::FMA, MVT::f32, Expand);
666
667   // Long double always uses X87.
668   if (!TM.Options.UseSoftFloat) {
669     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
670     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
671     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
672     {
673       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
674       addLegalFPImmediate(TmpFlt);  // FLD0
675       TmpFlt.changeSign();
676       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
677
678       bool ignored;
679       APFloat TmpFlt2(+1.0);
680       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
681                       &ignored);
682       addLegalFPImmediate(TmpFlt2);  // FLD1
683       TmpFlt2.changeSign();
684       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
685     }
686
687     if (!TM.Options.UnsafeFPMath) {
688       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
689       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
690     }
691
692     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
693     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
694     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
695     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
696     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
697     setOperationAction(ISD::FMA, MVT::f80, Expand);
698   }
699
700   // Always use a library call for pow.
701   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
702   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
703   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
704
705   setOperationAction(ISD::FLOG, MVT::f80, Expand);
706   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
707   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
708   setOperationAction(ISD::FEXP, MVT::f80, Expand);
709   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
710
711   // First set operation action for all vector types to either promote
712   // (for widening) or expand (for scalarization). Then we will selectively
713   // turn on ones that can be effectively codegen'd.
714   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
715            VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
716     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
731     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
733     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
734     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::FMA,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
769     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
770     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
772     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
774     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
775              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
776       setTruncStoreAction((MVT::SimpleValueType)VT,
777                           (MVT::SimpleValueType)InnerVT, Expand);
778     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
779     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
780     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
781   }
782
783   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
784   // with -msoft-float, disable use of MMX as well.
785   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
786     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
787     // No operations on x86mmx supported, everything uses intrinsics.
788   }
789
790   // MMX-sized vectors (other than x86mmx) are expected to be expanded
791   // into smaller operations.
792   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
793   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
794   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
795   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
796   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
797   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
798   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
799   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
800   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
801   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
802   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
803   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
804   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
805   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
806   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
807   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
808   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
809   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
810   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
811   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
812   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
813   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
814   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
815   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
816   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
817   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
818   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
819   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
820   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
821
822   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
823     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
824
825     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
826     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
827     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
828     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
829     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
830     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
831     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
832     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
833     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
834     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
835     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
836   }
837
838   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
839     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
840
841     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
842     // registers cannot be used even for integer operations.
843     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
844     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
845     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
846     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
847
848     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
849     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
850     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
851     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
852     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
853     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
854     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
855     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
856     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
857     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
858     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
859     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
860     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
861     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
862     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
863     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
864
865     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
866     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
867     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
868     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
869
870     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
871     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
872     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
873     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
874     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
875
876     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
877     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
878       MVT VT = (MVT::SimpleValueType)i;
879       // Do not attempt to custom lower non-power-of-2 vectors
880       if (!isPowerOf2_32(VT.getVectorNumElements()))
881         continue;
882       // Do not attempt to custom lower non-128-bit vectors
883       if (!VT.is128BitVector())
884         continue;
885       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
886       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
887       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
888     }
889
890     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
891     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
892     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
893     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
894     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
895     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
896
897     if (Subtarget->is64Bit()) {
898       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
899       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
900     }
901
902     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
903     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
904       MVT VT = (MVT::SimpleValueType)i;
905
906       // Do not attempt to promote non-128-bit vectors
907       if (!VT.is128BitVector())
908         continue;
909
910       setOperationAction(ISD::AND,    VT, Promote);
911       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
912       setOperationAction(ISD::OR,     VT, Promote);
913       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
914       setOperationAction(ISD::XOR,    VT, Promote);
915       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
916       setOperationAction(ISD::LOAD,   VT, Promote);
917       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
918       setOperationAction(ISD::SELECT, VT, Promote);
919       AddPromotedToType (ISD::SELECT, VT, 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 (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1007     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1008     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1009     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1010     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1011     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1012     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1013
1014     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1015     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1016     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1017
1018     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1019     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1020     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1021     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1022     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1023     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1024
1025     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1026     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1027     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1028     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1029     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1030     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1031
1032     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1033     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1034     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1035
1036     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1037     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1038
1039     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1040     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1041
1042     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1043     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1044
1045     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1046     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1047     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1048     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1049
1050     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1051     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1052     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1053
1054     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1055     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1056     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1057     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1058
1059     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1060       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1061       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1062       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1063       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1064       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1065       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1066     }
1067
1068     if (Subtarget->hasAVX2()) {
1069       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1070       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1071       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1072       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1073
1074       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1075       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1076       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1077       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1078
1079       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1080       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1081       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1082       // Don't lower v32i8 because there is no 128-bit byte mul
1083
1084       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1085
1086       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1087       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1088
1089       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1090       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1091
1092       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1093     } else {
1094       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1095       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1096       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1097       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1098
1099       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1100       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1101       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1102       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1103
1104       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1105       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1106       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1107       // Don't lower v32i8 because there is no 128-bit byte mul
1108
1109       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1110       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1111
1112       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1113       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1114
1115       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1116     }
1117
1118     // Custom lower several nodes for 256-bit types.
1119     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1120              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1121       MVT VT = (MVT::SimpleValueType)i;
1122
1123       // Extract subvector is special because the value type
1124       // (result) is 128-bit but the source is 256-bit wide.
1125       if (VT.is128BitVector())
1126         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1127
1128       // Do not attempt to custom lower other non-256-bit vectors
1129       if (!VT.is256BitVector())
1130         continue;
1131
1132       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1133       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1134       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1135       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1136       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1137       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1138       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1139     }
1140
1141     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1142     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1143       MVT VT = (MVT::SimpleValueType)i;
1144
1145       // Do not attempt to promote non-256-bit vectors
1146       if (!VT.is256BitVector())
1147         continue;
1148
1149       setOperationAction(ISD::AND,    VT, Promote);
1150       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1151       setOperationAction(ISD::OR,     VT, Promote);
1152       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1153       setOperationAction(ISD::XOR,    VT, Promote);
1154       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1155       setOperationAction(ISD::LOAD,   VT, Promote);
1156       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1157       setOperationAction(ISD::SELECT, VT, Promote);
1158       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1159     }
1160   }
1161
1162   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1163   // of this type with custom code.
1164   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1165            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1166     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1167                        Custom);
1168   }
1169
1170   // We want to custom lower some of our intrinsics.
1171   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1172   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1173
1174
1175   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1176   // handle type legalization for these operations here.
1177   //
1178   // FIXME: We really should do custom legalization for addition and
1179   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1180   // than generic legalization for 64-bit multiplication-with-overflow, though.
1181   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1182     // Add/Sub/Mul with overflow operations are custom lowered.
1183     MVT VT = IntVTs[i];
1184     setOperationAction(ISD::SADDO, VT, Custom);
1185     setOperationAction(ISD::UADDO, VT, Custom);
1186     setOperationAction(ISD::SSUBO, VT, Custom);
1187     setOperationAction(ISD::USUBO, VT, Custom);
1188     setOperationAction(ISD::SMULO, VT, Custom);
1189     setOperationAction(ISD::UMULO, VT, Custom);
1190   }
1191
1192   // There are no 8-bit 3-address imul/mul instructions
1193   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1194   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1195
1196   if (!Subtarget->is64Bit()) {
1197     // These libcalls are not available in 32-bit.
1198     setLibcallName(RTLIB::SHL_I128, 0);
1199     setLibcallName(RTLIB::SRL_I128, 0);
1200     setLibcallName(RTLIB::SRA_I128, 0);
1201   }
1202
1203   // We have target-specific dag combine patterns for the following nodes:
1204   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1205   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1206   setTargetDAGCombine(ISD::VSELECT);
1207   setTargetDAGCombine(ISD::SELECT);
1208   setTargetDAGCombine(ISD::SHL);
1209   setTargetDAGCombine(ISD::SRA);
1210   setTargetDAGCombine(ISD::SRL);
1211   setTargetDAGCombine(ISD::OR);
1212   setTargetDAGCombine(ISD::AND);
1213   setTargetDAGCombine(ISD::ADD);
1214   setTargetDAGCombine(ISD::FADD);
1215   setTargetDAGCombine(ISD::FSUB);
1216   setTargetDAGCombine(ISD::FMA);
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   setTargetDAGCombine(ISD::XOR);
1231
1232   computeRegisterProperties();
1233
1234   // On Darwin, -Os means optimize for size without hurting performance,
1235   // do not reduce the limit.
1236   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1237   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1238   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1239   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1240   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1241   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1242   setPrefLoopAlignment(4); // 2^4 bytes.
1243   benefitFromCodePlacementOpt = true;
1244
1245   // Predictable cmov don't hurt on atom because it's in-order.
1246   predictableSelectIsExpensive = !Subtarget->isAtom();
1247
1248   setPrefFunctionAlignment(4); // 2^4 bytes.
1249 }
1250
1251
1252 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1253   if (!VT.isVector()) return MVT::i8;
1254   return VT.changeVectorElementTypeToInteger();
1255 }
1256
1257
1258 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1259 /// the desired ByVal argument alignment.
1260 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1261   if (MaxAlign == 16)
1262     return;
1263   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1264     if (VTy->getBitWidth() == 128)
1265       MaxAlign = 16;
1266   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1267     unsigned EltAlign = 0;
1268     getMaxByValAlign(ATy->getElementType(), EltAlign);
1269     if (EltAlign > MaxAlign)
1270       MaxAlign = EltAlign;
1271   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1272     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1273       unsigned EltAlign = 0;
1274       getMaxByValAlign(STy->getElementType(i), EltAlign);
1275       if (EltAlign > MaxAlign)
1276         MaxAlign = EltAlign;
1277       if (MaxAlign == 16)
1278         break;
1279     }
1280   }
1281 }
1282
1283 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1284 /// function arguments in the caller parameter area. For X86, aggregates
1285 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1286 /// are at 4-byte boundaries.
1287 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1288   if (Subtarget->is64Bit()) {
1289     // Max of 8 and alignment of type.
1290     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1291     if (TyAlign > 8)
1292       return TyAlign;
1293     return 8;
1294   }
1295
1296   unsigned Align = 4;
1297   if (Subtarget->hasSSE1())
1298     getMaxByValAlign(Ty, Align);
1299   return Align;
1300 }
1301
1302 /// getOptimalMemOpType - Returns the target specific optimal type for load
1303 /// and store operations as a result of memset, memcpy, and memmove
1304 /// lowering. If DstAlign is zero that means it's safe to destination
1305 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1306 /// means there isn't a need to check it against alignment requirement,
1307 /// probably because the source does not need to be loaded. If
1308 /// 'IsZeroVal' is true, that means it's safe to return a
1309 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1310 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1311 /// constant so it does not need to be loaded.
1312 /// It returns EVT::Other if the type should be determined using generic
1313 /// target-independent logic.
1314 EVT
1315 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1316                                        unsigned DstAlign, unsigned SrcAlign,
1317                                        bool IsZeroVal,
1318                                        bool MemcpyStrSrc,
1319                                        MachineFunction &MF) const {
1320   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1321   // linux.  This is because the stack realignment code can't handle certain
1322   // cases like PR2962.  This should be removed when PR2962 is fixed.
1323   const Function *F = MF.getFunction();
1324   if (IsZeroVal &&
1325       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1326     if (Size >= 16 &&
1327         (Subtarget->isUnalignedMemAccessFast() ||
1328          ((DstAlign == 0 || DstAlign >= 16) &&
1329           (SrcAlign == 0 || SrcAlign >= 16))) &&
1330         Subtarget->getStackAlignment() >= 16) {
1331       if (Subtarget->getStackAlignment() >= 32) {
1332         if (Subtarget->hasAVX2())
1333           return MVT::v8i32;
1334         if (Subtarget->hasAVX())
1335           return MVT::v8f32;
1336       }
1337       if (Subtarget->hasSSE2())
1338         return MVT::v4i32;
1339       if (Subtarget->hasSSE1())
1340         return MVT::v4f32;
1341     } else if (!MemcpyStrSrc && Size >= 8 &&
1342                !Subtarget->is64Bit() &&
1343                Subtarget->getStackAlignment() >= 8 &&
1344                Subtarget->hasSSE2()) {
1345       // Do not use f64 to lower memcpy if source is string constant. It's
1346       // better to use i32 to avoid the loads.
1347       return MVT::f64;
1348     }
1349   }
1350   if (Subtarget->is64Bit() && Size >= 8)
1351     return MVT::i64;
1352   return MVT::i32;
1353 }
1354
1355 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1356 /// current function.  The returned value is a member of the
1357 /// MachineJumpTableInfo::JTEntryKind enum.
1358 unsigned X86TargetLowering::getJumpTableEncoding() const {
1359   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1360   // symbol.
1361   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1362       Subtarget->isPICStyleGOT())
1363     return MachineJumpTableInfo::EK_Custom32;
1364
1365   // Otherwise, use the normal jump table encoding heuristics.
1366   return TargetLowering::getJumpTableEncoding();
1367 }
1368
1369 const MCExpr *
1370 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1371                                              const MachineBasicBlock *MBB,
1372                                              unsigned uid,MCContext &Ctx) const{
1373   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1374          Subtarget->isPICStyleGOT());
1375   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1376   // entries.
1377   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1378                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1379 }
1380
1381 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1382 /// jumptable.
1383 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1384                                                     SelectionDAG &DAG) const {
1385   if (!Subtarget->is64Bit())
1386     // This doesn't have DebugLoc associated with it, but is not really the
1387     // same as a Register.
1388     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1389   return Table;
1390 }
1391
1392 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1393 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1394 /// MCExpr.
1395 const MCExpr *X86TargetLowering::
1396 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1397                              MCContext &Ctx) const {
1398   // X86-64 uses RIP relative addressing based on the jump table label.
1399   if (Subtarget->isPICStyleRIPRel())
1400     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1401
1402   // Otherwise, the reference is relative to the PIC base.
1403   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1404 }
1405
1406 // FIXME: Why this routine is here? Move to RegInfo!
1407 std::pair<const TargetRegisterClass*, uint8_t>
1408 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1409   const TargetRegisterClass *RRC = 0;
1410   uint8_t Cost = 1;
1411   switch (VT.getSimpleVT().SimpleTy) {
1412   default:
1413     return TargetLowering::findRepresentativeClass(VT);
1414   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1415     RRC = Subtarget->is64Bit() ?
1416       (const TargetRegisterClass*)&X86::GR64RegClass :
1417       (const TargetRegisterClass*)&X86::GR32RegClass;
1418     break;
1419   case MVT::x86mmx:
1420     RRC = &X86::VR64RegClass;
1421     break;
1422   case MVT::f32: case MVT::f64:
1423   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1424   case MVT::v4f32: case MVT::v2f64:
1425   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1426   case MVT::v4f64:
1427     RRC = &X86::VR128RegClass;
1428     break;
1429   }
1430   return std::make_pair(RRC, Cost);
1431 }
1432
1433 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1434                                                unsigned &Offset) const {
1435   if (!Subtarget->isTargetLinux())
1436     return false;
1437
1438   if (Subtarget->is64Bit()) {
1439     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1440     Offset = 0x28;
1441     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1442       AddressSpace = 256;
1443     else
1444       AddressSpace = 257;
1445   } else {
1446     // %gs:0x14 on i386
1447     Offset = 0x14;
1448     AddressSpace = 256;
1449   }
1450   return true;
1451 }
1452
1453
1454 //===----------------------------------------------------------------------===//
1455 //               Return Value Calling Convention Implementation
1456 //===----------------------------------------------------------------------===//
1457
1458 #include "X86GenCallingConv.inc"
1459
1460 bool
1461 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1462                                   MachineFunction &MF, bool isVarArg,
1463                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1464                         LLVMContext &Context) const {
1465   SmallVector<CCValAssign, 16> RVLocs;
1466   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1467                  RVLocs, Context);
1468   return CCInfo.CheckReturn(Outs, RetCC_X86);
1469 }
1470
1471 SDValue
1472 X86TargetLowering::LowerReturn(SDValue Chain,
1473                                CallingConv::ID CallConv, bool isVarArg,
1474                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1475                                const SmallVectorImpl<SDValue> &OutVals,
1476                                DebugLoc dl, SelectionDAG &DAG) const {
1477   MachineFunction &MF = DAG.getMachineFunction();
1478   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1479
1480   SmallVector<CCValAssign, 16> RVLocs;
1481   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1482                  RVLocs, *DAG.getContext());
1483   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1484
1485   // Add the regs to the liveout set for the function.
1486   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1487   for (unsigned i = 0; i != RVLocs.size(); ++i)
1488     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1489       MRI.addLiveOut(RVLocs[i].getLocReg());
1490
1491   SDValue Flag;
1492
1493   SmallVector<SDValue, 6> RetOps;
1494   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1495   // Operand #1 = Bytes To Pop
1496   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1497                    MVT::i16));
1498
1499   // Copy the result values into the output registers.
1500   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1501     CCValAssign &VA = RVLocs[i];
1502     assert(VA.isRegLoc() && "Can only return in registers!");
1503     SDValue ValToCopy = OutVals[i];
1504     EVT ValVT = ValToCopy.getValueType();
1505
1506     // Promote values to the appropriate types
1507     if (VA.getLocInfo() == CCValAssign::SExt)
1508       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1509     else if (VA.getLocInfo() == CCValAssign::ZExt)
1510       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1511     else if (VA.getLocInfo() == CCValAssign::AExt)
1512       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1513     else if (VA.getLocInfo() == CCValAssign::BCvt)
1514       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1515
1516     // If this is x86-64, and we disabled SSE, we can't return FP values,
1517     // or SSE or MMX vectors.
1518     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1519          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1520           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1521       report_fatal_error("SSE register return with SSE disabled");
1522     }
1523     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1524     // llvm-gcc has never done it right and no one has noticed, so this
1525     // should be OK for now.
1526     if (ValVT == MVT::f64 &&
1527         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1528       report_fatal_error("SSE2 register return with SSE2 disabled");
1529
1530     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1531     // the RET instruction and handled by the FP Stackifier.
1532     if (VA.getLocReg() == X86::ST0 ||
1533         VA.getLocReg() == X86::ST1) {
1534       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1535       // change the value to the FP stack register class.
1536       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1537         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1538       RetOps.push_back(ValToCopy);
1539       // Don't emit a copytoreg.
1540       continue;
1541     }
1542
1543     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1544     // which is returned in RAX / RDX.
1545     if (Subtarget->is64Bit()) {
1546       if (ValVT == MVT::x86mmx) {
1547         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1548           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1549           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1550                                   ValToCopy);
1551           // If we don't have SSE2 available, convert to v4f32 so the generated
1552           // register is legal.
1553           if (!Subtarget->hasSSE2())
1554             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1555         }
1556       }
1557     }
1558
1559     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1560     Flag = Chain.getValue(1);
1561   }
1562
1563   // The x86-64 ABI for returning structs by value requires that we copy
1564   // the sret argument into %rax for the return. We saved the argument into
1565   // a virtual register in the entry block, so now we copy the value out
1566   // and into %rax.
1567   if (Subtarget->is64Bit() &&
1568       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1569     MachineFunction &MF = DAG.getMachineFunction();
1570     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1571     unsigned Reg = FuncInfo->getSRetReturnReg();
1572     assert(Reg &&
1573            "SRetReturnReg should have been set in LowerFormalArguments().");
1574     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1575
1576     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1577     Flag = Chain.getValue(1);
1578
1579     // RAX now acts like a return value.
1580     MRI.addLiveOut(X86::RAX);
1581   }
1582
1583   RetOps[0] = Chain;  // Update chain.
1584
1585   // Add the flag if we have it.
1586   if (Flag.getNode())
1587     RetOps.push_back(Flag);
1588
1589   return DAG.getNode(X86ISD::RET_FLAG, dl,
1590                      MVT::Other, &RetOps[0], RetOps.size());
1591 }
1592
1593 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1594   if (N->getNumValues() != 1)
1595     return false;
1596   if (!N->hasNUsesOfValue(1, 0))
1597     return false;
1598
1599   SDValue TCChain = Chain;
1600   SDNode *Copy = *N->use_begin();
1601   if (Copy->getOpcode() == ISD::CopyToReg) {
1602     // If the copy has a glue operand, we conservatively assume it isn't safe to
1603     // perform a tail call.
1604     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1605       return false;
1606     TCChain = Copy->getOperand(0);
1607   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1608     return false;
1609
1610   bool HasRet = false;
1611   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1612        UI != UE; ++UI) {
1613     if (UI->getOpcode() != X86ISD::RET_FLAG)
1614       return false;
1615     HasRet = true;
1616   }
1617
1618   if (!HasRet)
1619     return false;
1620
1621   Chain = TCChain;
1622   return true;
1623 }
1624
1625 EVT
1626 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1627                                             ISD::NodeType ExtendKind) const {
1628   MVT ReturnMVT;
1629   // TODO: Is this also valid on 32-bit?
1630   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1631     ReturnMVT = MVT::i8;
1632   else
1633     ReturnMVT = MVT::i32;
1634
1635   EVT MinVT = getRegisterType(Context, ReturnMVT);
1636   return VT.bitsLT(MinVT) ? MinVT : VT;
1637 }
1638
1639 /// LowerCallResult - Lower the result values of a call into the
1640 /// appropriate copies out of appropriate physical registers.
1641 ///
1642 SDValue
1643 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1644                                    CallingConv::ID CallConv, bool isVarArg,
1645                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1646                                    DebugLoc dl, SelectionDAG &DAG,
1647                                    SmallVectorImpl<SDValue> &InVals) const {
1648
1649   // Assign locations to each value returned by this call.
1650   SmallVector<CCValAssign, 16> RVLocs;
1651   bool Is64Bit = Subtarget->is64Bit();
1652   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1653                  getTargetMachine(), RVLocs, *DAG.getContext());
1654   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1655
1656   // Copy all of the result registers out of their specified physreg.
1657   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1658     CCValAssign &VA = RVLocs[i];
1659     EVT CopyVT = VA.getValVT();
1660
1661     // If this is x86-64, and we disabled SSE, we can't return FP values
1662     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1663         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1664       report_fatal_error("SSE register return with SSE disabled");
1665     }
1666
1667     SDValue Val;
1668
1669     // If this is a call to a function that returns an fp value on the floating
1670     // point stack, we must guarantee the value is popped from the stack, so
1671     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1672     // if the return value is not used. We use the FpPOP_RETVAL instruction
1673     // instead.
1674     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1675       // If we prefer to use the value in xmm registers, copy it out as f80 and
1676       // use a truncate to move it from fp stack reg to xmm reg.
1677       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1678       SDValue Ops[] = { Chain, InFlag };
1679       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1680                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1681       Val = Chain.getValue(0);
1682
1683       // Round the f80 to the right size, which also moves it to the appropriate
1684       // xmm register.
1685       if (CopyVT != VA.getValVT())
1686         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1687                           // This truncation won't change the value.
1688                           DAG.getIntPtrConstant(1));
1689     } else {
1690       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1691                                  CopyVT, InFlag).getValue(1);
1692       Val = Chain.getValue(0);
1693     }
1694     InFlag = Chain.getValue(2);
1695     InVals.push_back(Val);
1696   }
1697
1698   return Chain;
1699 }
1700
1701
1702 //===----------------------------------------------------------------------===//
1703 //                C & StdCall & Fast Calling Convention implementation
1704 //===----------------------------------------------------------------------===//
1705 //  StdCall calling convention seems to be standard for many Windows' API
1706 //  routines and around. It differs from C calling convention just a little:
1707 //  callee should clean up the stack, not caller. Symbols should be also
1708 //  decorated in some fancy way :) It doesn't support any vector arguments.
1709 //  For info on fast calling convention see Fast Calling Convention (tail call)
1710 //  implementation LowerX86_32FastCCCallTo.
1711
1712 /// CallIsStructReturn - Determines whether a call uses struct return
1713 /// semantics.
1714 enum StructReturnType {
1715   NotStructReturn,
1716   RegStructReturn,
1717   StackStructReturn
1718 };
1719 static StructReturnType
1720 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1721   if (Outs.empty())
1722     return NotStructReturn;
1723
1724   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1725   if (!Flags.isSRet())
1726     return NotStructReturn;
1727   if (Flags.isInReg())
1728     return RegStructReturn;
1729   return StackStructReturn;
1730 }
1731
1732 /// ArgsAreStructReturn - Determines whether a function uses struct
1733 /// return semantics.
1734 static StructReturnType
1735 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1736   if (Ins.empty())
1737     return NotStructReturn;
1738
1739   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1740   if (!Flags.isSRet())
1741     return NotStructReturn;
1742   if (Flags.isInReg())
1743     return RegStructReturn;
1744   return StackStructReturn;
1745 }
1746
1747 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1748 /// by "Src" to address "Dst" with size and alignment information specified by
1749 /// the specific parameter attribute. The copy will be passed as a byval
1750 /// function parameter.
1751 static SDValue
1752 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1753                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1754                           DebugLoc dl) {
1755   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1756
1757   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1758                        /*isVolatile*/false, /*AlwaysInline=*/true,
1759                        MachinePointerInfo(), MachinePointerInfo());
1760 }
1761
1762 /// IsTailCallConvention - Return true if the calling convention is one that
1763 /// supports tail call optimization.
1764 static bool IsTailCallConvention(CallingConv::ID CC) {
1765   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1766 }
1767
1768 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1769   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1770     return false;
1771
1772   CallSite CS(CI);
1773   CallingConv::ID CalleeCC = CS.getCallingConv();
1774   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1775     return false;
1776
1777   return true;
1778 }
1779
1780 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1781 /// a tailcall target by changing its ABI.
1782 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1783                                    bool GuaranteedTailCallOpt) {
1784   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1785 }
1786
1787 SDValue
1788 X86TargetLowering::LowerMemArgument(SDValue Chain,
1789                                     CallingConv::ID CallConv,
1790                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1791                                     DebugLoc dl, SelectionDAG &DAG,
1792                                     const CCValAssign &VA,
1793                                     MachineFrameInfo *MFI,
1794                                     unsigned i) const {
1795   // Create the nodes corresponding to a load from this parameter slot.
1796   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1797   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1798                               getTargetMachine().Options.GuaranteedTailCallOpt);
1799   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1800   EVT ValVT;
1801
1802   // If value is passed by pointer we have address passed instead of the value
1803   // itself.
1804   if (VA.getLocInfo() == CCValAssign::Indirect)
1805     ValVT = VA.getLocVT();
1806   else
1807     ValVT = VA.getValVT();
1808
1809   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1810   // changed with more analysis.
1811   // In case of tail call optimization mark all arguments mutable. Since they
1812   // could be overwritten by lowering of arguments in case of a tail call.
1813   if (Flags.isByVal()) {
1814     unsigned Bytes = Flags.getByValSize();
1815     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1816     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1817     return DAG.getFrameIndex(FI, getPointerTy());
1818   } else {
1819     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1820                                     VA.getLocMemOffset(), isImmutable);
1821     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1822     return DAG.getLoad(ValVT, dl, Chain, FIN,
1823                        MachinePointerInfo::getFixedStack(FI),
1824                        false, false, false, 0);
1825   }
1826 }
1827
1828 SDValue
1829 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1830                                         CallingConv::ID CallConv,
1831                                         bool isVarArg,
1832                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1833                                         DebugLoc dl,
1834                                         SelectionDAG &DAG,
1835                                         SmallVectorImpl<SDValue> &InVals)
1836                                           const {
1837   MachineFunction &MF = DAG.getMachineFunction();
1838   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1839
1840   const Function* Fn = MF.getFunction();
1841   if (Fn->hasExternalLinkage() &&
1842       Subtarget->isTargetCygMing() &&
1843       Fn->getName() == "main")
1844     FuncInfo->setForceFramePointer(true);
1845
1846   MachineFrameInfo *MFI = MF.getFrameInfo();
1847   bool Is64Bit = Subtarget->is64Bit();
1848   bool IsWindows = Subtarget->isTargetWindows();
1849   bool IsWin64 = Subtarget->isTargetWin64();
1850
1851   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1852          "Var args not supported with calling convention fastcc or ghc");
1853
1854   // Assign locations to all of the incoming arguments.
1855   SmallVector<CCValAssign, 16> ArgLocs;
1856   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1857                  ArgLocs, *DAG.getContext());
1858
1859   // Allocate shadow area for Win64
1860   if (IsWin64) {
1861     CCInfo.AllocateStack(32, 8);
1862   }
1863
1864   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1865
1866   unsigned LastVal = ~0U;
1867   SDValue ArgValue;
1868   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1869     CCValAssign &VA = ArgLocs[i];
1870     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1871     // places.
1872     assert(VA.getValNo() != LastVal &&
1873            "Don't support value assigned to multiple locs yet");
1874     (void)LastVal;
1875     LastVal = VA.getValNo();
1876
1877     if (VA.isRegLoc()) {
1878       EVT RegVT = VA.getLocVT();
1879       const TargetRegisterClass *RC;
1880       if (RegVT == MVT::i32)
1881         RC = &X86::GR32RegClass;
1882       else if (Is64Bit && RegVT == MVT::i64)
1883         RC = &X86::GR64RegClass;
1884       else if (RegVT == MVT::f32)
1885         RC = &X86::FR32RegClass;
1886       else if (RegVT == MVT::f64)
1887         RC = &X86::FR64RegClass;
1888       else if (RegVT.is256BitVector())
1889         RC = &X86::VR256RegClass;
1890       else if (RegVT.is128BitVector())
1891         RC = &X86::VR128RegClass;
1892       else if (RegVT == MVT::x86mmx)
1893         RC = &X86::VR64RegClass;
1894       else
1895         llvm_unreachable("Unknown argument type!");
1896
1897       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1898       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1899
1900       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1901       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1902       // right size.
1903       if (VA.getLocInfo() == CCValAssign::SExt)
1904         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1905                                DAG.getValueType(VA.getValVT()));
1906       else if (VA.getLocInfo() == CCValAssign::ZExt)
1907         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1908                                DAG.getValueType(VA.getValVT()));
1909       else if (VA.getLocInfo() == CCValAssign::BCvt)
1910         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1911
1912       if (VA.isExtInLoc()) {
1913         // Handle MMX values passed in XMM regs.
1914         if (RegVT.isVector()) {
1915           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1916                                  ArgValue);
1917         } else
1918           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1919       }
1920     } else {
1921       assert(VA.isMemLoc());
1922       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1923     }
1924
1925     // If value is passed via pointer - do a load.
1926     if (VA.getLocInfo() == CCValAssign::Indirect)
1927       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1928                              MachinePointerInfo(), false, false, false, 0);
1929
1930     InVals.push_back(ArgValue);
1931   }
1932
1933   // The x86-64 ABI for returning structs by value requires that we copy
1934   // the sret argument into %rax for the return. Save the argument into
1935   // a virtual register so that we can access it from the return points.
1936   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1937     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1938     unsigned Reg = FuncInfo->getSRetReturnReg();
1939     if (!Reg) {
1940       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1941       FuncInfo->setSRetReturnReg(Reg);
1942     }
1943     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1944     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1945   }
1946
1947   unsigned StackSize = CCInfo.getNextStackOffset();
1948   // Align stack specially for tail calls.
1949   if (FuncIsMadeTailCallSafe(CallConv,
1950                              MF.getTarget().Options.GuaranteedTailCallOpt))
1951     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1952
1953   // If the function takes variable number of arguments, make a frame index for
1954   // the start of the first vararg value... for expansion of llvm.va_start.
1955   if (isVarArg) {
1956     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1957                     CallConv != CallingConv::X86_ThisCall)) {
1958       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1959     }
1960     if (Is64Bit) {
1961       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1962
1963       // FIXME: We should really autogenerate these arrays
1964       static const uint16_t GPR64ArgRegsWin64[] = {
1965         X86::RCX, X86::RDX, X86::R8,  X86::R9
1966       };
1967       static const uint16_t GPR64ArgRegs64Bit[] = {
1968         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1969       };
1970       static const uint16_t XMMArgRegs64Bit[] = {
1971         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1972         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1973       };
1974       const uint16_t *GPR64ArgRegs;
1975       unsigned NumXMMRegs = 0;
1976
1977       if (IsWin64) {
1978         // The XMM registers which might contain var arg parameters are shadowed
1979         // in their paired GPR.  So we only need to save the GPR to their home
1980         // slots.
1981         TotalNumIntRegs = 4;
1982         GPR64ArgRegs = GPR64ArgRegsWin64;
1983       } else {
1984         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1985         GPR64ArgRegs = GPR64ArgRegs64Bit;
1986
1987         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1988                                                 TotalNumXMMRegs);
1989       }
1990       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1991                                                        TotalNumIntRegs);
1992
1993       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1994       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1995              "SSE register cannot be used when SSE is disabled!");
1996       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1997                NoImplicitFloatOps) &&
1998              "SSE register cannot be used when SSE is disabled!");
1999       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2000           !Subtarget->hasSSE1())
2001         // Kernel mode asks for SSE to be disabled, so don't push them
2002         // on the stack.
2003         TotalNumXMMRegs = 0;
2004
2005       if (IsWin64) {
2006         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2007         // Get to the caller-allocated home save location.  Add 8 to account
2008         // for the return address.
2009         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2010         FuncInfo->setRegSaveFrameIndex(
2011           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2012         // Fixup to set vararg frame on shadow area (4 x i64).
2013         if (NumIntRegs < 4)
2014           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2015       } else {
2016         // For X86-64, if there are vararg parameters that are passed via
2017         // registers, then we must store them to their spots on the stack so
2018         // they may be loaded by deferencing the result of va_next.
2019         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2020         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2021         FuncInfo->setRegSaveFrameIndex(
2022           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2023                                false));
2024       }
2025
2026       // Store the integer parameter registers.
2027       SmallVector<SDValue, 8> MemOps;
2028       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2029                                         getPointerTy());
2030       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2031       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2032         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2033                                   DAG.getIntPtrConstant(Offset));
2034         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2035                                      &X86::GR64RegClass);
2036         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2037         SDValue Store =
2038           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2039                        MachinePointerInfo::getFixedStack(
2040                          FuncInfo->getRegSaveFrameIndex(), Offset),
2041                        false, false, 0);
2042         MemOps.push_back(Store);
2043         Offset += 8;
2044       }
2045
2046       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2047         // Now store the XMM (fp + vector) parameter registers.
2048         SmallVector<SDValue, 11> SaveXMMOps;
2049         SaveXMMOps.push_back(Chain);
2050
2051         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2052         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2053         SaveXMMOps.push_back(ALVal);
2054
2055         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2056                                FuncInfo->getRegSaveFrameIndex()));
2057         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2058                                FuncInfo->getVarArgsFPOffset()));
2059
2060         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2061           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2062                                        &X86::VR128RegClass);
2063           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2064           SaveXMMOps.push_back(Val);
2065         }
2066         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2067                                      MVT::Other,
2068                                      &SaveXMMOps[0], SaveXMMOps.size()));
2069       }
2070
2071       if (!MemOps.empty())
2072         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2073                             &MemOps[0], MemOps.size());
2074     }
2075   }
2076
2077   // Some CCs need callee pop.
2078   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2079                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2080     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2081   } else {
2082     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2083     // If this is an sret function, the return should pop the hidden pointer.
2084     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2085         argsAreStructReturn(Ins) == StackStructReturn)
2086       FuncInfo->setBytesToPopOnReturn(4);
2087   }
2088
2089   if (!Is64Bit) {
2090     // RegSaveFrameIndex is X86-64 only.
2091     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2092     if (CallConv == CallingConv::X86_FastCall ||
2093         CallConv == CallingConv::X86_ThisCall)
2094       // fastcc functions can't have varargs.
2095       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2096   }
2097
2098   FuncInfo->setArgumentStackSize(StackSize);
2099
2100   return Chain;
2101 }
2102
2103 SDValue
2104 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2105                                     SDValue StackPtr, SDValue Arg,
2106                                     DebugLoc dl, SelectionDAG &DAG,
2107                                     const CCValAssign &VA,
2108                                     ISD::ArgFlagsTy Flags) const {
2109   unsigned LocMemOffset = VA.getLocMemOffset();
2110   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2111   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2112   if (Flags.isByVal())
2113     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2114
2115   return DAG.getStore(Chain, dl, Arg, PtrOff,
2116                       MachinePointerInfo::getStack(LocMemOffset),
2117                       false, false, 0);
2118 }
2119
2120 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2121 /// optimization is performed and it is required.
2122 SDValue
2123 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2124                                            SDValue &OutRetAddr, SDValue Chain,
2125                                            bool IsTailCall, bool Is64Bit,
2126                                            int FPDiff, DebugLoc dl) const {
2127   // Adjust the Return address stack slot.
2128   EVT VT = getPointerTy();
2129   OutRetAddr = getReturnAddressFrameIndex(DAG);
2130
2131   // Load the "old" Return address.
2132   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2133                            false, false, false, 0);
2134   return SDValue(OutRetAddr.getNode(), 1);
2135 }
2136
2137 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2138 /// optimization is performed and it is required (FPDiff!=0).
2139 static SDValue
2140 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2141                          SDValue Chain, SDValue RetAddrFrIdx,
2142                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2143   // Store the return address to the appropriate stack slot.
2144   if (!FPDiff) return Chain;
2145   // Calculate the new stack slot for the return address.
2146   int SlotSize = Is64Bit ? 8 : 4;
2147   int NewReturnAddrFI =
2148     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2149   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2150   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2151   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2152                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2153                        false, false, 0);
2154   return Chain;
2155 }
2156
2157 SDValue
2158 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2159                              SmallVectorImpl<SDValue> &InVals) const {
2160   SelectionDAG &DAG                     = CLI.DAG;
2161   DebugLoc &dl                          = CLI.DL;
2162   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2163   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2164   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2165   SDValue Chain                         = CLI.Chain;
2166   SDValue Callee                        = CLI.Callee;
2167   CallingConv::ID CallConv              = CLI.CallConv;
2168   bool &isTailCall                      = CLI.IsTailCall;
2169   bool isVarArg                         = CLI.IsVarArg;
2170
2171   MachineFunction &MF = DAG.getMachineFunction();
2172   bool Is64Bit        = Subtarget->is64Bit();
2173   bool IsWin64        = Subtarget->isTargetWin64();
2174   bool IsWindows      = Subtarget->isTargetWindows();
2175   StructReturnType SR = callIsStructReturn(Outs);
2176   bool IsSibcall      = false;
2177
2178   if (MF.getTarget().Options.DisableTailCalls)
2179     isTailCall = false;
2180
2181   if (isTailCall) {
2182     // Check if it's really possible to do a tail call.
2183     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2184                     isVarArg, SR != NotStructReturn,
2185                     MF.getFunction()->hasStructRetAttr(),
2186                     Outs, OutVals, Ins, DAG);
2187
2188     // Sibcalls are automatically detected tailcalls which do not require
2189     // ABI changes.
2190     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2191       IsSibcall = true;
2192
2193     if (isTailCall)
2194       ++NumTailCalls;
2195   }
2196
2197   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2198          "Var args not supported with calling convention fastcc or ghc");
2199
2200   // Analyze operands of the call, assigning locations to each operand.
2201   SmallVector<CCValAssign, 16> ArgLocs;
2202   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2203                  ArgLocs, *DAG.getContext());
2204
2205   // Allocate shadow area for Win64
2206   if (IsWin64) {
2207     CCInfo.AllocateStack(32, 8);
2208   }
2209
2210   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2211
2212   // Get a count of how many bytes are to be pushed on the stack.
2213   unsigned NumBytes = CCInfo.getNextStackOffset();
2214   if (IsSibcall)
2215     // This is a sibcall. The memory operands are available in caller's
2216     // own caller's stack.
2217     NumBytes = 0;
2218   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2219            IsTailCallConvention(CallConv))
2220     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2221
2222   int FPDiff = 0;
2223   if (isTailCall && !IsSibcall) {
2224     // Lower arguments at fp - stackoffset + fpdiff.
2225     unsigned NumBytesCallerPushed =
2226       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2227     FPDiff = NumBytesCallerPushed - NumBytes;
2228
2229     // Set the delta of movement of the returnaddr stackslot.
2230     // But only set if delta is greater than previous delta.
2231     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2232       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2233   }
2234
2235   if (!IsSibcall)
2236     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2237
2238   SDValue RetAddrFrIdx;
2239   // Load return address for tail calls.
2240   if (isTailCall && FPDiff)
2241     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2242                                     Is64Bit, FPDiff, dl);
2243
2244   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2245   SmallVector<SDValue, 8> MemOpChains;
2246   SDValue StackPtr;
2247
2248   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2249   // of tail call optimization arguments are handle later.
2250   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2251     CCValAssign &VA = ArgLocs[i];
2252     EVT RegVT = VA.getLocVT();
2253     SDValue Arg = OutVals[i];
2254     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2255     bool isByVal = Flags.isByVal();
2256
2257     // Promote the value if needed.
2258     switch (VA.getLocInfo()) {
2259     default: llvm_unreachable("Unknown loc info!");
2260     case CCValAssign::Full: break;
2261     case CCValAssign::SExt:
2262       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2263       break;
2264     case CCValAssign::ZExt:
2265       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2266       break;
2267     case CCValAssign::AExt:
2268       if (RegVT.is128BitVector()) {
2269         // Special case: passing MMX values in XMM registers.
2270         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2271         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2272         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2273       } else
2274         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2275       break;
2276     case CCValAssign::BCvt:
2277       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2278       break;
2279     case CCValAssign::Indirect: {
2280       // Store the argument.
2281       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2282       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2283       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2284                            MachinePointerInfo::getFixedStack(FI),
2285                            false, false, 0);
2286       Arg = SpillSlot;
2287       break;
2288     }
2289     }
2290
2291     if (VA.isRegLoc()) {
2292       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2293       if (isVarArg && IsWin64) {
2294         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2295         // shadow reg if callee is a varargs function.
2296         unsigned ShadowReg = 0;
2297         switch (VA.getLocReg()) {
2298         case X86::XMM0: ShadowReg = X86::RCX; break;
2299         case X86::XMM1: ShadowReg = X86::RDX; break;
2300         case X86::XMM2: ShadowReg = X86::R8; break;
2301         case X86::XMM3: ShadowReg = X86::R9; break;
2302         }
2303         if (ShadowReg)
2304           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2305       }
2306     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2307       assert(VA.isMemLoc());
2308       if (StackPtr.getNode() == 0)
2309         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2310       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2311                                              dl, DAG, VA, Flags));
2312     }
2313   }
2314
2315   if (!MemOpChains.empty())
2316     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2317                         &MemOpChains[0], MemOpChains.size());
2318
2319   if (Subtarget->isPICStyleGOT()) {
2320     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2321     // GOT pointer.
2322     if (!isTailCall) {
2323       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2324                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2325     } else {
2326       // If we are tail calling and generating PIC/GOT style code load the
2327       // address of the callee into ECX. The value in ecx is used as target of
2328       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2329       // for tail calls on PIC/GOT architectures. Normally we would just put the
2330       // address of GOT into ebx and then call target@PLT. But for tail calls
2331       // ebx would be restored (since ebx is callee saved) before jumping to the
2332       // target@PLT.
2333
2334       // Note: The actual moving to ECX is done further down.
2335       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2336       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2337           !G->getGlobal()->hasProtectedVisibility())
2338         Callee = LowerGlobalAddress(Callee, DAG);
2339       else if (isa<ExternalSymbolSDNode>(Callee))
2340         Callee = LowerExternalSymbol(Callee, DAG);
2341     }
2342   }
2343
2344   if (Is64Bit && isVarArg && !IsWin64) {
2345     // From AMD64 ABI document:
2346     // For calls that may call functions that use varargs or stdargs
2347     // (prototype-less calls or calls to functions containing ellipsis (...) in
2348     // the declaration) %al is used as hidden argument to specify the number
2349     // of SSE registers used. The contents of %al do not need to match exactly
2350     // the number of registers, but must be an ubound on the number of SSE
2351     // registers used and is in the range 0 - 8 inclusive.
2352
2353     // Count the number of XMM registers allocated.
2354     static const uint16_t XMMArgRegs[] = {
2355       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2356       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2357     };
2358     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2359     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2360            && "SSE registers cannot be used when SSE is disabled");
2361
2362     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2363                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2364   }
2365
2366   // For tail calls lower the arguments to the 'real' stack slot.
2367   if (isTailCall) {
2368     // Force all the incoming stack arguments to be loaded from the stack
2369     // before any new outgoing arguments are stored to the stack, because the
2370     // outgoing stack slots may alias the incoming argument stack slots, and
2371     // the alias isn't otherwise explicit. This is slightly more conservative
2372     // than necessary, because it means that each store effectively depends
2373     // on every argument instead of just those arguments it would clobber.
2374     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2375
2376     SmallVector<SDValue, 8> MemOpChains2;
2377     SDValue FIN;
2378     int FI = 0;
2379     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2380       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2381         CCValAssign &VA = ArgLocs[i];
2382         if (VA.isRegLoc())
2383           continue;
2384         assert(VA.isMemLoc());
2385         SDValue Arg = OutVals[i];
2386         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2387         // Create frame index.
2388         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2389         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2390         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2391         FIN = DAG.getFrameIndex(FI, getPointerTy());
2392
2393         if (Flags.isByVal()) {
2394           // Copy relative to framepointer.
2395           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2396           if (StackPtr.getNode() == 0)
2397             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2398                                           getPointerTy());
2399           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2400
2401           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2402                                                            ArgChain,
2403                                                            Flags, DAG, dl));
2404         } else {
2405           // Store relative to framepointer.
2406           MemOpChains2.push_back(
2407             DAG.getStore(ArgChain, dl, Arg, FIN,
2408                          MachinePointerInfo::getFixedStack(FI),
2409                          false, false, 0));
2410         }
2411       }
2412     }
2413
2414     if (!MemOpChains2.empty())
2415       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2416                           &MemOpChains2[0], MemOpChains2.size());
2417
2418     // Store the return address to the appropriate stack slot.
2419     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2420                                      FPDiff, dl);
2421   }
2422
2423   // Build a sequence of copy-to-reg nodes chained together with token chain
2424   // and flag operands which copy the outgoing args into registers.
2425   SDValue InFlag;
2426   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2427     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2428                              RegsToPass[i].second, InFlag);
2429     InFlag = Chain.getValue(1);
2430   }
2431
2432   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2433     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2434     // In the 64-bit large code model, we have to make all calls
2435     // through a register, since the call instruction's 32-bit
2436     // pc-relative offset may not be large enough to hold the whole
2437     // address.
2438   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2439     // If the callee is a GlobalAddress node (quite common, every direct call
2440     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2441     // it.
2442
2443     // We should use extra load for direct calls to dllimported functions in
2444     // non-JIT mode.
2445     const GlobalValue *GV = G->getGlobal();
2446     if (!GV->hasDLLImportLinkage()) {
2447       unsigned char OpFlags = 0;
2448       bool ExtraLoad = false;
2449       unsigned WrapperKind = ISD::DELETED_NODE;
2450
2451       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2452       // external symbols most go through the PLT in PIC mode.  If the symbol
2453       // has hidden or protected visibility, or if it is static or local, then
2454       // we don't need to use the PLT - we can directly call it.
2455       if (Subtarget->isTargetELF() &&
2456           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2457           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2458         OpFlags = X86II::MO_PLT;
2459       } else if (Subtarget->isPICStyleStubAny() &&
2460                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2461                  (!Subtarget->getTargetTriple().isMacOSX() ||
2462                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2463         // PC-relative references to external symbols should go through $stub,
2464         // unless we're building with the leopard linker or later, which
2465         // automatically synthesizes these stubs.
2466         OpFlags = X86II::MO_DARWIN_STUB;
2467       } else if (Subtarget->isPICStyleRIPRel() &&
2468                  isa<Function>(GV) &&
2469                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2470         // If the function is marked as non-lazy, generate an indirect call
2471         // which loads from the GOT directly. This avoids runtime overhead
2472         // at the cost of eager binding (and one extra byte of encoding).
2473         OpFlags = X86II::MO_GOTPCREL;
2474         WrapperKind = X86ISD::WrapperRIP;
2475         ExtraLoad = true;
2476       }
2477
2478       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2479                                           G->getOffset(), OpFlags);
2480
2481       // Add a wrapper if needed.
2482       if (WrapperKind != ISD::DELETED_NODE)
2483         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2484       // Add extra indirection if needed.
2485       if (ExtraLoad)
2486         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2487                              MachinePointerInfo::getGOT(),
2488                              false, false, false, 0);
2489     }
2490   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2491     unsigned char OpFlags = 0;
2492
2493     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2494     // external symbols should go through the PLT.
2495     if (Subtarget->isTargetELF() &&
2496         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2497       OpFlags = X86II::MO_PLT;
2498     } else if (Subtarget->isPICStyleStubAny() &&
2499                (!Subtarget->getTargetTriple().isMacOSX() ||
2500                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2501       // PC-relative references to external symbols should go through $stub,
2502       // unless we're building with the leopard linker or later, which
2503       // automatically synthesizes these stubs.
2504       OpFlags = X86II::MO_DARWIN_STUB;
2505     }
2506
2507     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2508                                          OpFlags);
2509   }
2510
2511   // Returns a chain & a flag for retval copy to use.
2512   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2513   SmallVector<SDValue, 8> Ops;
2514
2515   if (!IsSibcall && isTailCall) {
2516     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2517                            DAG.getIntPtrConstant(0, true), InFlag);
2518     InFlag = Chain.getValue(1);
2519   }
2520
2521   Ops.push_back(Chain);
2522   Ops.push_back(Callee);
2523
2524   if (isTailCall)
2525     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2526
2527   // Add argument registers to the end of the list so that they are known live
2528   // into the call.
2529   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2530     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2531                                   RegsToPass[i].second.getValueType()));
2532
2533   // Add a register mask operand representing the call-preserved registers.
2534   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2535   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2536   assert(Mask && "Missing call preserved mask for calling convention");
2537   Ops.push_back(DAG.getRegisterMask(Mask));
2538
2539   if (InFlag.getNode())
2540     Ops.push_back(InFlag);
2541
2542   if (isTailCall) {
2543     // We used to do:
2544     //// If this is the first return lowered for this function, add the regs
2545     //// to the liveout set for the function.
2546     // This isn't right, although it's probably harmless on x86; liveouts
2547     // should be computed from returns not tail calls.  Consider a void
2548     // function making a tail call to a function returning int.
2549     return DAG.getNode(X86ISD::TC_RETURN, dl,
2550                        NodeTys, &Ops[0], Ops.size());
2551   }
2552
2553   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2554   InFlag = Chain.getValue(1);
2555
2556   // Create the CALLSEQ_END node.
2557   unsigned NumBytesForCalleeToPush;
2558   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2559                        getTargetMachine().Options.GuaranteedTailCallOpt))
2560     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2561   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2562            SR == StackStructReturn)
2563     // If this is a call to a struct-return function, the callee
2564     // pops the hidden struct pointer, so we have to push it back.
2565     // This is common for Darwin/X86, Linux & Mingw32 targets.
2566     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2567     NumBytesForCalleeToPush = 4;
2568   else
2569     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2570
2571   // Returns a flag for retval copy to use.
2572   if (!IsSibcall) {
2573     Chain = DAG.getCALLSEQ_END(Chain,
2574                                DAG.getIntPtrConstant(NumBytes, true),
2575                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2576                                                      true),
2577                                InFlag);
2578     InFlag = Chain.getValue(1);
2579   }
2580
2581   // Handle result values, copying them out of physregs into vregs that we
2582   // return.
2583   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2584                          Ins, dl, DAG, InVals);
2585 }
2586
2587
2588 //===----------------------------------------------------------------------===//
2589 //                Fast Calling Convention (tail call) implementation
2590 //===----------------------------------------------------------------------===//
2591
2592 //  Like std call, callee cleans arguments, convention except that ECX is
2593 //  reserved for storing the tail called function address. Only 2 registers are
2594 //  free for argument passing (inreg). Tail call optimization is performed
2595 //  provided:
2596 //                * tailcallopt is enabled
2597 //                * caller/callee are fastcc
2598 //  On X86_64 architecture with GOT-style position independent code only local
2599 //  (within module) calls are supported at the moment.
2600 //  To keep the stack aligned according to platform abi the function
2601 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2602 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2603 //  If a tail called function callee has more arguments than the caller the
2604 //  caller needs to make sure that there is room to move the RETADDR to. This is
2605 //  achieved by reserving an area the size of the argument delta right after the
2606 //  original REtADDR, but before the saved framepointer or the spilled registers
2607 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2608 //  stack layout:
2609 //    arg1
2610 //    arg2
2611 //    RETADDR
2612 //    [ new RETADDR
2613 //      move area ]
2614 //    (possible EBP)
2615 //    ESI
2616 //    EDI
2617 //    local1 ..
2618
2619 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2620 /// for a 16 byte align requirement.
2621 unsigned
2622 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2623                                                SelectionDAG& DAG) const {
2624   MachineFunction &MF = DAG.getMachineFunction();
2625   const TargetMachine &TM = MF.getTarget();
2626   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2627   unsigned StackAlignment = TFI.getStackAlignment();
2628   uint64_t AlignMask = StackAlignment - 1;
2629   int64_t Offset = StackSize;
2630   uint64_t SlotSize = TD->getPointerSize();
2631   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2632     // Number smaller than 12 so just add the difference.
2633     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2634   } else {
2635     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2636     Offset = ((~AlignMask) & Offset) + StackAlignment +
2637       (StackAlignment-SlotSize);
2638   }
2639   return Offset;
2640 }
2641
2642 /// MatchingStackOffset - Return true if the given stack call argument is
2643 /// already available in the same position (relatively) of the caller's
2644 /// incoming argument stack.
2645 static
2646 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2647                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2648                          const X86InstrInfo *TII) {
2649   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2650   int FI = INT_MAX;
2651   if (Arg.getOpcode() == ISD::CopyFromReg) {
2652     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2653     if (!TargetRegisterInfo::isVirtualRegister(VR))
2654       return false;
2655     MachineInstr *Def = MRI->getVRegDef(VR);
2656     if (!Def)
2657       return false;
2658     if (!Flags.isByVal()) {
2659       if (!TII->isLoadFromStackSlot(Def, FI))
2660         return false;
2661     } else {
2662       unsigned Opcode = Def->getOpcode();
2663       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2664           Def->getOperand(1).isFI()) {
2665         FI = Def->getOperand(1).getIndex();
2666         Bytes = Flags.getByValSize();
2667       } else
2668         return false;
2669     }
2670   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2671     if (Flags.isByVal())
2672       // ByVal argument is passed in as a pointer but it's now being
2673       // dereferenced. e.g.
2674       // define @foo(%struct.X* %A) {
2675       //   tail call @bar(%struct.X* byval %A)
2676       // }
2677       return false;
2678     SDValue Ptr = Ld->getBasePtr();
2679     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2680     if (!FINode)
2681       return false;
2682     FI = FINode->getIndex();
2683   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2684     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2685     FI = FINode->getIndex();
2686     Bytes = Flags.getByValSize();
2687   } else
2688     return false;
2689
2690   assert(FI != INT_MAX);
2691   if (!MFI->isFixedObjectIndex(FI))
2692     return false;
2693   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2694 }
2695
2696 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2697 /// for tail call optimization. Targets which want to do tail call
2698 /// optimization should implement this function.
2699 bool
2700 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2701                                                      CallingConv::ID CalleeCC,
2702                                                      bool isVarArg,
2703                                                      bool isCalleeStructRet,
2704                                                      bool isCallerStructRet,
2705                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2706                                     const SmallVectorImpl<SDValue> &OutVals,
2707                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2708                                                      SelectionDAG& DAG) const {
2709   if (!IsTailCallConvention(CalleeCC) &&
2710       CalleeCC != CallingConv::C)
2711     return false;
2712
2713   // If -tailcallopt is specified, make fastcc functions tail-callable.
2714   const MachineFunction &MF = DAG.getMachineFunction();
2715   const Function *CallerF = DAG.getMachineFunction().getFunction();
2716   CallingConv::ID CallerCC = CallerF->getCallingConv();
2717   bool CCMatch = CallerCC == CalleeCC;
2718
2719   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2720     if (IsTailCallConvention(CalleeCC) && CCMatch)
2721       return true;
2722     return false;
2723   }
2724
2725   // Look for obvious safe cases to perform tail call optimization that do not
2726   // require ABI changes. This is what gcc calls sibcall.
2727
2728   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2729   // emit a special epilogue.
2730   if (RegInfo->needsStackRealignment(MF))
2731     return false;
2732
2733   // Also avoid sibcall optimization if either caller or callee uses struct
2734   // return semantics.
2735   if (isCalleeStructRet || isCallerStructRet)
2736     return false;
2737
2738   // An stdcall caller is expected to clean up its arguments; the callee
2739   // isn't going to do that.
2740   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2741     return false;
2742
2743   // Do not sibcall optimize vararg calls unless all arguments are passed via
2744   // registers.
2745   if (isVarArg && !Outs.empty()) {
2746
2747     // Optimizing for varargs on Win64 is unlikely to be safe without
2748     // additional testing.
2749     if (Subtarget->isTargetWin64())
2750       return false;
2751
2752     SmallVector<CCValAssign, 16> ArgLocs;
2753     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2754                    getTargetMachine(), ArgLocs, *DAG.getContext());
2755
2756     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2757     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2758       if (!ArgLocs[i].isRegLoc())
2759         return false;
2760   }
2761
2762   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2763   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2764   // this into a sibcall.
2765   bool Unused = false;
2766   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2767     if (!Ins[i].Used) {
2768       Unused = true;
2769       break;
2770     }
2771   }
2772   if (Unused) {
2773     SmallVector<CCValAssign, 16> RVLocs;
2774     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2775                    getTargetMachine(), RVLocs, *DAG.getContext());
2776     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2777     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2778       CCValAssign &VA = RVLocs[i];
2779       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2780         return false;
2781     }
2782   }
2783
2784   // If the calling conventions do not match, then we'd better make sure the
2785   // results are returned in the same way as what the caller expects.
2786   if (!CCMatch) {
2787     SmallVector<CCValAssign, 16> RVLocs1;
2788     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2789                     getTargetMachine(), RVLocs1, *DAG.getContext());
2790     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2791
2792     SmallVector<CCValAssign, 16> RVLocs2;
2793     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2794                     getTargetMachine(), RVLocs2, *DAG.getContext());
2795     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2796
2797     if (RVLocs1.size() != RVLocs2.size())
2798       return false;
2799     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2800       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2801         return false;
2802       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2803         return false;
2804       if (RVLocs1[i].isRegLoc()) {
2805         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2806           return false;
2807       } else {
2808         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2809           return false;
2810       }
2811     }
2812   }
2813
2814   // If the callee takes no arguments then go on to check the results of the
2815   // call.
2816   if (!Outs.empty()) {
2817     // Check if stack adjustment is needed. For now, do not do this if any
2818     // argument is passed on the stack.
2819     SmallVector<CCValAssign, 16> ArgLocs;
2820     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2821                    getTargetMachine(), ArgLocs, *DAG.getContext());
2822
2823     // Allocate shadow area for Win64
2824     if (Subtarget->isTargetWin64()) {
2825       CCInfo.AllocateStack(32, 8);
2826     }
2827
2828     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2829     if (CCInfo.getNextStackOffset()) {
2830       MachineFunction &MF = DAG.getMachineFunction();
2831       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2832         return false;
2833
2834       // Check if the arguments are already laid out in the right way as
2835       // the caller's fixed stack objects.
2836       MachineFrameInfo *MFI = MF.getFrameInfo();
2837       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2838       const X86InstrInfo *TII =
2839         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2840       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2841         CCValAssign &VA = ArgLocs[i];
2842         SDValue Arg = OutVals[i];
2843         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2844         if (VA.getLocInfo() == CCValAssign::Indirect)
2845           return false;
2846         if (!VA.isRegLoc()) {
2847           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2848                                    MFI, MRI, TII))
2849             return false;
2850         }
2851       }
2852     }
2853
2854     // If the tailcall address may be in a register, then make sure it's
2855     // possible to register allocate for it. In 32-bit, the call address can
2856     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2857     // callee-saved registers are restored. These happen to be the same
2858     // registers used to pass 'inreg' arguments so watch out for those.
2859     if (!Subtarget->is64Bit() &&
2860         !isa<GlobalAddressSDNode>(Callee) &&
2861         !isa<ExternalSymbolSDNode>(Callee)) {
2862       unsigned NumInRegs = 0;
2863       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2864         CCValAssign &VA = ArgLocs[i];
2865         if (!VA.isRegLoc())
2866           continue;
2867         unsigned Reg = VA.getLocReg();
2868         switch (Reg) {
2869         default: break;
2870         case X86::EAX: case X86::EDX: case X86::ECX:
2871           if (++NumInRegs == 3)
2872             return false;
2873           break;
2874         }
2875       }
2876     }
2877   }
2878
2879   return true;
2880 }
2881
2882 FastISel *
2883 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2884                                   const TargetLibraryInfo *libInfo) const {
2885   return X86::createFastISel(funcInfo, libInfo);
2886 }
2887
2888
2889 //===----------------------------------------------------------------------===//
2890 //                           Other Lowering Hooks
2891 //===----------------------------------------------------------------------===//
2892
2893 static bool MayFoldLoad(SDValue Op) {
2894   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2895 }
2896
2897 static bool MayFoldIntoStore(SDValue Op) {
2898   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2899 }
2900
2901 static bool isTargetShuffle(unsigned Opcode) {
2902   switch(Opcode) {
2903   default: return false;
2904   case X86ISD::PSHUFD:
2905   case X86ISD::PSHUFHW:
2906   case X86ISD::PSHUFLW:
2907   case X86ISD::SHUFP:
2908   case X86ISD::PALIGN:
2909   case X86ISD::MOVLHPS:
2910   case X86ISD::MOVLHPD:
2911   case X86ISD::MOVHLPS:
2912   case X86ISD::MOVLPS:
2913   case X86ISD::MOVLPD:
2914   case X86ISD::MOVSHDUP:
2915   case X86ISD::MOVSLDUP:
2916   case X86ISD::MOVDDUP:
2917   case X86ISD::MOVSS:
2918   case X86ISD::MOVSD:
2919   case X86ISD::UNPCKL:
2920   case X86ISD::UNPCKH:
2921   case X86ISD::VPERMILP:
2922   case X86ISD::VPERM2X128:
2923   case X86ISD::VPERMI:
2924     return true;
2925   }
2926 }
2927
2928 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2929                                     SDValue V1, SelectionDAG &DAG) {
2930   switch(Opc) {
2931   default: llvm_unreachable("Unknown x86 shuffle node");
2932   case X86ISD::MOVSHDUP:
2933   case X86ISD::MOVSLDUP:
2934   case X86ISD::MOVDDUP:
2935     return DAG.getNode(Opc, dl, VT, V1);
2936   }
2937 }
2938
2939 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2940                                     SDValue V1, unsigned TargetMask,
2941                                     SelectionDAG &DAG) {
2942   switch(Opc) {
2943   default: llvm_unreachable("Unknown x86 shuffle node");
2944   case X86ISD::PSHUFD:
2945   case X86ISD::PSHUFHW:
2946   case X86ISD::PSHUFLW:
2947   case X86ISD::VPERMILP:
2948   case X86ISD::VPERMI:
2949     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2950   }
2951 }
2952
2953 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2954                                     SDValue V1, SDValue V2, unsigned TargetMask,
2955                                     SelectionDAG &DAG) {
2956   switch(Opc) {
2957   default: llvm_unreachable("Unknown x86 shuffle node");
2958   case X86ISD::PALIGN:
2959   case X86ISD::SHUFP:
2960   case X86ISD::VPERM2X128:
2961     return DAG.getNode(Opc, dl, VT, V1, V2,
2962                        DAG.getConstant(TargetMask, MVT::i8));
2963   }
2964 }
2965
2966 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2967                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2968   switch(Opc) {
2969   default: llvm_unreachable("Unknown x86 shuffle node");
2970   case X86ISD::MOVLHPS:
2971   case X86ISD::MOVLHPD:
2972   case X86ISD::MOVHLPS:
2973   case X86ISD::MOVLPS:
2974   case X86ISD::MOVLPD:
2975   case X86ISD::MOVSS:
2976   case X86ISD::MOVSD:
2977   case X86ISD::UNPCKL:
2978   case X86ISD::UNPCKH:
2979     return DAG.getNode(Opc, dl, VT, V1, V2);
2980   }
2981 }
2982
2983 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2984   MachineFunction &MF = DAG.getMachineFunction();
2985   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2986   int ReturnAddrIndex = FuncInfo->getRAIndex();
2987
2988   if (ReturnAddrIndex == 0) {
2989     // Set up a frame object for the return address.
2990     uint64_t SlotSize = TD->getPointerSize();
2991     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2992                                                            false);
2993     FuncInfo->setRAIndex(ReturnAddrIndex);
2994   }
2995
2996   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2997 }
2998
2999
3000 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3001                                        bool hasSymbolicDisplacement) {
3002   // Offset should fit into 32 bit immediate field.
3003   if (!isInt<32>(Offset))
3004     return false;
3005
3006   // If we don't have a symbolic displacement - we don't have any extra
3007   // restrictions.
3008   if (!hasSymbolicDisplacement)
3009     return true;
3010
3011   // FIXME: Some tweaks might be needed for medium code model.
3012   if (M != CodeModel::Small && M != CodeModel::Kernel)
3013     return false;
3014
3015   // For small code model we assume that latest object is 16MB before end of 31
3016   // bits boundary. We may also accept pretty large negative constants knowing
3017   // that all objects are in the positive half of address space.
3018   if (M == CodeModel::Small && Offset < 16*1024*1024)
3019     return true;
3020
3021   // For kernel code model we know that all object resist in the negative half
3022   // of 32bits address space. We may not accept negative offsets, since they may
3023   // be just off and we may accept pretty large positive ones.
3024   if (M == CodeModel::Kernel && Offset > 0)
3025     return true;
3026
3027   return false;
3028 }
3029
3030 /// isCalleePop - Determines whether the callee is required to pop its
3031 /// own arguments. Callee pop is necessary to support tail calls.
3032 bool X86::isCalleePop(CallingConv::ID CallingConv,
3033                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3034   if (IsVarArg)
3035     return false;
3036
3037   switch (CallingConv) {
3038   default:
3039     return false;
3040   case CallingConv::X86_StdCall:
3041     return !is64Bit;
3042   case CallingConv::X86_FastCall:
3043     return !is64Bit;
3044   case CallingConv::X86_ThisCall:
3045     return !is64Bit;
3046   case CallingConv::Fast:
3047     return TailCallOpt;
3048   case CallingConv::GHC:
3049     return TailCallOpt;
3050   }
3051 }
3052
3053 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3054 /// specific condition code, returning the condition code and the LHS/RHS of the
3055 /// comparison to make.
3056 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3057                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3058   if (!isFP) {
3059     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3060       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3061         // X > -1   -> X == 0, jump !sign.
3062         RHS = DAG.getConstant(0, RHS.getValueType());
3063         return X86::COND_NS;
3064       }
3065       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3066         // X < 0   -> X == 0, jump on sign.
3067         return X86::COND_S;
3068       }
3069       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3070         // X < 1   -> X <= 0
3071         RHS = DAG.getConstant(0, RHS.getValueType());
3072         return X86::COND_LE;
3073       }
3074     }
3075
3076     switch (SetCCOpcode) {
3077     default: llvm_unreachable("Invalid integer condition!");
3078     case ISD::SETEQ:  return X86::COND_E;
3079     case ISD::SETGT:  return X86::COND_G;
3080     case ISD::SETGE:  return X86::COND_GE;
3081     case ISD::SETLT:  return X86::COND_L;
3082     case ISD::SETLE:  return X86::COND_LE;
3083     case ISD::SETNE:  return X86::COND_NE;
3084     case ISD::SETULT: return X86::COND_B;
3085     case ISD::SETUGT: return X86::COND_A;
3086     case ISD::SETULE: return X86::COND_BE;
3087     case ISD::SETUGE: return X86::COND_AE;
3088     }
3089   }
3090
3091   // First determine if it is required or is profitable to flip the operands.
3092
3093   // If LHS is a foldable load, but RHS is not, flip the condition.
3094   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3095       !ISD::isNON_EXTLoad(RHS.getNode())) {
3096     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3097     std::swap(LHS, RHS);
3098   }
3099
3100   switch (SetCCOpcode) {
3101   default: break;
3102   case ISD::SETOLT:
3103   case ISD::SETOLE:
3104   case ISD::SETUGT:
3105   case ISD::SETUGE:
3106     std::swap(LHS, RHS);
3107     break;
3108   }
3109
3110   // On a floating point condition, the flags are set as follows:
3111   // ZF  PF  CF   op
3112   //  0 | 0 | 0 | X > Y
3113   //  0 | 0 | 1 | X < Y
3114   //  1 | 0 | 0 | X == Y
3115   //  1 | 1 | 1 | unordered
3116   switch (SetCCOpcode) {
3117   default: llvm_unreachable("Condcode should be pre-legalized away");
3118   case ISD::SETUEQ:
3119   case ISD::SETEQ:   return X86::COND_E;
3120   case ISD::SETOLT:              // flipped
3121   case ISD::SETOGT:
3122   case ISD::SETGT:   return X86::COND_A;
3123   case ISD::SETOLE:              // flipped
3124   case ISD::SETOGE:
3125   case ISD::SETGE:   return X86::COND_AE;
3126   case ISD::SETUGT:              // flipped
3127   case ISD::SETULT:
3128   case ISD::SETLT:   return X86::COND_B;
3129   case ISD::SETUGE:              // flipped
3130   case ISD::SETULE:
3131   case ISD::SETLE:   return X86::COND_BE;
3132   case ISD::SETONE:
3133   case ISD::SETNE:   return X86::COND_NE;
3134   case ISD::SETUO:   return X86::COND_P;
3135   case ISD::SETO:    return X86::COND_NP;
3136   case ISD::SETOEQ:
3137   case ISD::SETUNE:  return X86::COND_INVALID;
3138   }
3139 }
3140
3141 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3142 /// code. Current x86 isa includes the following FP cmov instructions:
3143 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3144 static bool hasFPCMov(unsigned X86CC) {
3145   switch (X86CC) {
3146   default:
3147     return false;
3148   case X86::COND_B:
3149   case X86::COND_BE:
3150   case X86::COND_E:
3151   case X86::COND_P:
3152   case X86::COND_A:
3153   case X86::COND_AE:
3154   case X86::COND_NE:
3155   case X86::COND_NP:
3156     return true;
3157   }
3158 }
3159
3160 /// isFPImmLegal - Returns true if the target can instruction select the
3161 /// specified FP immediate natively. If false, the legalizer will
3162 /// materialize the FP immediate as a load from a constant pool.
3163 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3164   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3165     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3166       return true;
3167   }
3168   return false;
3169 }
3170
3171 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3172 /// the specified range (L, H].
3173 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3174   return (Val < 0) || (Val >= Low && Val < Hi);
3175 }
3176
3177 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3178 /// specified value.
3179 static bool isUndefOrEqual(int Val, int CmpVal) {
3180   if (Val < 0 || Val == CmpVal)
3181     return true;
3182   return false;
3183 }
3184
3185 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3186 /// from position Pos and ending in Pos+Size, falls within the specified
3187 /// sequential range (L, L+Pos]. or is undef.
3188 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3189                                        unsigned Pos, unsigned Size, int Low) {
3190   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3191     if (!isUndefOrEqual(Mask[i], Low))
3192       return false;
3193   return true;
3194 }
3195
3196 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3197 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3198 /// the second operand.
3199 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3200   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3201     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3202   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3203     return (Mask[0] < 2 && Mask[1] < 2);
3204   return false;
3205 }
3206
3207 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3208 /// is suitable for input to PSHUFHW.
3209 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3210   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3211     return false;
3212
3213   // Lower quadword copied in order or undef.
3214   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3215     return false;
3216
3217   // Upper quadword shuffled.
3218   for (unsigned i = 4; i != 8; ++i)
3219     if (!isUndefOrInRange(Mask[i], 4, 8))
3220       return false;
3221
3222   if (VT == MVT::v16i16) {
3223     // Lower quadword copied in order or undef.
3224     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3225       return false;
3226
3227     // Upper quadword shuffled.
3228     for (unsigned i = 12; i != 16; ++i)
3229       if (!isUndefOrInRange(Mask[i], 12, 16))
3230         return false;
3231   }
3232
3233   return true;
3234 }
3235
3236 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3237 /// is suitable for input to PSHUFLW.
3238 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3239   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3240     return false;
3241
3242   // Upper quadword copied in order.
3243   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3244     return false;
3245
3246   // Lower quadword shuffled.
3247   for (unsigned i = 0; i != 4; ++i)
3248     if (!isUndefOrInRange(Mask[i], 0, 4))
3249       return false;
3250
3251   if (VT == MVT::v16i16) {
3252     // Upper quadword copied in order.
3253     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3254       return false;
3255
3256     // Lower quadword shuffled.
3257     for (unsigned i = 8; i != 12; ++i)
3258       if (!isUndefOrInRange(Mask[i], 8, 12))
3259         return false;
3260   }
3261
3262   return true;
3263 }
3264
3265 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3266 /// is suitable for input to PALIGNR.
3267 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3268                           const X86Subtarget *Subtarget) {
3269   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3270       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3271     return false;
3272
3273   unsigned NumElts = VT.getVectorNumElements();
3274   unsigned NumLanes = VT.getSizeInBits()/128;
3275   unsigned NumLaneElts = NumElts/NumLanes;
3276
3277   // Do not handle 64-bit element shuffles with palignr.
3278   if (NumLaneElts == 2)
3279     return false;
3280
3281   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3282     unsigned i;
3283     for (i = 0; i != NumLaneElts; ++i) {
3284       if (Mask[i+l] >= 0)
3285         break;
3286     }
3287
3288     // Lane is all undef, go to next lane
3289     if (i == NumLaneElts)
3290       continue;
3291
3292     int Start = Mask[i+l];
3293
3294     // Make sure its in this lane in one of the sources
3295     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3296         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3297       return false;
3298
3299     // If not lane 0, then we must match lane 0
3300     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3301       return false;
3302
3303     // Correct second source to be contiguous with first source
3304     if (Start >= (int)NumElts)
3305       Start -= NumElts - NumLaneElts;
3306
3307     // Make sure we're shifting in the right direction.
3308     if (Start <= (int)(i+l))
3309       return false;
3310
3311     Start -= i;
3312
3313     // Check the rest of the elements to see if they are consecutive.
3314     for (++i; i != NumLaneElts; ++i) {
3315       int Idx = Mask[i+l];
3316
3317       // Make sure its in this lane
3318       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3319           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3320         return false;
3321
3322       // If not lane 0, then we must match lane 0
3323       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3324         return false;
3325
3326       if (Idx >= (int)NumElts)
3327         Idx -= NumElts - NumLaneElts;
3328
3329       if (!isUndefOrEqual(Idx, Start+i))
3330         return false;
3331
3332     }
3333   }
3334
3335   return true;
3336 }
3337
3338 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3339 /// the two vector operands have swapped position.
3340 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3341                                      unsigned NumElems) {
3342   for (unsigned i = 0; i != NumElems; ++i) {
3343     int idx = Mask[i];
3344     if (idx < 0)
3345       continue;
3346     else if (idx < (int)NumElems)
3347       Mask[i] = idx + NumElems;
3348     else
3349       Mask[i] = idx - NumElems;
3350   }
3351 }
3352
3353 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3354 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3355 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3356 /// reverse of what x86 shuffles want.
3357 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3358                         bool Commuted = false) {
3359   if (!HasAVX && VT.getSizeInBits() == 256)
3360     return false;
3361
3362   unsigned NumElems = VT.getVectorNumElements();
3363   unsigned NumLanes = VT.getSizeInBits()/128;
3364   unsigned NumLaneElems = NumElems/NumLanes;
3365
3366   if (NumLaneElems != 2 && NumLaneElems != 4)
3367     return false;
3368
3369   // VSHUFPSY divides the resulting vector into 4 chunks.
3370   // The sources are also splitted into 4 chunks, and each destination
3371   // chunk must come from a different source chunk.
3372   //
3373   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3374   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3375   //
3376   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3377   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3378   //
3379   // VSHUFPDY divides the resulting vector into 4 chunks.
3380   // The sources are also splitted into 4 chunks, and each destination
3381   // chunk must come from a different source chunk.
3382   //
3383   //  SRC1 =>      X3       X2       X1       X0
3384   //  SRC2 =>      Y3       Y2       Y1       Y0
3385   //
3386   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3387   //
3388   unsigned HalfLaneElems = NumLaneElems/2;
3389   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3390     for (unsigned i = 0; i != NumLaneElems; ++i) {
3391       int Idx = Mask[i+l];
3392       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3393       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3394         return false;
3395       // For VSHUFPSY, the mask of the second half must be the same as the
3396       // first but with the appropriate offsets. This works in the same way as
3397       // VPERMILPS works with masks.
3398       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3399         continue;
3400       if (!isUndefOrEqual(Idx, Mask[i]+l))
3401         return false;
3402     }
3403   }
3404
3405   return true;
3406 }
3407
3408 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3409 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3410 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3411   if (!VT.is128BitVector())
3412     return false;
3413
3414   unsigned NumElems = VT.getVectorNumElements();
3415
3416   if (NumElems != 4)
3417     return false;
3418
3419   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3420   return isUndefOrEqual(Mask[0], 6) &&
3421          isUndefOrEqual(Mask[1], 7) &&
3422          isUndefOrEqual(Mask[2], 2) &&
3423          isUndefOrEqual(Mask[3], 3);
3424 }
3425
3426 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3427 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3428 /// <2, 3, 2, 3>
3429 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3430   if (!VT.is128BitVector())
3431     return false;
3432
3433   unsigned NumElems = VT.getVectorNumElements();
3434
3435   if (NumElems != 4)
3436     return false;
3437
3438   return isUndefOrEqual(Mask[0], 2) &&
3439          isUndefOrEqual(Mask[1], 3) &&
3440          isUndefOrEqual(Mask[2], 2) &&
3441          isUndefOrEqual(Mask[3], 3);
3442 }
3443
3444 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3445 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3446 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3447   if (!VT.is128BitVector())
3448     return false;
3449
3450   unsigned NumElems = VT.getVectorNumElements();
3451
3452   if (NumElems != 2 && NumElems != 4)
3453     return false;
3454
3455   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3456     if (!isUndefOrEqual(Mask[i], i + NumElems))
3457       return false;
3458
3459   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3460     if (!isUndefOrEqual(Mask[i], i))
3461       return false;
3462
3463   return true;
3464 }
3465
3466 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3467 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3468 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3469   if (!VT.is128BitVector())
3470     return false;
3471
3472   unsigned NumElems = VT.getVectorNumElements();
3473
3474   if (NumElems != 2 && NumElems != 4)
3475     return false;
3476
3477   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3478     if (!isUndefOrEqual(Mask[i], i))
3479       return false;
3480
3481   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3482     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3483       return false;
3484
3485   return true;
3486 }
3487
3488 //
3489 // Some special combinations that can be optimized.
3490 //
3491 static
3492 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3493                                SelectionDAG &DAG) {
3494   EVT VT = SVOp->getValueType(0);
3495   DebugLoc dl = SVOp->getDebugLoc();
3496
3497   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3498     return SDValue();
3499
3500   ArrayRef<int> Mask = SVOp->getMask();
3501
3502   // These are the special masks that may be optimized.
3503   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3504   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3505   bool MatchEvenMask = true;
3506   bool MatchOddMask  = true;
3507   for (int i=0; i<8; ++i) {
3508     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3509       MatchEvenMask = false;
3510     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3511       MatchOddMask = false;
3512   }
3513
3514   if (!MatchEvenMask && !MatchOddMask)
3515     return SDValue();
3516   
3517   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3518
3519   SDValue Op0 = SVOp->getOperand(0);
3520   SDValue Op1 = SVOp->getOperand(1);
3521
3522   if (MatchEvenMask) {
3523     // Shift the second operand right to 32 bits.
3524     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3525     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3526   } else {
3527     // Shift the first operand left to 32 bits.
3528     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3529     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3530   }
3531   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3532   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3533 }
3534
3535 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3536 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3537 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3538                          bool HasAVX2, bool V2IsSplat = false) {
3539   unsigned NumElts = VT.getVectorNumElements();
3540
3541   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3542          "Unsupported vector type for unpckh");
3543
3544   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3545       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3546     return false;
3547
3548   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3549   // independently on 128-bit lanes.
3550   unsigned NumLanes = VT.getSizeInBits()/128;
3551   unsigned NumLaneElts = NumElts/NumLanes;
3552
3553   for (unsigned l = 0; l != NumLanes; ++l) {
3554     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3555          i != (l+1)*NumLaneElts;
3556          i += 2, ++j) {
3557       int BitI  = Mask[i];
3558       int BitI1 = Mask[i+1];
3559       if (!isUndefOrEqual(BitI, j))
3560         return false;
3561       if (V2IsSplat) {
3562         if (!isUndefOrEqual(BitI1, NumElts))
3563           return false;
3564       } else {
3565         if (!isUndefOrEqual(BitI1, j + NumElts))
3566           return false;
3567       }
3568     }
3569   }
3570
3571   return true;
3572 }
3573
3574 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3575 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3576 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3577                          bool HasAVX2, bool V2IsSplat = false) {
3578   unsigned NumElts = VT.getVectorNumElements();
3579
3580   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3581          "Unsupported vector type for unpckh");
3582
3583   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3584       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3585     return false;
3586
3587   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3588   // independently on 128-bit lanes.
3589   unsigned NumLanes = VT.getSizeInBits()/128;
3590   unsigned NumLaneElts = NumElts/NumLanes;
3591
3592   for (unsigned l = 0; l != NumLanes; ++l) {
3593     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3594          i != (l+1)*NumLaneElts; i += 2, ++j) {
3595       int BitI  = Mask[i];
3596       int BitI1 = Mask[i+1];
3597       if (!isUndefOrEqual(BitI, j))
3598         return false;
3599       if (V2IsSplat) {
3600         if (isUndefOrEqual(BitI1, NumElts))
3601           return false;
3602       } else {
3603         if (!isUndefOrEqual(BitI1, j+NumElts))
3604           return false;
3605       }
3606     }
3607   }
3608   return true;
3609 }
3610
3611 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3612 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3613 /// <0, 0, 1, 1>
3614 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3615                                   bool HasAVX2) {
3616   unsigned NumElts = VT.getVectorNumElements();
3617
3618   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3619          "Unsupported vector type for unpckh");
3620
3621   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3622       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3623     return false;
3624
3625   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3626   // FIXME: Need a better way to get rid of this, there's no latency difference
3627   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3628   // the former later. We should also remove the "_undef" special mask.
3629   if (NumElts == 4 && VT.getSizeInBits() == 256)
3630     return false;
3631
3632   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3633   // independently on 128-bit lanes.
3634   unsigned NumLanes = VT.getSizeInBits()/128;
3635   unsigned NumLaneElts = NumElts/NumLanes;
3636
3637   for (unsigned l = 0; l != NumLanes; ++l) {
3638     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3639          i != (l+1)*NumLaneElts;
3640          i += 2, ++j) {
3641       int BitI  = Mask[i];
3642       int BitI1 = Mask[i+1];
3643
3644       if (!isUndefOrEqual(BitI, j))
3645         return false;
3646       if (!isUndefOrEqual(BitI1, j))
3647         return false;
3648     }
3649   }
3650
3651   return true;
3652 }
3653
3654 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3655 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3656 /// <2, 2, 3, 3>
3657 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3658   unsigned NumElts = VT.getVectorNumElements();
3659
3660   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3661          "Unsupported vector type for unpckh");
3662
3663   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3664       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3665     return false;
3666
3667   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3668   // independently on 128-bit lanes.
3669   unsigned NumLanes = VT.getSizeInBits()/128;
3670   unsigned NumLaneElts = NumElts/NumLanes;
3671
3672   for (unsigned l = 0; l != NumLanes; ++l) {
3673     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3674          i != (l+1)*NumLaneElts; i += 2, ++j) {
3675       int BitI  = Mask[i];
3676       int BitI1 = Mask[i+1];
3677       if (!isUndefOrEqual(BitI, j))
3678         return false;
3679       if (!isUndefOrEqual(BitI1, j))
3680         return false;
3681     }
3682   }
3683   return true;
3684 }
3685
3686 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3687 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3688 /// MOVSD, and MOVD, i.e. setting the lowest element.
3689 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3690   if (VT.getVectorElementType().getSizeInBits() < 32)
3691     return false;
3692   if (!VT.is128BitVector())
3693     return false;
3694
3695   unsigned NumElts = VT.getVectorNumElements();
3696
3697   if (!isUndefOrEqual(Mask[0], NumElts))
3698     return false;
3699
3700   for (unsigned i = 1; i != NumElts; ++i)
3701     if (!isUndefOrEqual(Mask[i], i))
3702       return false;
3703
3704   return true;
3705 }
3706
3707 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3708 /// as permutations between 128-bit chunks or halves. As an example: this
3709 /// shuffle bellow:
3710 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3711 /// The first half comes from the second half of V1 and the second half from the
3712 /// the second half of V2.
3713 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3714   if (!HasAVX || !VT.is256BitVector())
3715     return false;
3716
3717   // The shuffle result is divided into half A and half B. In total the two
3718   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3719   // B must come from C, D, E or F.
3720   unsigned HalfSize = VT.getVectorNumElements()/2;
3721   bool MatchA = false, MatchB = false;
3722
3723   // Check if A comes from one of C, D, E, F.
3724   for (unsigned Half = 0; Half != 4; ++Half) {
3725     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3726       MatchA = true;
3727       break;
3728     }
3729   }
3730
3731   // Check if B comes from one of C, D, E, F.
3732   for (unsigned Half = 0; Half != 4; ++Half) {
3733     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3734       MatchB = true;
3735       break;
3736     }
3737   }
3738
3739   return MatchA && MatchB;
3740 }
3741
3742 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3743 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3744 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3745   EVT VT = SVOp->getValueType(0);
3746
3747   unsigned HalfSize = VT.getVectorNumElements()/2;
3748
3749   unsigned FstHalf = 0, SndHalf = 0;
3750   for (unsigned i = 0; i < HalfSize; ++i) {
3751     if (SVOp->getMaskElt(i) > 0) {
3752       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3753       break;
3754     }
3755   }
3756   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3757     if (SVOp->getMaskElt(i) > 0) {
3758       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3759       break;
3760     }
3761   }
3762
3763   return (FstHalf | (SndHalf << 4));
3764 }
3765
3766 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3767 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3768 /// Note that VPERMIL mask matching is different depending whether theunderlying
3769 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3770 /// to the same elements of the low, but to the higher half of the source.
3771 /// In VPERMILPD the two lanes could be shuffled independently of each other
3772 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3773 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3774   if (!HasAVX)
3775     return false;
3776
3777   unsigned NumElts = VT.getVectorNumElements();
3778   // Only match 256-bit with 32/64-bit types
3779   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3780     return false;
3781
3782   unsigned NumLanes = VT.getSizeInBits()/128;
3783   unsigned LaneSize = NumElts/NumLanes;
3784   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3785     for (unsigned i = 0; i != LaneSize; ++i) {
3786       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3787         return false;
3788       if (NumElts != 8 || l == 0)
3789         continue;
3790       // VPERMILPS handling
3791       if (Mask[i] < 0)
3792         continue;
3793       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3794         return false;
3795     }
3796   }
3797
3798   return true;
3799 }
3800
3801 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3802 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3803 /// element of vector 2 and the other elements to come from vector 1 in order.
3804 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3805                                bool V2IsSplat = false, bool V2IsUndef = false) {
3806   if (!VT.is128BitVector())
3807     return false;
3808
3809   unsigned NumOps = VT.getVectorNumElements();
3810   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3811     return false;
3812
3813   if (!isUndefOrEqual(Mask[0], 0))
3814     return false;
3815
3816   for (unsigned i = 1; i != NumOps; ++i)
3817     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3818           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3819           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3820       return false;
3821
3822   return true;
3823 }
3824
3825 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3826 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3827 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3828 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3829                            const X86Subtarget *Subtarget) {
3830   if (!Subtarget->hasSSE3())
3831     return false;
3832
3833   unsigned NumElems = VT.getVectorNumElements();
3834
3835   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3836       (VT.getSizeInBits() == 256 && NumElems != 8))
3837     return false;
3838
3839   // "i+1" is the value the indexed mask element must have
3840   for (unsigned i = 0; i != NumElems; i += 2)
3841     if (!isUndefOrEqual(Mask[i], i+1) ||
3842         !isUndefOrEqual(Mask[i+1], i+1))
3843       return false;
3844
3845   return true;
3846 }
3847
3848 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3849 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3850 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3851 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3852                            const X86Subtarget *Subtarget) {
3853   if (!Subtarget->hasSSE3())
3854     return false;
3855
3856   unsigned NumElems = VT.getVectorNumElements();
3857
3858   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3859       (VT.getSizeInBits() == 256 && NumElems != 8))
3860     return false;
3861
3862   // "i" is the value the indexed mask element must have
3863   for (unsigned i = 0; i != NumElems; i += 2)
3864     if (!isUndefOrEqual(Mask[i], i) ||
3865         !isUndefOrEqual(Mask[i+1], i))
3866       return false;
3867
3868   return true;
3869 }
3870
3871 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3872 /// specifies a shuffle of elements that is suitable for input to 256-bit
3873 /// version of MOVDDUP.
3874 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3875   if (!HasAVX || !VT.is256BitVector())
3876     return false;
3877
3878   unsigned NumElts = VT.getVectorNumElements();
3879   if (NumElts != 4)
3880     return false;
3881
3882   for (unsigned i = 0; i != NumElts/2; ++i)
3883     if (!isUndefOrEqual(Mask[i], 0))
3884       return false;
3885   for (unsigned i = NumElts/2; i != NumElts; ++i)
3886     if (!isUndefOrEqual(Mask[i], NumElts/2))
3887       return false;
3888   return true;
3889 }
3890
3891 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3892 /// specifies a shuffle of elements that is suitable for input to 128-bit
3893 /// version of MOVDDUP.
3894 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3895   if (!VT.is128BitVector())
3896     return false;
3897
3898   unsigned e = VT.getVectorNumElements() / 2;
3899   for (unsigned i = 0; i != e; ++i)
3900     if (!isUndefOrEqual(Mask[i], i))
3901       return false;
3902   for (unsigned i = 0; i != e; ++i)
3903     if (!isUndefOrEqual(Mask[e+i], i))
3904       return false;
3905   return true;
3906 }
3907
3908 /// isVEXTRACTF128Index - Return true if the specified
3909 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3910 /// suitable for input to VEXTRACTF128.
3911 bool X86::isVEXTRACTF128Index(SDNode *N) {
3912   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3913     return false;
3914
3915   // The index should be aligned on a 128-bit boundary.
3916   uint64_t Index =
3917     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3918
3919   unsigned VL = N->getValueType(0).getVectorNumElements();
3920   unsigned VBits = N->getValueType(0).getSizeInBits();
3921   unsigned ElSize = VBits / VL;
3922   bool Result = (Index * ElSize) % 128 == 0;
3923
3924   return Result;
3925 }
3926
3927 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3928 /// operand specifies a subvector insert that is suitable for input to
3929 /// VINSERTF128.
3930 bool X86::isVINSERTF128Index(SDNode *N) {
3931   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3932     return false;
3933
3934   // The index should be aligned on a 128-bit boundary.
3935   uint64_t Index =
3936     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3937
3938   unsigned VL = N->getValueType(0).getVectorNumElements();
3939   unsigned VBits = N->getValueType(0).getSizeInBits();
3940   unsigned ElSize = VBits / VL;
3941   bool Result = (Index * ElSize) % 128 == 0;
3942
3943   return Result;
3944 }
3945
3946 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3947 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3948 /// Handles 128-bit and 256-bit.
3949 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3950   EVT VT = N->getValueType(0);
3951
3952   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3953          "Unsupported vector type for PSHUF/SHUFP");
3954
3955   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3956   // independently on 128-bit lanes.
3957   unsigned NumElts = VT.getVectorNumElements();
3958   unsigned NumLanes = VT.getSizeInBits()/128;
3959   unsigned NumLaneElts = NumElts/NumLanes;
3960
3961   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3962          "Only supports 2 or 4 elements per lane");
3963
3964   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3965   unsigned Mask = 0;
3966   for (unsigned i = 0; i != NumElts; ++i) {
3967     int Elt = N->getMaskElt(i);
3968     if (Elt < 0) continue;
3969     Elt &= NumLaneElts - 1;
3970     unsigned ShAmt = (i << Shift) % 8;
3971     Mask |= Elt << ShAmt;
3972   }
3973
3974   return Mask;
3975 }
3976
3977 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3978 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3979 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3980   EVT VT = N->getValueType(0);
3981
3982   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3983          "Unsupported vector type for PSHUFHW");
3984
3985   unsigned NumElts = VT.getVectorNumElements();
3986
3987   unsigned Mask = 0;
3988   for (unsigned l = 0; l != NumElts; l += 8) {
3989     // 8 nodes per lane, but we only care about the last 4.
3990     for (unsigned i = 0; i < 4; ++i) {
3991       int Elt = N->getMaskElt(l+i+4);
3992       if (Elt < 0) continue;
3993       Elt &= 0x3; // only 2-bits.
3994       Mask |= Elt << (i * 2);
3995     }
3996   }
3997
3998   return Mask;
3999 }
4000
4001 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4002 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4003 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4004   EVT VT = N->getValueType(0);
4005
4006   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4007          "Unsupported vector type for PSHUFHW");
4008
4009   unsigned NumElts = VT.getVectorNumElements();
4010
4011   unsigned Mask = 0;
4012   for (unsigned l = 0; l != NumElts; l += 8) {
4013     // 8 nodes per lane, but we only care about the first 4.
4014     for (unsigned i = 0; i < 4; ++i) {
4015       int Elt = N->getMaskElt(l+i);
4016       if (Elt < 0) continue;
4017       Elt &= 0x3; // only 2-bits
4018       Mask |= Elt << (i * 2);
4019     }
4020   }
4021
4022   return Mask;
4023 }
4024
4025 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4026 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4027 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4028   EVT VT = SVOp->getValueType(0);
4029   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4030
4031   unsigned NumElts = VT.getVectorNumElements();
4032   unsigned NumLanes = VT.getSizeInBits()/128;
4033   unsigned NumLaneElts = NumElts/NumLanes;
4034
4035   int Val = 0;
4036   unsigned i;
4037   for (i = 0; i != NumElts; ++i) {
4038     Val = SVOp->getMaskElt(i);
4039     if (Val >= 0)
4040       break;
4041   }
4042   if (Val >= (int)NumElts)
4043     Val -= NumElts - NumLaneElts;
4044
4045   assert(Val - i > 0 && "PALIGNR imm should be positive");
4046   return (Val - i) * EltSize;
4047 }
4048
4049 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4050 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4051 /// instructions.
4052 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4053   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4054     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4055
4056   uint64_t Index =
4057     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4058
4059   EVT VecVT = N->getOperand(0).getValueType();
4060   EVT ElVT = VecVT.getVectorElementType();
4061
4062   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4063   return Index / NumElemsPerChunk;
4064 }
4065
4066 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4067 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4068 /// instructions.
4069 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4070   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4071     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4072
4073   uint64_t Index =
4074     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4075
4076   EVT VecVT = N->getValueType(0);
4077   EVT ElVT = VecVT.getVectorElementType();
4078
4079   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4080   return Index / NumElemsPerChunk;
4081 }
4082
4083 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4084 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4085 /// Handles 256-bit.
4086 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4087   EVT VT = N->getValueType(0);
4088
4089   unsigned NumElts = VT.getVectorNumElements();
4090
4091   assert((VT.is256BitVector() && NumElts == 4) &&
4092          "Unsupported vector type for VPERMQ/VPERMPD");
4093
4094   unsigned Mask = 0;
4095   for (unsigned i = 0; i != NumElts; ++i) {
4096     int Elt = N->getMaskElt(i);
4097     if (Elt < 0)
4098       continue;
4099     Mask |= Elt << (i*2);
4100   }
4101
4102   return Mask;
4103 }
4104 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4105 /// constant +0.0.
4106 bool X86::isZeroNode(SDValue Elt) {
4107   return ((isa<ConstantSDNode>(Elt) &&
4108            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4109           (isa<ConstantFPSDNode>(Elt) &&
4110            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4111 }
4112
4113 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4114 /// their permute mask.
4115 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4116                                     SelectionDAG &DAG) {
4117   EVT VT = SVOp->getValueType(0);
4118   unsigned NumElems = VT.getVectorNumElements();
4119   SmallVector<int, 8> MaskVec;
4120
4121   for (unsigned i = 0; i != NumElems; ++i) {
4122     int Idx = SVOp->getMaskElt(i);
4123     if (Idx >= 0) {
4124       if (Idx < (int)NumElems)
4125         Idx += NumElems;
4126       else
4127         Idx -= NumElems;
4128     }
4129     MaskVec.push_back(Idx);
4130   }
4131   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4132                               SVOp->getOperand(0), &MaskVec[0]);
4133 }
4134
4135 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4136 /// match movhlps. The lower half elements should come from upper half of
4137 /// V1 (and in order), and the upper half elements should come from the upper
4138 /// half of V2 (and in order).
4139 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4140   if (!VT.is128BitVector())
4141     return false;
4142   if (VT.getVectorNumElements() != 4)
4143     return false;
4144   for (unsigned i = 0, e = 2; i != e; ++i)
4145     if (!isUndefOrEqual(Mask[i], i+2))
4146       return false;
4147   for (unsigned i = 2; i != 4; ++i)
4148     if (!isUndefOrEqual(Mask[i], i+4))
4149       return false;
4150   return true;
4151 }
4152
4153 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4154 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4155 /// required.
4156 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4157   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4158     return false;
4159   N = N->getOperand(0).getNode();
4160   if (!ISD::isNON_EXTLoad(N))
4161     return false;
4162   if (LD)
4163     *LD = cast<LoadSDNode>(N);
4164   return true;
4165 }
4166
4167 // Test whether the given value is a vector value which will be legalized
4168 // into a load.
4169 static bool WillBeConstantPoolLoad(SDNode *N) {
4170   if (N->getOpcode() != ISD::BUILD_VECTOR)
4171     return false;
4172
4173   // Check for any non-constant elements.
4174   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4175     switch (N->getOperand(i).getNode()->getOpcode()) {
4176     case ISD::UNDEF:
4177     case ISD::ConstantFP:
4178     case ISD::Constant:
4179       break;
4180     default:
4181       return false;
4182     }
4183
4184   // Vectors of all-zeros and all-ones are materialized with special
4185   // instructions rather than being loaded.
4186   return !ISD::isBuildVectorAllZeros(N) &&
4187          !ISD::isBuildVectorAllOnes(N);
4188 }
4189
4190 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4191 /// match movlp{s|d}. The lower half elements should come from lower half of
4192 /// V1 (and in order), and the upper half elements should come from the upper
4193 /// half of V2 (and in order). And since V1 will become the source of the
4194 /// MOVLP, it must be either a vector load or a scalar load to vector.
4195 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4196                                ArrayRef<int> Mask, EVT VT) {
4197   if (!VT.is128BitVector())
4198     return false;
4199
4200   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4201     return false;
4202   // Is V2 is a vector load, don't do this transformation. We will try to use
4203   // load folding shufps op.
4204   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4205     return false;
4206
4207   unsigned NumElems = VT.getVectorNumElements();
4208
4209   if (NumElems != 2 && NumElems != 4)
4210     return false;
4211   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4212     if (!isUndefOrEqual(Mask[i], i))
4213       return false;
4214   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4215     if (!isUndefOrEqual(Mask[i], i+NumElems))
4216       return false;
4217   return true;
4218 }
4219
4220 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4221 /// all the same.
4222 static bool isSplatVector(SDNode *N) {
4223   if (N->getOpcode() != ISD::BUILD_VECTOR)
4224     return false;
4225
4226   SDValue SplatValue = N->getOperand(0);
4227   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4228     if (N->getOperand(i) != SplatValue)
4229       return false;
4230   return true;
4231 }
4232
4233 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4234 /// to an zero vector.
4235 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4236 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4237   SDValue V1 = N->getOperand(0);
4238   SDValue V2 = N->getOperand(1);
4239   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4240   for (unsigned i = 0; i != NumElems; ++i) {
4241     int Idx = N->getMaskElt(i);
4242     if (Idx >= (int)NumElems) {
4243       unsigned Opc = V2.getOpcode();
4244       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4245         continue;
4246       if (Opc != ISD::BUILD_VECTOR ||
4247           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4248         return false;
4249     } else if (Idx >= 0) {
4250       unsigned Opc = V1.getOpcode();
4251       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4252         continue;
4253       if (Opc != ISD::BUILD_VECTOR ||
4254           !X86::isZeroNode(V1.getOperand(Idx)))
4255         return false;
4256     }
4257   }
4258   return true;
4259 }
4260
4261 /// getZeroVector - Returns a vector of specified type with all zero elements.
4262 ///
4263 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4264                              SelectionDAG &DAG, DebugLoc dl) {
4265   assert(VT.isVector() && "Expected a vector type");
4266   unsigned Size = VT.getSizeInBits();
4267
4268   // Always build SSE zero vectors as <4 x i32> bitcasted
4269   // to their dest type. This ensures they get CSE'd.
4270   SDValue Vec;
4271   if (Size == 128) {  // SSE
4272     if (Subtarget->hasSSE2()) {  // SSE2
4273       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4274       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4275     } else { // SSE1
4276       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4277       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4278     }
4279   } else if (Size == 256) { // AVX
4280     if (Subtarget->hasAVX2()) { // AVX2
4281       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4282       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4283       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4284     } else {
4285       // 256-bit logic and arithmetic instructions in AVX are all
4286       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4287       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4288       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4289       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4290     }
4291   } else
4292     llvm_unreachable("Unexpected vector type");
4293
4294   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4295 }
4296
4297 /// getOnesVector - Returns a vector of specified type with all bits set.
4298 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4299 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4300 /// Then bitcast to their original type, ensuring they get CSE'd.
4301 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4302                              DebugLoc dl) {
4303   assert(VT.isVector() && "Expected a vector type");
4304   unsigned Size = VT.getSizeInBits();
4305
4306   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4307   SDValue Vec;
4308   if (Size == 256) {
4309     if (HasAVX2) { // AVX2
4310       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4311       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4312     } else { // AVX
4313       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4314       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4315     }
4316   } else if (Size == 128) {
4317     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4318   } else
4319     llvm_unreachable("Unexpected vector type");
4320
4321   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4322 }
4323
4324 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4325 /// that point to V2 points to its first element.
4326 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4327   for (unsigned i = 0; i != NumElems; ++i) {
4328     if (Mask[i] > (int)NumElems) {
4329       Mask[i] = NumElems;
4330     }
4331   }
4332 }
4333
4334 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4335 /// operation of specified width.
4336 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4337                        SDValue V2) {
4338   unsigned NumElems = VT.getVectorNumElements();
4339   SmallVector<int, 8> Mask;
4340   Mask.push_back(NumElems);
4341   for (unsigned i = 1; i != NumElems; ++i)
4342     Mask.push_back(i);
4343   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4344 }
4345
4346 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4347 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4348                           SDValue V2) {
4349   unsigned NumElems = VT.getVectorNumElements();
4350   SmallVector<int, 8> Mask;
4351   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4352     Mask.push_back(i);
4353     Mask.push_back(i + NumElems);
4354   }
4355   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4356 }
4357
4358 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4359 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4360                           SDValue V2) {
4361   unsigned NumElems = VT.getVectorNumElements();
4362   SmallVector<int, 8> Mask;
4363   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4364     Mask.push_back(i + Half);
4365     Mask.push_back(i + NumElems + Half);
4366   }
4367   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4368 }
4369
4370 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4371 // a generic shuffle instruction because the target has no such instructions.
4372 // Generate shuffles which repeat i16 and i8 several times until they can be
4373 // represented by v4f32 and then be manipulated by target suported shuffles.
4374 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4375   EVT VT = V.getValueType();
4376   int NumElems = VT.getVectorNumElements();
4377   DebugLoc dl = V.getDebugLoc();
4378
4379   while (NumElems > 4) {
4380     if (EltNo < NumElems/2) {
4381       V = getUnpackl(DAG, dl, VT, V, V);
4382     } else {
4383       V = getUnpackh(DAG, dl, VT, V, V);
4384       EltNo -= NumElems/2;
4385     }
4386     NumElems >>= 1;
4387   }
4388   return V;
4389 }
4390
4391 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4392 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4393   EVT VT = V.getValueType();
4394   DebugLoc dl = V.getDebugLoc();
4395   unsigned Size = VT.getSizeInBits();
4396
4397   if (Size == 128) {
4398     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4399     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4400     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4401                              &SplatMask[0]);
4402   } else if (Size == 256) {
4403     // To use VPERMILPS to splat scalars, the second half of indicies must
4404     // refer to the higher part, which is a duplication of the lower one,
4405     // because VPERMILPS can only handle in-lane permutations.
4406     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4407                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4408
4409     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4410     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4411                              &SplatMask[0]);
4412   } else
4413     llvm_unreachable("Vector size not supported");
4414
4415   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4416 }
4417
4418 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4419 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4420   EVT SrcVT = SV->getValueType(0);
4421   SDValue V1 = SV->getOperand(0);
4422   DebugLoc dl = SV->getDebugLoc();
4423
4424   int EltNo = SV->getSplatIndex();
4425   int NumElems = SrcVT.getVectorNumElements();
4426   unsigned Size = SrcVT.getSizeInBits();
4427
4428   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4429           "Unknown how to promote splat for type");
4430
4431   // Extract the 128-bit part containing the splat element and update
4432   // the splat element index when it refers to the higher register.
4433   if (Size == 256) {
4434     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4435     if (EltNo >= NumElems/2)
4436       EltNo -= NumElems/2;
4437   }
4438
4439   // All i16 and i8 vector types can't be used directly by a generic shuffle
4440   // instruction because the target has no such instruction. Generate shuffles
4441   // which repeat i16 and i8 several times until they fit in i32, and then can
4442   // be manipulated by target suported shuffles.
4443   EVT EltVT = SrcVT.getVectorElementType();
4444   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4445     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4446
4447   // Recreate the 256-bit vector and place the same 128-bit vector
4448   // into the low and high part. This is necessary because we want
4449   // to use VPERM* to shuffle the vectors
4450   if (Size == 256) {
4451     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4452   }
4453
4454   return getLegalSplat(DAG, V1, EltNo);
4455 }
4456
4457 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4458 /// vector of zero or undef vector.  This produces a shuffle where the low
4459 /// element of V2 is swizzled into the zero/undef vector, landing at element
4460 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4461 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4462                                            bool IsZero,
4463                                            const X86Subtarget *Subtarget,
4464                                            SelectionDAG &DAG) {
4465   EVT VT = V2.getValueType();
4466   SDValue V1 = IsZero
4467     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4468   unsigned NumElems = VT.getVectorNumElements();
4469   SmallVector<int, 16> MaskVec;
4470   for (unsigned i = 0; i != NumElems; ++i)
4471     // If this is the insertion idx, put the low elt of V2 here.
4472     MaskVec.push_back(i == Idx ? NumElems : i);
4473   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4474 }
4475
4476 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4477 /// target specific opcode. Returns true if the Mask could be calculated.
4478 /// Sets IsUnary to true if only uses one source.
4479 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4480                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4481   unsigned NumElems = VT.getVectorNumElements();
4482   SDValue ImmN;
4483
4484   IsUnary = false;
4485   switch(N->getOpcode()) {
4486   case X86ISD::SHUFP:
4487     ImmN = N->getOperand(N->getNumOperands()-1);
4488     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4489     break;
4490   case X86ISD::UNPCKH:
4491     DecodeUNPCKHMask(VT, Mask);
4492     break;
4493   case X86ISD::UNPCKL:
4494     DecodeUNPCKLMask(VT, Mask);
4495     break;
4496   case X86ISD::MOVHLPS:
4497     DecodeMOVHLPSMask(NumElems, Mask);
4498     break;
4499   case X86ISD::MOVLHPS:
4500     DecodeMOVLHPSMask(NumElems, Mask);
4501     break;
4502   case X86ISD::PSHUFD:
4503   case X86ISD::VPERMILP:
4504     ImmN = N->getOperand(N->getNumOperands()-1);
4505     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4506     IsUnary = true;
4507     break;
4508   case X86ISD::PSHUFHW:
4509     ImmN = N->getOperand(N->getNumOperands()-1);
4510     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4511     IsUnary = true;
4512     break;
4513   case X86ISD::PSHUFLW:
4514     ImmN = N->getOperand(N->getNumOperands()-1);
4515     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4516     IsUnary = true;
4517     break;
4518   case X86ISD::VPERMI:
4519     ImmN = N->getOperand(N->getNumOperands()-1);
4520     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4521     IsUnary = true;
4522     break;
4523   case X86ISD::MOVSS:
4524   case X86ISD::MOVSD: {
4525     // The index 0 always comes from the first element of the second source,
4526     // this is why MOVSS and MOVSD are used in the first place. The other
4527     // elements come from the other positions of the first source vector
4528     Mask.push_back(NumElems);
4529     for (unsigned i = 1; i != NumElems; ++i) {
4530       Mask.push_back(i);
4531     }
4532     break;
4533   }
4534   case X86ISD::VPERM2X128:
4535     ImmN = N->getOperand(N->getNumOperands()-1);
4536     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4537     if (Mask.empty()) return false;
4538     break;
4539   case X86ISD::MOVDDUP:
4540   case X86ISD::MOVLHPD:
4541   case X86ISD::MOVLPD:
4542   case X86ISD::MOVLPS:
4543   case X86ISD::MOVSHDUP:
4544   case X86ISD::MOVSLDUP:
4545   case X86ISD::PALIGN:
4546     // Not yet implemented
4547     return false;
4548   default: llvm_unreachable("unknown target shuffle node");
4549   }
4550
4551   return true;
4552 }
4553
4554 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4555 /// element of the result of the vector shuffle.
4556 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4557                                    unsigned Depth) {
4558   if (Depth == 6)
4559     return SDValue();  // Limit search depth.
4560
4561   SDValue V = SDValue(N, 0);
4562   EVT VT = V.getValueType();
4563   unsigned Opcode = V.getOpcode();
4564
4565   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4566   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4567     int Elt = SV->getMaskElt(Index);
4568
4569     if (Elt < 0)
4570       return DAG.getUNDEF(VT.getVectorElementType());
4571
4572     unsigned NumElems = VT.getVectorNumElements();
4573     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4574                                          : SV->getOperand(1);
4575     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4576   }
4577
4578   // Recurse into target specific vector shuffles to find scalars.
4579   if (isTargetShuffle(Opcode)) {
4580     MVT ShufVT = V.getValueType().getSimpleVT();
4581     unsigned NumElems = ShufVT.getVectorNumElements();
4582     SmallVector<int, 16> ShuffleMask;
4583     SDValue ImmN;
4584     bool IsUnary;
4585
4586     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4587       return SDValue();
4588
4589     int Elt = ShuffleMask[Index];
4590     if (Elt < 0)
4591       return DAG.getUNDEF(ShufVT.getVectorElementType());
4592
4593     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4594                                          : N->getOperand(1);
4595     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4596                                Depth+1);
4597   }
4598
4599   // Actual nodes that may contain scalar elements
4600   if (Opcode == ISD::BITCAST) {
4601     V = V.getOperand(0);
4602     EVT SrcVT = V.getValueType();
4603     unsigned NumElems = VT.getVectorNumElements();
4604
4605     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4606       return SDValue();
4607   }
4608
4609   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4610     return (Index == 0) ? V.getOperand(0)
4611                         : DAG.getUNDEF(VT.getVectorElementType());
4612
4613   if (V.getOpcode() == ISD::BUILD_VECTOR)
4614     return V.getOperand(Index);
4615
4616   return SDValue();
4617 }
4618
4619 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4620 /// shuffle operation which come from a consecutively from a zero. The
4621 /// search can start in two different directions, from left or right.
4622 static
4623 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4624                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4625   unsigned i;
4626   for (i = 0; i != NumElems; ++i) {
4627     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4628     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4629     if (!(Elt.getNode() &&
4630          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4631       break;
4632   }
4633
4634   return i;
4635 }
4636
4637 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4638 /// correspond consecutively to elements from one of the vector operands,
4639 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4640 static
4641 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4642                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4643                               unsigned NumElems, unsigned &OpNum) {
4644   bool SeenV1 = false;
4645   bool SeenV2 = false;
4646
4647   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4648     int Idx = SVOp->getMaskElt(i);
4649     // Ignore undef indicies
4650     if (Idx < 0)
4651       continue;
4652
4653     if (Idx < (int)NumElems)
4654       SeenV1 = true;
4655     else
4656       SeenV2 = true;
4657
4658     // Only accept consecutive elements from the same vector
4659     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4660       return false;
4661   }
4662
4663   OpNum = SeenV1 ? 0 : 1;
4664   return true;
4665 }
4666
4667 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4668 /// logical left shift of a vector.
4669 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4670                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4671   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4672   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4673               false /* check zeros from right */, DAG);
4674   unsigned OpSrc;
4675
4676   if (!NumZeros)
4677     return false;
4678
4679   // Considering the elements in the mask that are not consecutive zeros,
4680   // check if they consecutively come from only one of the source vectors.
4681   //
4682   //               V1 = {X, A, B, C}     0
4683   //                         \  \  \    /
4684   //   vector_shuffle V1, V2 <1, 2, 3, X>
4685   //
4686   if (!isShuffleMaskConsecutive(SVOp,
4687             0,                   // Mask Start Index
4688             NumElems-NumZeros,   // Mask End Index(exclusive)
4689             NumZeros,            // Where to start looking in the src vector
4690             NumElems,            // Number of elements in vector
4691             OpSrc))              // Which source operand ?
4692     return false;
4693
4694   isLeft = false;
4695   ShAmt = NumZeros;
4696   ShVal = SVOp->getOperand(OpSrc);
4697   return true;
4698 }
4699
4700 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4701 /// logical left shift of a vector.
4702 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4703                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4704   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4705   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4706               true /* check zeros from left */, DAG);
4707   unsigned OpSrc;
4708
4709   if (!NumZeros)
4710     return false;
4711
4712   // Considering the elements in the mask that are not consecutive zeros,
4713   // check if they consecutively come from only one of the source vectors.
4714   //
4715   //                           0    { A, B, X, X } = V2
4716   //                          / \    /  /
4717   //   vector_shuffle V1, V2 <X, X, 4, 5>
4718   //
4719   if (!isShuffleMaskConsecutive(SVOp,
4720             NumZeros,     // Mask Start Index
4721             NumElems,     // Mask End Index(exclusive)
4722             0,            // Where to start looking in the src vector
4723             NumElems,     // Number of elements in vector
4724             OpSrc))       // Which source operand ?
4725     return false;
4726
4727   isLeft = true;
4728   ShAmt = NumZeros;
4729   ShVal = SVOp->getOperand(OpSrc);
4730   return true;
4731 }
4732
4733 /// isVectorShift - Returns true if the shuffle can be implemented as a
4734 /// logical left or right shift of a vector.
4735 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4736                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4737   // Although the logic below support any bitwidth size, there are no
4738   // shift instructions which handle more than 128-bit vectors.
4739   if (!SVOp->getValueType(0).is128BitVector())
4740     return false;
4741
4742   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4743       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4744     return true;
4745
4746   return false;
4747 }
4748
4749 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4750 ///
4751 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4752                                        unsigned NumNonZero, unsigned NumZero,
4753                                        SelectionDAG &DAG,
4754                                        const X86Subtarget* Subtarget,
4755                                        const TargetLowering &TLI) {
4756   if (NumNonZero > 8)
4757     return SDValue();
4758
4759   DebugLoc dl = Op.getDebugLoc();
4760   SDValue V(0, 0);
4761   bool First = true;
4762   for (unsigned i = 0; i < 16; ++i) {
4763     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4764     if (ThisIsNonZero && First) {
4765       if (NumZero)
4766         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4767       else
4768         V = DAG.getUNDEF(MVT::v8i16);
4769       First = false;
4770     }
4771
4772     if ((i & 1) != 0) {
4773       SDValue ThisElt(0, 0), LastElt(0, 0);
4774       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4775       if (LastIsNonZero) {
4776         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4777                               MVT::i16, Op.getOperand(i-1));
4778       }
4779       if (ThisIsNonZero) {
4780         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4781         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4782                               ThisElt, DAG.getConstant(8, MVT::i8));
4783         if (LastIsNonZero)
4784           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4785       } else
4786         ThisElt = LastElt;
4787
4788       if (ThisElt.getNode())
4789         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4790                         DAG.getIntPtrConstant(i/2));
4791     }
4792   }
4793
4794   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4795 }
4796
4797 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4798 ///
4799 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4800                                      unsigned NumNonZero, unsigned NumZero,
4801                                      SelectionDAG &DAG,
4802                                      const X86Subtarget* Subtarget,
4803                                      const TargetLowering &TLI) {
4804   if (NumNonZero > 4)
4805     return SDValue();
4806
4807   DebugLoc dl = Op.getDebugLoc();
4808   SDValue V(0, 0);
4809   bool First = true;
4810   for (unsigned i = 0; i < 8; ++i) {
4811     bool isNonZero = (NonZeros & (1 << i)) != 0;
4812     if (isNonZero) {
4813       if (First) {
4814         if (NumZero)
4815           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4816         else
4817           V = DAG.getUNDEF(MVT::v8i16);
4818         First = false;
4819       }
4820       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4821                       MVT::v8i16, V, Op.getOperand(i),
4822                       DAG.getIntPtrConstant(i));
4823     }
4824   }
4825
4826   return V;
4827 }
4828
4829 /// getVShift - Return a vector logical shift node.
4830 ///
4831 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4832                          unsigned NumBits, SelectionDAG &DAG,
4833                          const TargetLowering &TLI, DebugLoc dl) {
4834   assert(VT.is128BitVector() && "Unknown type for VShift");
4835   EVT ShVT = MVT::v2i64;
4836   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4837   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4838   return DAG.getNode(ISD::BITCAST, dl, VT,
4839                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4840                              DAG.getConstant(NumBits,
4841                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4842 }
4843
4844 SDValue
4845 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4846                                           SelectionDAG &DAG) const {
4847
4848   // Check if the scalar load can be widened into a vector load. And if
4849   // the address is "base + cst" see if the cst can be "absorbed" into
4850   // the shuffle mask.
4851   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4852     SDValue Ptr = LD->getBasePtr();
4853     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4854       return SDValue();
4855     EVT PVT = LD->getValueType(0);
4856     if (PVT != MVT::i32 && PVT != MVT::f32)
4857       return SDValue();
4858
4859     int FI = -1;
4860     int64_t Offset = 0;
4861     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4862       FI = FINode->getIndex();
4863       Offset = 0;
4864     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4865                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4866       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4867       Offset = Ptr.getConstantOperandVal(1);
4868       Ptr = Ptr.getOperand(0);
4869     } else {
4870       return SDValue();
4871     }
4872
4873     // FIXME: 256-bit vector instructions don't require a strict alignment,
4874     // improve this code to support it better.
4875     unsigned RequiredAlign = VT.getSizeInBits()/8;
4876     SDValue Chain = LD->getChain();
4877     // Make sure the stack object alignment is at least 16 or 32.
4878     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4879     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4880       if (MFI->isFixedObjectIndex(FI)) {
4881         // Can't change the alignment. FIXME: It's possible to compute
4882         // the exact stack offset and reference FI + adjust offset instead.
4883         // If someone *really* cares about this. That's the way to implement it.
4884         return SDValue();
4885       } else {
4886         MFI->setObjectAlignment(FI, RequiredAlign);
4887       }
4888     }
4889
4890     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4891     // Ptr + (Offset & ~15).
4892     if (Offset < 0)
4893       return SDValue();
4894     if ((Offset % RequiredAlign) & 3)
4895       return SDValue();
4896     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4897     if (StartOffset)
4898       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4899                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4900
4901     int EltNo = (Offset - StartOffset) >> 2;
4902     unsigned NumElems = VT.getVectorNumElements();
4903
4904     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4905     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4906                              LD->getPointerInfo().getWithOffset(StartOffset),
4907                              false, false, false, 0);
4908
4909     SmallVector<int, 8> Mask;
4910     for (unsigned i = 0; i != NumElems; ++i)
4911       Mask.push_back(EltNo);
4912
4913     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4914   }
4915
4916   return SDValue();
4917 }
4918
4919 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4920 /// vector of type 'VT', see if the elements can be replaced by a single large
4921 /// load which has the same value as a build_vector whose operands are 'elts'.
4922 ///
4923 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4924 ///
4925 /// FIXME: we'd also like to handle the case where the last elements are zero
4926 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4927 /// There's even a handy isZeroNode for that purpose.
4928 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4929                                         DebugLoc &DL, SelectionDAG &DAG) {
4930   EVT EltVT = VT.getVectorElementType();
4931   unsigned NumElems = Elts.size();
4932
4933   LoadSDNode *LDBase = NULL;
4934   unsigned LastLoadedElt = -1U;
4935
4936   // For each element in the initializer, see if we've found a load or an undef.
4937   // If we don't find an initial load element, or later load elements are
4938   // non-consecutive, bail out.
4939   for (unsigned i = 0; i < NumElems; ++i) {
4940     SDValue Elt = Elts[i];
4941
4942     if (!Elt.getNode() ||
4943         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4944       return SDValue();
4945     if (!LDBase) {
4946       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4947         return SDValue();
4948       LDBase = cast<LoadSDNode>(Elt.getNode());
4949       LastLoadedElt = i;
4950       continue;
4951     }
4952     if (Elt.getOpcode() == ISD::UNDEF)
4953       continue;
4954
4955     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4956     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4957       return SDValue();
4958     LastLoadedElt = i;
4959   }
4960
4961   // If we have found an entire vector of loads and undefs, then return a large
4962   // load of the entire vector width starting at the base pointer.  If we found
4963   // consecutive loads for the low half, generate a vzext_load node.
4964   if (LastLoadedElt == NumElems - 1) {
4965     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4966       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4967                          LDBase->getPointerInfo(),
4968                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4969                          LDBase->isInvariant(), 0);
4970     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4971                        LDBase->getPointerInfo(),
4972                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4973                        LDBase->isInvariant(), LDBase->getAlignment());
4974   }
4975   if (NumElems == 4 && LastLoadedElt == 1 &&
4976       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4977     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4978     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4979     SDValue ResNode =
4980         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4981                                 LDBase->getPointerInfo(),
4982                                 LDBase->getAlignment(),
4983                                 false/*isVolatile*/, true/*ReadMem*/,
4984                                 false/*WriteMem*/);
4985
4986     // Make sure the newly-created LOAD is in the same position as LDBase in
4987     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4988     // update uses of LDBase's output chain to use the TokenFactor.
4989     if (LDBase->hasAnyUseOfValue(1)) {
4990       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4991                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
4992       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4993       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4994                              SDValue(ResNode.getNode(), 1));
4995     }
4996
4997     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4998   }
4999   return SDValue();
5000 }
5001
5002 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5003 /// to generate a splat value for the following cases:
5004 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5005 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5006 /// a scalar load, or a constant.
5007 /// The VBROADCAST node is returned when a pattern is found,
5008 /// or SDValue() otherwise.
5009 SDValue
5010 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5011   if (!Subtarget->hasAVX())
5012     return SDValue();
5013
5014   EVT VT = Op.getValueType();
5015   DebugLoc dl = Op.getDebugLoc();
5016
5017   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5018          "Unsupported vector type for broadcast.");
5019
5020   SDValue Ld;
5021   bool ConstSplatVal;
5022
5023   switch (Op.getOpcode()) {
5024     default:
5025       // Unknown pattern found.
5026       return SDValue();
5027
5028     case ISD::BUILD_VECTOR: {
5029       // The BUILD_VECTOR node must be a splat.
5030       if (!isSplatVector(Op.getNode()))
5031         return SDValue();
5032
5033       Ld = Op.getOperand(0);
5034       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5035                      Ld.getOpcode() == ISD::ConstantFP);
5036
5037       // The suspected load node has several users. Make sure that all
5038       // of its users are from the BUILD_VECTOR node.
5039       // Constants may have multiple users.
5040       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5041         return SDValue();
5042       break;
5043     }
5044
5045     case ISD::VECTOR_SHUFFLE: {
5046       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5047
5048       // Shuffles must have a splat mask where the first element is
5049       // broadcasted.
5050       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5051         return SDValue();
5052
5053       SDValue Sc = Op.getOperand(0);
5054       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5055           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5056
5057         if (!Subtarget->hasAVX2())
5058           return SDValue();
5059
5060         // Use the register form of the broadcast instruction available on AVX2.
5061         if (VT.is256BitVector())
5062           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5063         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5064       }
5065
5066       Ld = Sc.getOperand(0);
5067       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5068                        Ld.getOpcode() == ISD::ConstantFP);
5069
5070       // The scalar_to_vector node and the suspected
5071       // load node must have exactly one user.
5072       // Constants may have multiple users.
5073       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5074         return SDValue();
5075       break;
5076     }
5077   }
5078
5079   bool Is256 = VT.is256BitVector();
5080
5081   // Handle the broadcasting a single constant scalar from the constant pool
5082   // into a vector. On Sandybridge it is still better to load a constant vector
5083   // from the constant pool and not to broadcast it from a scalar.
5084   if (ConstSplatVal && Subtarget->hasAVX2()) {
5085     EVT CVT = Ld.getValueType();
5086     assert(!CVT.isVector() && "Must not broadcast a vector type");
5087     unsigned ScalarSize = CVT.getSizeInBits();
5088
5089     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5090       const Constant *C = 0;
5091       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5092         C = CI->getConstantIntValue();
5093       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5094         C = CF->getConstantFPValue();
5095
5096       assert(C && "Invalid constant type");
5097
5098       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5099       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5100       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5101                        MachinePointerInfo::getConstantPool(),
5102                        false, false, false, Alignment);
5103
5104       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5105     }
5106   }
5107
5108   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5109   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5110
5111   // Handle AVX2 in-register broadcasts.
5112   if (!IsLoad && Subtarget->hasAVX2() &&
5113       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5114     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5115
5116   // The scalar source must be a normal load.
5117   if (!IsLoad)
5118     return SDValue();
5119
5120   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5121     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5122
5123   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5124   // double since there is no vbroadcastsd xmm
5125   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5126     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5127       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5128   }
5129
5130   // Unsupported broadcast.
5131   return SDValue();
5132 }
5133
5134 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5135 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5136 // constraint of matching input/output vector elements.
5137 SDValue
5138 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5139   DebugLoc DL = Op.getDebugLoc();
5140   SDNode *N = Op.getNode();
5141   EVT VT = Op.getValueType();
5142   unsigned NumElts = Op.getNumOperands();
5143
5144   // Check supported types and sub-targets.
5145   //
5146   // Only v2f32 -> v2f64 needs special handling.
5147   if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5148     return SDValue();
5149
5150   SDValue VecIn;
5151   EVT VecInVT;
5152   SmallVector<int, 8> Mask;
5153   EVT SrcVT = MVT::Other;
5154
5155   // Check the patterns could be translated into X86vfpext.
5156   for (unsigned i = 0; i < NumElts; ++i) {
5157     SDValue In = N->getOperand(i);
5158     unsigned Opcode = In.getOpcode();
5159
5160     // Skip if the element is undefined.
5161     if (Opcode == ISD::UNDEF) {
5162       Mask.push_back(-1);
5163       continue;
5164     }
5165
5166     // Quit if one of the elements is not defined from 'fpext'.
5167     if (Opcode != ISD::FP_EXTEND)
5168       return SDValue();
5169
5170     // Check how the source of 'fpext' is defined.
5171     SDValue L2In = In.getOperand(0);
5172     EVT L2InVT = L2In.getValueType();
5173
5174     // Check the original type
5175     if (SrcVT == MVT::Other)
5176       SrcVT = L2InVT;
5177     else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5178       return SDValue();
5179
5180     // Check whether the value being 'fpext'ed is extracted from the same
5181     // source.
5182     Opcode = L2In.getOpcode();
5183
5184     // Quit if it's not extracted with a constant index.
5185     if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5186         !isa<ConstantSDNode>(L2In.getOperand(1)))
5187       return SDValue();
5188
5189     SDValue ExtractedFromVec = L2In.getOperand(0);
5190
5191     if (VecIn.getNode() == 0) {
5192       VecIn = ExtractedFromVec;
5193       VecInVT = ExtractedFromVec.getValueType();
5194     } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5195       return SDValue();
5196
5197     Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5198   }
5199
5200   // Quit if all operands of BUILD_VECTOR are undefined.
5201   if (!VecIn.getNode())
5202     return SDValue();
5203
5204   // Fill the remaining mask as undef.
5205   for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5206     Mask.push_back(-1);
5207
5208   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5209                      DAG.getVectorShuffle(VecInVT, DL,
5210                                           VecIn, DAG.getUNDEF(VecInVT),
5211                                           &Mask[0]));
5212 }
5213
5214 SDValue
5215 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5216   DebugLoc dl = Op.getDebugLoc();
5217
5218   EVT VT = Op.getValueType();
5219   EVT ExtVT = VT.getVectorElementType();
5220   unsigned NumElems = Op.getNumOperands();
5221
5222   // Vectors containing all zeros can be matched by pxor and xorps later
5223   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5224     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5225     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5226     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5227       return Op;
5228
5229     return getZeroVector(VT, Subtarget, DAG, dl);
5230   }
5231
5232   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5233   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5234   // vpcmpeqd on 256-bit vectors.
5235   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5236     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5237       return Op;
5238
5239     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5240   }
5241
5242   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5243   if (Broadcast.getNode())
5244     return Broadcast;
5245
5246   SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5247   if (FpExt.getNode())
5248     return FpExt;
5249
5250   unsigned EVTBits = ExtVT.getSizeInBits();
5251
5252   unsigned NumZero  = 0;
5253   unsigned NumNonZero = 0;
5254   unsigned NonZeros = 0;
5255   bool IsAllConstants = true;
5256   SmallSet<SDValue, 8> Values;
5257   for (unsigned i = 0; i < NumElems; ++i) {
5258     SDValue Elt = Op.getOperand(i);
5259     if (Elt.getOpcode() == ISD::UNDEF)
5260       continue;
5261     Values.insert(Elt);
5262     if (Elt.getOpcode() != ISD::Constant &&
5263         Elt.getOpcode() != ISD::ConstantFP)
5264       IsAllConstants = false;
5265     if (X86::isZeroNode(Elt))
5266       NumZero++;
5267     else {
5268       NonZeros |= (1 << i);
5269       NumNonZero++;
5270     }
5271   }
5272
5273   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5274   if (NumNonZero == 0)
5275     return DAG.getUNDEF(VT);
5276
5277   // Special case for single non-zero, non-undef, element.
5278   if (NumNonZero == 1) {
5279     unsigned Idx = CountTrailingZeros_32(NonZeros);
5280     SDValue Item = Op.getOperand(Idx);
5281
5282     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5283     // the value are obviously zero, truncate the value to i32 and do the
5284     // insertion that way.  Only do this if the value is non-constant or if the
5285     // value is a constant being inserted into element 0.  It is cheaper to do
5286     // a constant pool load than it is to do a movd + shuffle.
5287     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5288         (!IsAllConstants || Idx == 0)) {
5289       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5290         // Handle SSE only.
5291         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5292         EVT VecVT = MVT::v4i32;
5293         unsigned VecElts = 4;
5294
5295         // Truncate the value (which may itself be a constant) to i32, and
5296         // convert it to a vector with movd (S2V+shuffle to zero extend).
5297         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5298         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5299         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5300
5301         // Now we have our 32-bit value zero extended in the low element of
5302         // a vector.  If Idx != 0, swizzle it into place.
5303         if (Idx != 0) {
5304           SmallVector<int, 4> Mask;
5305           Mask.push_back(Idx);
5306           for (unsigned i = 1; i != VecElts; ++i)
5307             Mask.push_back(i);
5308           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5309                                       &Mask[0]);
5310         }
5311         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5312       }
5313     }
5314
5315     // If we have a constant or non-constant insertion into the low element of
5316     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5317     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5318     // depending on what the source datatype is.
5319     if (Idx == 0) {
5320       if (NumZero == 0)
5321         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5322
5323       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5324           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5325         if (VT.is256BitVector()) {
5326           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5327           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5328                              Item, DAG.getIntPtrConstant(0));
5329         }
5330         assert(VT.is128BitVector() && "Expected an SSE value type!");
5331         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5332         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5333         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5334       }
5335
5336       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5337         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5338         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5339         if (VT.is256BitVector()) {
5340           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5341           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5342         } else {
5343           assert(VT.is128BitVector() && "Expected an SSE value type!");
5344           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5345         }
5346         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5347       }
5348     }
5349
5350     // Is it a vector logical left shift?
5351     if (NumElems == 2 && Idx == 1 &&
5352         X86::isZeroNode(Op.getOperand(0)) &&
5353         !X86::isZeroNode(Op.getOperand(1))) {
5354       unsigned NumBits = VT.getSizeInBits();
5355       return getVShift(true, VT,
5356                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5357                                    VT, Op.getOperand(1)),
5358                        NumBits/2, DAG, *this, dl);
5359     }
5360
5361     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5362       return SDValue();
5363
5364     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5365     // is a non-constant being inserted into an element other than the low one,
5366     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5367     // movd/movss) to move this into the low element, then shuffle it into
5368     // place.
5369     if (EVTBits == 32) {
5370       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5371
5372       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5373       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5374       SmallVector<int, 8> MaskVec;
5375       for (unsigned i = 0; i != NumElems; ++i)
5376         MaskVec.push_back(i == Idx ? 0 : 1);
5377       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5378     }
5379   }
5380
5381   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5382   if (Values.size() == 1) {
5383     if (EVTBits == 32) {
5384       // Instead of a shuffle like this:
5385       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5386       // Check if it's possible to issue this instead.
5387       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5388       unsigned Idx = CountTrailingZeros_32(NonZeros);
5389       SDValue Item = Op.getOperand(Idx);
5390       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5391         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5392     }
5393     return SDValue();
5394   }
5395
5396   // A vector full of immediates; various special cases are already
5397   // handled, so this is best done with a single constant-pool load.
5398   if (IsAllConstants)
5399     return SDValue();
5400
5401   // For AVX-length vectors, build the individual 128-bit pieces and use
5402   // shuffles to put them in place.
5403   if (VT.is256BitVector()) {
5404     SmallVector<SDValue, 32> V;
5405     for (unsigned i = 0; i != NumElems; ++i)
5406       V.push_back(Op.getOperand(i));
5407
5408     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5409
5410     // Build both the lower and upper subvector.
5411     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5412     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5413                                 NumElems/2);
5414
5415     // Recreate the wider vector with the lower and upper part.
5416     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5417   }
5418
5419   // Let legalizer expand 2-wide build_vectors.
5420   if (EVTBits == 64) {
5421     if (NumNonZero == 1) {
5422       // One half is zero or undef.
5423       unsigned Idx = CountTrailingZeros_32(NonZeros);
5424       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5425                                  Op.getOperand(Idx));
5426       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5427     }
5428     return SDValue();
5429   }
5430
5431   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5432   if (EVTBits == 8 && NumElems == 16) {
5433     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5434                                         Subtarget, *this);
5435     if (V.getNode()) return V;
5436   }
5437
5438   if (EVTBits == 16 && NumElems == 8) {
5439     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5440                                       Subtarget, *this);
5441     if (V.getNode()) return V;
5442   }
5443
5444   // If element VT is == 32 bits, turn it into a number of shuffles.
5445   SmallVector<SDValue, 8> V(NumElems);
5446   if (NumElems == 4 && NumZero > 0) {
5447     for (unsigned i = 0; i < 4; ++i) {
5448       bool isZero = !(NonZeros & (1 << i));
5449       if (isZero)
5450         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5451       else
5452         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5453     }
5454
5455     for (unsigned i = 0; i < 2; ++i) {
5456       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5457         default: break;
5458         case 0:
5459           V[i] = V[i*2];  // Must be a zero vector.
5460           break;
5461         case 1:
5462           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5463           break;
5464         case 2:
5465           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5466           break;
5467         case 3:
5468           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5469           break;
5470       }
5471     }
5472
5473     bool Reverse1 = (NonZeros & 0x3) == 2;
5474     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5475     int MaskVec[] = {
5476       Reverse1 ? 1 : 0,
5477       Reverse1 ? 0 : 1,
5478       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5479       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5480     };
5481     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5482   }
5483
5484   if (Values.size() > 1 && VT.is128BitVector()) {
5485     // Check for a build vector of consecutive loads.
5486     for (unsigned i = 0; i < NumElems; ++i)
5487       V[i] = Op.getOperand(i);
5488
5489     // Check for elements which are consecutive loads.
5490     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5491     if (LD.getNode())
5492       return LD;
5493
5494     // For SSE 4.1, use insertps to put the high elements into the low element.
5495     if (getSubtarget()->hasSSE41()) {
5496       SDValue Result;
5497       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5498         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5499       else
5500         Result = DAG.getUNDEF(VT);
5501
5502       for (unsigned i = 1; i < NumElems; ++i) {
5503         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5504         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5505                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5506       }
5507       return Result;
5508     }
5509
5510     // Otherwise, expand into a number of unpckl*, start by extending each of
5511     // our (non-undef) elements to the full vector width with the element in the
5512     // bottom slot of the vector (which generates no code for SSE).
5513     for (unsigned i = 0; i < NumElems; ++i) {
5514       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5515         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5516       else
5517         V[i] = DAG.getUNDEF(VT);
5518     }
5519
5520     // Next, we iteratively mix elements, e.g. for v4f32:
5521     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5522     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5523     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5524     unsigned EltStride = NumElems >> 1;
5525     while (EltStride != 0) {
5526       for (unsigned i = 0; i < EltStride; ++i) {
5527         // If V[i+EltStride] is undef and this is the first round of mixing,
5528         // then it is safe to just drop this shuffle: V[i] is already in the
5529         // right place, the one element (since it's the first round) being
5530         // inserted as undef can be dropped.  This isn't safe for successive
5531         // rounds because they will permute elements within both vectors.
5532         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5533             EltStride == NumElems/2)
5534           continue;
5535
5536         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5537       }
5538       EltStride >>= 1;
5539     }
5540     return V[0];
5541   }
5542   return SDValue();
5543 }
5544
5545 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5546 // to create 256-bit vectors from two other 128-bit ones.
5547 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5548   DebugLoc dl = Op.getDebugLoc();
5549   EVT ResVT = Op.getValueType();
5550
5551   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5552
5553   SDValue V1 = Op.getOperand(0);
5554   SDValue V2 = Op.getOperand(1);
5555   unsigned NumElems = ResVT.getVectorNumElements();
5556
5557   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5558 }
5559
5560 SDValue
5561 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5562   assert(Op.getNumOperands() == 2);
5563
5564   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5565   // from two other 128-bit ones.
5566   return LowerAVXCONCAT_VECTORS(Op, DAG);
5567 }
5568
5569 // Try to lower a shuffle node into a simple blend instruction.
5570 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5571                                           const X86Subtarget *Subtarget,
5572                                           SelectionDAG &DAG) {
5573   SDValue V1 = SVOp->getOperand(0);
5574   SDValue V2 = SVOp->getOperand(1);
5575   DebugLoc dl = SVOp->getDebugLoc();
5576   MVT VT = SVOp->getValueType(0).getSimpleVT();
5577   unsigned NumElems = VT.getVectorNumElements();
5578
5579   if (!Subtarget->hasSSE41())
5580     return SDValue();
5581
5582   unsigned ISDNo = 0;
5583   MVT OpTy;
5584
5585   switch (VT.SimpleTy) {
5586   default: return SDValue();
5587   case MVT::v8i16:
5588     ISDNo = X86ISD::BLENDPW;
5589     OpTy = MVT::v8i16;
5590     break;
5591   case MVT::v4i32:
5592   case MVT::v4f32:
5593     ISDNo = X86ISD::BLENDPS;
5594     OpTy = MVT::v4f32;
5595     break;
5596   case MVT::v2i64:
5597   case MVT::v2f64:
5598     ISDNo = X86ISD::BLENDPD;
5599     OpTy = MVT::v2f64;
5600     break;
5601   case MVT::v8i32:
5602   case MVT::v8f32:
5603     if (!Subtarget->hasAVX())
5604       return SDValue();
5605     ISDNo = X86ISD::BLENDPS;
5606     OpTy = MVT::v8f32;
5607     break;
5608   case MVT::v4i64:
5609   case MVT::v4f64:
5610     if (!Subtarget->hasAVX())
5611       return SDValue();
5612     ISDNo = X86ISD::BLENDPD;
5613     OpTy = MVT::v4f64;
5614     break;
5615   }
5616   assert(ISDNo && "Invalid Op Number");
5617
5618   unsigned MaskVals = 0;
5619
5620   for (unsigned i = 0; i != NumElems; ++i) {
5621     int EltIdx = SVOp->getMaskElt(i);
5622     if (EltIdx == (int)i || EltIdx < 0)
5623       MaskVals |= (1<<i);
5624     else if (EltIdx == (int)(i + NumElems))
5625       continue; // Bit is set to zero;
5626     else
5627       return SDValue();
5628   }
5629
5630   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5631   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5632   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5633                              DAG.getConstant(MaskVals, MVT::i32));
5634   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5635 }
5636
5637 // v8i16 shuffles - Prefer shuffles in the following order:
5638 // 1. [all]   pshuflw, pshufhw, optional move
5639 // 2. [ssse3] 1 x pshufb
5640 // 3. [ssse3] 2 x pshufb + 1 x por
5641 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5642 SDValue
5643 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5644                                             SelectionDAG &DAG) const {
5645   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5646   SDValue V1 = SVOp->getOperand(0);
5647   SDValue V2 = SVOp->getOperand(1);
5648   DebugLoc dl = SVOp->getDebugLoc();
5649   SmallVector<int, 8> MaskVals;
5650
5651   // Determine if more than 1 of the words in each of the low and high quadwords
5652   // of the result come from the same quadword of one of the two inputs.  Undef
5653   // mask values count as coming from any quadword, for better codegen.
5654   unsigned LoQuad[] = { 0, 0, 0, 0 };
5655   unsigned HiQuad[] = { 0, 0, 0, 0 };
5656   std::bitset<4> InputQuads;
5657   for (unsigned i = 0; i < 8; ++i) {
5658     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5659     int EltIdx = SVOp->getMaskElt(i);
5660     MaskVals.push_back(EltIdx);
5661     if (EltIdx < 0) {
5662       ++Quad[0];
5663       ++Quad[1];
5664       ++Quad[2];
5665       ++Quad[3];
5666       continue;
5667     }
5668     ++Quad[EltIdx / 4];
5669     InputQuads.set(EltIdx / 4);
5670   }
5671
5672   int BestLoQuad = -1;
5673   unsigned MaxQuad = 1;
5674   for (unsigned i = 0; i < 4; ++i) {
5675     if (LoQuad[i] > MaxQuad) {
5676       BestLoQuad = i;
5677       MaxQuad = LoQuad[i];
5678     }
5679   }
5680
5681   int BestHiQuad = -1;
5682   MaxQuad = 1;
5683   for (unsigned i = 0; i < 4; ++i) {
5684     if (HiQuad[i] > MaxQuad) {
5685       BestHiQuad = i;
5686       MaxQuad = HiQuad[i];
5687     }
5688   }
5689
5690   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5691   // of the two input vectors, shuffle them into one input vector so only a
5692   // single pshufb instruction is necessary. If There are more than 2 input
5693   // quads, disable the next transformation since it does not help SSSE3.
5694   bool V1Used = InputQuads[0] || InputQuads[1];
5695   bool V2Used = InputQuads[2] || InputQuads[3];
5696   if (Subtarget->hasSSSE3()) {
5697     if (InputQuads.count() == 2 && V1Used && V2Used) {
5698       BestLoQuad = InputQuads[0] ? 0 : 1;
5699       BestHiQuad = InputQuads[2] ? 2 : 3;
5700     }
5701     if (InputQuads.count() > 2) {
5702       BestLoQuad = -1;
5703       BestHiQuad = -1;
5704     }
5705   }
5706
5707   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5708   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5709   // words from all 4 input quadwords.
5710   SDValue NewV;
5711   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5712     int MaskV[] = {
5713       BestLoQuad < 0 ? 0 : BestLoQuad,
5714       BestHiQuad < 0 ? 1 : BestHiQuad
5715     };
5716     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5717                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5718                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5719     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5720
5721     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5722     // source words for the shuffle, to aid later transformations.
5723     bool AllWordsInNewV = true;
5724     bool InOrder[2] = { true, true };
5725     for (unsigned i = 0; i != 8; ++i) {
5726       int idx = MaskVals[i];
5727       if (idx != (int)i)
5728         InOrder[i/4] = false;
5729       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5730         continue;
5731       AllWordsInNewV = false;
5732       break;
5733     }
5734
5735     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5736     if (AllWordsInNewV) {
5737       for (int i = 0; i != 8; ++i) {
5738         int idx = MaskVals[i];
5739         if (idx < 0)
5740           continue;
5741         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5742         if ((idx != i) && idx < 4)
5743           pshufhw = false;
5744         if ((idx != i) && idx > 3)
5745           pshuflw = false;
5746       }
5747       V1 = NewV;
5748       V2Used = false;
5749       BestLoQuad = 0;
5750       BestHiQuad = 1;
5751     }
5752
5753     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5754     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5755     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5756       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5757       unsigned TargetMask = 0;
5758       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5759                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5760       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5761       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5762                              getShufflePSHUFLWImmediate(SVOp);
5763       V1 = NewV.getOperand(0);
5764       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5765     }
5766   }
5767
5768   // If we have SSSE3, and all words of the result are from 1 input vector,
5769   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5770   // is present, fall back to case 4.
5771   if (Subtarget->hasSSSE3()) {
5772     SmallVector<SDValue,16> pshufbMask;
5773
5774     // If we have elements from both input vectors, set the high bit of the
5775     // shuffle mask element to zero out elements that come from V2 in the V1
5776     // mask, and elements that come from V1 in the V2 mask, so that the two
5777     // results can be OR'd together.
5778     bool TwoInputs = V1Used && V2Used;
5779     for (unsigned i = 0; i != 8; ++i) {
5780       int EltIdx = MaskVals[i] * 2;
5781       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5782       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5783       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5784       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5785     }
5786     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5787     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5788                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5789                                  MVT::v16i8, &pshufbMask[0], 16));
5790     if (!TwoInputs)
5791       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5792
5793     // Calculate the shuffle mask for the second input, shuffle it, and
5794     // OR it with the first shuffled input.
5795     pshufbMask.clear();
5796     for (unsigned i = 0; i != 8; ++i) {
5797       int EltIdx = MaskVals[i] * 2;
5798       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5799       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5800       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5801       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5802     }
5803     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5804     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5805                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5806                                  MVT::v16i8, &pshufbMask[0], 16));
5807     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5808     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5809   }
5810
5811   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5812   // and update MaskVals with new element order.
5813   std::bitset<8> InOrder;
5814   if (BestLoQuad >= 0) {
5815     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5816     for (int i = 0; i != 4; ++i) {
5817       int idx = MaskVals[i];
5818       if (idx < 0) {
5819         InOrder.set(i);
5820       } else if ((idx / 4) == BestLoQuad) {
5821         MaskV[i] = idx & 3;
5822         InOrder.set(i);
5823       }
5824     }
5825     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5826                                 &MaskV[0]);
5827
5828     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5829       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5830       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5831                                   NewV.getOperand(0),
5832                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5833     }
5834   }
5835
5836   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5837   // and update MaskVals with the new element order.
5838   if (BestHiQuad >= 0) {
5839     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5840     for (unsigned i = 4; i != 8; ++i) {
5841       int idx = MaskVals[i];
5842       if (idx < 0) {
5843         InOrder.set(i);
5844       } else if ((idx / 4) == BestHiQuad) {
5845         MaskV[i] = (idx & 3) + 4;
5846         InOrder.set(i);
5847       }
5848     }
5849     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5850                                 &MaskV[0]);
5851
5852     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5853       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5854       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5855                                   NewV.getOperand(0),
5856                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5857     }
5858   }
5859
5860   // In case BestHi & BestLo were both -1, which means each quadword has a word
5861   // from each of the four input quadwords, calculate the InOrder bitvector now
5862   // before falling through to the insert/extract cleanup.
5863   if (BestLoQuad == -1 && BestHiQuad == -1) {
5864     NewV = V1;
5865     for (int i = 0; i != 8; ++i)
5866       if (MaskVals[i] < 0 || MaskVals[i] == i)
5867         InOrder.set(i);
5868   }
5869
5870   // The other elements are put in the right place using pextrw and pinsrw.
5871   for (unsigned i = 0; i != 8; ++i) {
5872     if (InOrder[i])
5873       continue;
5874     int EltIdx = MaskVals[i];
5875     if (EltIdx < 0)
5876       continue;
5877     SDValue ExtOp = (EltIdx < 8) ?
5878       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5879                   DAG.getIntPtrConstant(EltIdx)) :
5880       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5881                   DAG.getIntPtrConstant(EltIdx - 8));
5882     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5883                        DAG.getIntPtrConstant(i));
5884   }
5885   return NewV;
5886 }
5887
5888 // v16i8 shuffles - Prefer shuffles in the following order:
5889 // 1. [ssse3] 1 x pshufb
5890 // 2. [ssse3] 2 x pshufb + 1 x por
5891 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5892 static
5893 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5894                                  SelectionDAG &DAG,
5895                                  const X86TargetLowering &TLI) {
5896   SDValue V1 = SVOp->getOperand(0);
5897   SDValue V2 = SVOp->getOperand(1);
5898   DebugLoc dl = SVOp->getDebugLoc();
5899   ArrayRef<int> MaskVals = SVOp->getMask();
5900
5901   // If we have SSSE3, case 1 is generated when all result bytes come from
5902   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5903   // present, fall back to case 3.
5904
5905   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5906   if (TLI.getSubtarget()->hasSSSE3()) {
5907     SmallVector<SDValue,16> pshufbMask;
5908
5909     // If all result elements are from one input vector, then only translate
5910     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5911     //
5912     // Otherwise, we have elements from both input vectors, and must zero out
5913     // elements that come from V2 in the first mask, and V1 in the second mask
5914     // so that we can OR them together.
5915     for (unsigned i = 0; i != 16; ++i) {
5916       int EltIdx = MaskVals[i];
5917       if (EltIdx < 0 || EltIdx >= 16)
5918         EltIdx = 0x80;
5919       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5920     }
5921     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5922                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5923                                  MVT::v16i8, &pshufbMask[0], 16));
5924
5925     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5926     // the 2nd operand if it's undefined or zero.
5927     if (V2.getOpcode() == ISD::UNDEF ||
5928         ISD::isBuildVectorAllZeros(V2.getNode()))
5929       return V1;
5930
5931     // Calculate the shuffle mask for the second input, shuffle it, and
5932     // OR it with the first shuffled input.
5933     pshufbMask.clear();
5934     for (unsigned i = 0; i != 16; ++i) {
5935       int EltIdx = MaskVals[i];
5936       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5937       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5938     }
5939     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5940                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5941                                  MVT::v16i8, &pshufbMask[0], 16));
5942     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5943   }
5944
5945   // No SSSE3 - Calculate in place words and then fix all out of place words
5946   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5947   // the 16 different words that comprise the two doublequadword input vectors.
5948   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5949   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5950   SDValue NewV = V1;
5951   for (int i = 0; i != 8; ++i) {
5952     int Elt0 = MaskVals[i*2];
5953     int Elt1 = MaskVals[i*2+1];
5954
5955     // This word of the result is all undef, skip it.
5956     if (Elt0 < 0 && Elt1 < 0)
5957       continue;
5958
5959     // This word of the result is already in the correct place, skip it.
5960     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5961       continue;
5962
5963     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5964     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5965     SDValue InsElt;
5966
5967     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5968     // using a single extract together, load it and store it.
5969     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5970       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5971                            DAG.getIntPtrConstant(Elt1 / 2));
5972       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5973                         DAG.getIntPtrConstant(i));
5974       continue;
5975     }
5976
5977     // If Elt1 is defined, extract it from the appropriate source.  If the
5978     // source byte is not also odd, shift the extracted word left 8 bits
5979     // otherwise clear the bottom 8 bits if we need to do an or.
5980     if (Elt1 >= 0) {
5981       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5982                            DAG.getIntPtrConstant(Elt1 / 2));
5983       if ((Elt1 & 1) == 0)
5984         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5985                              DAG.getConstant(8,
5986                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5987       else if (Elt0 >= 0)
5988         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5989                              DAG.getConstant(0xFF00, MVT::i16));
5990     }
5991     // If Elt0 is defined, extract it from the appropriate source.  If the
5992     // source byte is not also even, shift the extracted word right 8 bits. If
5993     // Elt1 was also defined, OR the extracted values together before
5994     // inserting them in the result.
5995     if (Elt0 >= 0) {
5996       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5997                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5998       if ((Elt0 & 1) != 0)
5999         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6000                               DAG.getConstant(8,
6001                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6002       else if (Elt1 >= 0)
6003         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6004                              DAG.getConstant(0x00FF, MVT::i16));
6005       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6006                          : InsElt0;
6007     }
6008     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6009                        DAG.getIntPtrConstant(i));
6010   }
6011   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6012 }
6013
6014 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6015 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6016 /// done when every pair / quad of shuffle mask elements point to elements in
6017 /// the right sequence. e.g.
6018 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6019 static
6020 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6021                                  SelectionDAG &DAG, DebugLoc dl) {
6022   MVT VT = SVOp->getValueType(0).getSimpleVT();
6023   unsigned NumElems = VT.getVectorNumElements();
6024   MVT NewVT;
6025   unsigned Scale;
6026   switch (VT.SimpleTy) {
6027   default: llvm_unreachable("Unexpected!");
6028   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6029   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6030   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6031   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6032   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6033   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6034   }
6035
6036   SmallVector<int, 8> MaskVec;
6037   for (unsigned i = 0; i != NumElems; i += Scale) {
6038     int StartIdx = -1;
6039     for (unsigned j = 0; j != Scale; ++j) {
6040       int EltIdx = SVOp->getMaskElt(i+j);
6041       if (EltIdx < 0)
6042         continue;
6043       if (StartIdx < 0)
6044         StartIdx = (EltIdx / Scale);
6045       if (EltIdx != (int)(StartIdx*Scale + j))
6046         return SDValue();
6047     }
6048     MaskVec.push_back(StartIdx);
6049   }
6050
6051   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6052   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6053   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6054 }
6055
6056 /// getVZextMovL - Return a zero-extending vector move low node.
6057 ///
6058 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6059                             SDValue SrcOp, SelectionDAG &DAG,
6060                             const X86Subtarget *Subtarget, DebugLoc dl) {
6061   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6062     LoadSDNode *LD = NULL;
6063     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6064       LD = dyn_cast<LoadSDNode>(SrcOp);
6065     if (!LD) {
6066       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6067       // instead.
6068       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6069       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6070           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6071           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6072           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6073         // PR2108
6074         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6075         return DAG.getNode(ISD::BITCAST, dl, VT,
6076                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6077                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6078                                                    OpVT,
6079                                                    SrcOp.getOperand(0)
6080                                                           .getOperand(0))));
6081       }
6082     }
6083   }
6084
6085   return DAG.getNode(ISD::BITCAST, dl, VT,
6086                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6087                                  DAG.getNode(ISD::BITCAST, dl,
6088                                              OpVT, SrcOp)));
6089 }
6090
6091 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6092 /// which could not be matched by any known target speficic shuffle
6093 static SDValue
6094 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6095
6096   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6097   if (NewOp.getNode())
6098     return NewOp;
6099
6100   EVT VT = SVOp->getValueType(0);
6101
6102   unsigned NumElems = VT.getVectorNumElements();
6103   unsigned NumLaneElems = NumElems / 2;
6104
6105   DebugLoc dl = SVOp->getDebugLoc();
6106   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6107   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6108   SDValue Output[2];
6109
6110   SmallVector<int, 16> Mask;
6111   for (unsigned l = 0; l < 2; ++l) {
6112     // Build a shuffle mask for the output, discovering on the fly which
6113     // input vectors to use as shuffle operands (recorded in InputUsed).
6114     // If building a suitable shuffle vector proves too hard, then bail
6115     // out with UseBuildVector set.
6116     bool UseBuildVector = false;
6117     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6118     unsigned LaneStart = l * NumLaneElems;
6119     for (unsigned i = 0; i != NumLaneElems; ++i) {
6120       // The mask element.  This indexes into the input.
6121       int Idx = SVOp->getMaskElt(i+LaneStart);
6122       if (Idx < 0) {
6123         // the mask element does not index into any input vector.
6124         Mask.push_back(-1);
6125         continue;
6126       }
6127
6128       // The input vector this mask element indexes into.
6129       int Input = Idx / NumLaneElems;
6130
6131       // Turn the index into an offset from the start of the input vector.
6132       Idx -= Input * NumLaneElems;
6133
6134       // Find or create a shuffle vector operand to hold this input.
6135       unsigned OpNo;
6136       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6137         if (InputUsed[OpNo] == Input)
6138           // This input vector is already an operand.
6139           break;
6140         if (InputUsed[OpNo] < 0) {
6141           // Create a new operand for this input vector.
6142           InputUsed[OpNo] = Input;
6143           break;
6144         }
6145       }
6146
6147       if (OpNo >= array_lengthof(InputUsed)) {
6148         // More than two input vectors used!  Give up on trying to create a
6149         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6150         UseBuildVector = true;
6151         break;
6152       }
6153
6154       // Add the mask index for the new shuffle vector.
6155       Mask.push_back(Idx + OpNo * NumLaneElems);
6156     }
6157
6158     if (UseBuildVector) {
6159       SmallVector<SDValue, 16> SVOps;
6160       for (unsigned i = 0; i != NumLaneElems; ++i) {
6161         // The mask element.  This indexes into the input.
6162         int Idx = SVOp->getMaskElt(i+LaneStart);
6163         if (Idx < 0) {
6164           SVOps.push_back(DAG.getUNDEF(EltVT));
6165           continue;
6166         }
6167
6168         // The input vector this mask element indexes into.
6169         int Input = Idx / NumElems;
6170
6171         // Turn the index into an offset from the start of the input vector.
6172         Idx -= Input * NumElems;
6173
6174         // Extract the vector element by hand.
6175         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6176                                     SVOp->getOperand(Input),
6177                                     DAG.getIntPtrConstant(Idx)));
6178       }
6179
6180       // Construct the output using a BUILD_VECTOR.
6181       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6182                               SVOps.size());
6183     } else if (InputUsed[0] < 0) {
6184       // No input vectors were used! The result is undefined.
6185       Output[l] = DAG.getUNDEF(NVT);
6186     } else {
6187       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6188                                         (InputUsed[0] % 2) * NumLaneElems,
6189                                         DAG, dl);
6190       // If only one input was used, use an undefined vector for the other.
6191       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6192         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6193                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6194       // At least one input vector was used. Create a new shuffle vector.
6195       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6196     }
6197
6198     Mask.clear();
6199   }
6200
6201   // Concatenate the result back
6202   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6203 }
6204
6205 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6206 /// 4 elements, and match them with several different shuffle types.
6207 static SDValue
6208 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6209   SDValue V1 = SVOp->getOperand(0);
6210   SDValue V2 = SVOp->getOperand(1);
6211   DebugLoc dl = SVOp->getDebugLoc();
6212   EVT VT = SVOp->getValueType(0);
6213
6214   assert(VT.is128BitVector() && "Unsupported vector size");
6215
6216   std::pair<int, int> Locs[4];
6217   int Mask1[] = { -1, -1, -1, -1 };
6218   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6219
6220   unsigned NumHi = 0;
6221   unsigned NumLo = 0;
6222   for (unsigned i = 0; i != 4; ++i) {
6223     int Idx = PermMask[i];
6224     if (Idx < 0) {
6225       Locs[i] = std::make_pair(-1, -1);
6226     } else {
6227       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6228       if (Idx < 4) {
6229         Locs[i] = std::make_pair(0, NumLo);
6230         Mask1[NumLo] = Idx;
6231         NumLo++;
6232       } else {
6233         Locs[i] = std::make_pair(1, NumHi);
6234         if (2+NumHi < 4)
6235           Mask1[2+NumHi] = Idx;
6236         NumHi++;
6237       }
6238     }
6239   }
6240
6241   if (NumLo <= 2 && NumHi <= 2) {
6242     // If no more than two elements come from either vector. This can be
6243     // implemented with two shuffles. First shuffle gather the elements.
6244     // The second shuffle, which takes the first shuffle as both of its
6245     // vector operands, put the elements into the right order.
6246     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6247
6248     int Mask2[] = { -1, -1, -1, -1 };
6249
6250     for (unsigned i = 0; i != 4; ++i)
6251       if (Locs[i].first != -1) {
6252         unsigned Idx = (i < 2) ? 0 : 4;
6253         Idx += Locs[i].first * 2 + Locs[i].second;
6254         Mask2[i] = Idx;
6255       }
6256
6257     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6258   }
6259
6260   if (NumLo == 3 || NumHi == 3) {
6261     // Otherwise, we must have three elements from one vector, call it X, and
6262     // one element from the other, call it Y.  First, use a shufps to build an
6263     // intermediate vector with the one element from Y and the element from X
6264     // that will be in the same half in the final destination (the indexes don't
6265     // matter). Then, use a shufps to build the final vector, taking the half
6266     // containing the element from Y from the intermediate, and the other half
6267     // from X.
6268     if (NumHi == 3) {
6269       // Normalize it so the 3 elements come from V1.
6270       CommuteVectorShuffleMask(PermMask, 4);
6271       std::swap(V1, V2);
6272     }
6273
6274     // Find the element from V2.
6275     unsigned HiIndex;
6276     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6277       int Val = PermMask[HiIndex];
6278       if (Val < 0)
6279         continue;
6280       if (Val >= 4)
6281         break;
6282     }
6283
6284     Mask1[0] = PermMask[HiIndex];
6285     Mask1[1] = -1;
6286     Mask1[2] = PermMask[HiIndex^1];
6287     Mask1[3] = -1;
6288     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6289
6290     if (HiIndex >= 2) {
6291       Mask1[0] = PermMask[0];
6292       Mask1[1] = PermMask[1];
6293       Mask1[2] = HiIndex & 1 ? 6 : 4;
6294       Mask1[3] = HiIndex & 1 ? 4 : 6;
6295       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6296     }
6297
6298     Mask1[0] = HiIndex & 1 ? 2 : 0;
6299     Mask1[1] = HiIndex & 1 ? 0 : 2;
6300     Mask1[2] = PermMask[2];
6301     Mask1[3] = PermMask[3];
6302     if (Mask1[2] >= 0)
6303       Mask1[2] += 4;
6304     if (Mask1[3] >= 0)
6305       Mask1[3] += 4;
6306     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6307   }
6308
6309   // Break it into (shuffle shuffle_hi, shuffle_lo).
6310   int LoMask[] = { -1, -1, -1, -1 };
6311   int HiMask[] = { -1, -1, -1, -1 };
6312
6313   int *MaskPtr = LoMask;
6314   unsigned MaskIdx = 0;
6315   unsigned LoIdx = 0;
6316   unsigned HiIdx = 2;
6317   for (unsigned i = 0; i != 4; ++i) {
6318     if (i == 2) {
6319       MaskPtr = HiMask;
6320       MaskIdx = 1;
6321       LoIdx = 0;
6322       HiIdx = 2;
6323     }
6324     int Idx = PermMask[i];
6325     if (Idx < 0) {
6326       Locs[i] = std::make_pair(-1, -1);
6327     } else if (Idx < 4) {
6328       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6329       MaskPtr[LoIdx] = Idx;
6330       LoIdx++;
6331     } else {
6332       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6333       MaskPtr[HiIdx] = Idx;
6334       HiIdx++;
6335     }
6336   }
6337
6338   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6339   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6340   int MaskOps[] = { -1, -1, -1, -1 };
6341   for (unsigned i = 0; i != 4; ++i)
6342     if (Locs[i].first != -1)
6343       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6344   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6345 }
6346
6347 static bool MayFoldVectorLoad(SDValue V) {
6348   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6349     V = V.getOperand(0);
6350   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6351     V = V.getOperand(0);
6352   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6353       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6354     // BUILD_VECTOR (load), undef
6355     V = V.getOperand(0);
6356   if (MayFoldLoad(V))
6357     return true;
6358   return false;
6359 }
6360
6361 // FIXME: the version above should always be used. Since there's
6362 // a bug where several vector shuffles can't be folded because the
6363 // DAG is not updated during lowering and a node claims to have two
6364 // uses while it only has one, use this version, and let isel match
6365 // another instruction if the load really happens to have more than
6366 // one use. Remove this version after this bug get fixed.
6367 // rdar://8434668, PR8156
6368 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6369   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6370     V = V.getOperand(0);
6371   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6372     V = V.getOperand(0);
6373   if (ISD::isNormalLoad(V.getNode()))
6374     return true;
6375   return false;
6376 }
6377
6378 static
6379 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6380   EVT VT = Op.getValueType();
6381
6382   // Canonizalize to v2f64.
6383   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6384   return DAG.getNode(ISD::BITCAST, dl, VT,
6385                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6386                                           V1, DAG));
6387 }
6388
6389 static
6390 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6391                         bool HasSSE2) {
6392   SDValue V1 = Op.getOperand(0);
6393   SDValue V2 = Op.getOperand(1);
6394   EVT VT = Op.getValueType();
6395
6396   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6397
6398   if (HasSSE2 && VT == MVT::v2f64)
6399     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6400
6401   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6402   return DAG.getNode(ISD::BITCAST, dl, VT,
6403                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6404                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6405                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6406 }
6407
6408 static
6409 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6410   SDValue V1 = Op.getOperand(0);
6411   SDValue V2 = Op.getOperand(1);
6412   EVT VT = Op.getValueType();
6413
6414   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6415          "unsupported shuffle type");
6416
6417   if (V2.getOpcode() == ISD::UNDEF)
6418     V2 = V1;
6419
6420   // v4i32 or v4f32
6421   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6422 }
6423
6424 static
6425 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6426   SDValue V1 = Op.getOperand(0);
6427   SDValue V2 = Op.getOperand(1);
6428   EVT VT = Op.getValueType();
6429   unsigned NumElems = VT.getVectorNumElements();
6430
6431   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6432   // operand of these instructions is only memory, so check if there's a
6433   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6434   // same masks.
6435   bool CanFoldLoad = false;
6436
6437   // Trivial case, when V2 comes from a load.
6438   if (MayFoldVectorLoad(V2))
6439     CanFoldLoad = true;
6440
6441   // When V1 is a load, it can be folded later into a store in isel, example:
6442   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6443   //    turns into:
6444   //  (MOVLPSmr addr:$src1, VR128:$src2)
6445   // So, recognize this potential and also use MOVLPS or MOVLPD
6446   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6447     CanFoldLoad = true;
6448
6449   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6450   if (CanFoldLoad) {
6451     if (HasSSE2 && NumElems == 2)
6452       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6453
6454     if (NumElems == 4)
6455       // If we don't care about the second element, proceed to use movss.
6456       if (SVOp->getMaskElt(1) != -1)
6457         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6458   }
6459
6460   // movl and movlp will both match v2i64, but v2i64 is never matched by
6461   // movl earlier because we make it strict to avoid messing with the movlp load
6462   // folding logic (see the code above getMOVLP call). Match it here then,
6463   // this is horrible, but will stay like this until we move all shuffle
6464   // matching to x86 specific nodes. Note that for the 1st condition all
6465   // types are matched with movsd.
6466   if (HasSSE2) {
6467     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6468     // as to remove this logic from here, as much as possible
6469     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6470       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6471     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6472   }
6473
6474   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6475
6476   // Invert the operand order and use SHUFPS to match it.
6477   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6478                               getShuffleSHUFImmediate(SVOp), DAG);
6479 }
6480
6481 SDValue
6482 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6483   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6484   EVT VT = Op.getValueType();
6485   DebugLoc dl = Op.getDebugLoc();
6486   SDValue V1 = Op.getOperand(0);
6487   SDValue V2 = Op.getOperand(1);
6488
6489   if (isZeroShuffle(SVOp))
6490     return getZeroVector(VT, Subtarget, DAG, dl);
6491
6492   // Handle splat operations
6493   if (SVOp->isSplat()) {
6494     unsigned NumElem = VT.getVectorNumElements();
6495     int Size = VT.getSizeInBits();
6496
6497     // Use vbroadcast whenever the splat comes from a foldable load
6498     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6499     if (Broadcast.getNode())
6500       return Broadcast;
6501
6502     // Handle splats by matching through known shuffle masks
6503     if ((Size == 128 && NumElem <= 4) ||
6504         (Size == 256 && NumElem < 8))
6505       return SDValue();
6506
6507     // All remaning splats are promoted to target supported vector shuffles.
6508     return PromoteSplat(SVOp, DAG);
6509   }
6510
6511   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6512   // do it!
6513   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6514       VT == MVT::v16i16 || VT == MVT::v32i8) {
6515     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6516     if (NewOp.getNode())
6517       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6518   } else if ((VT == MVT::v4i32 ||
6519              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6520     // FIXME: Figure out a cleaner way to do this.
6521     // Try to make use of movq to zero out the top part.
6522     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6523       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6524       if (NewOp.getNode()) {
6525         EVT NewVT = NewOp.getValueType();
6526         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6527                                NewVT, true, false))
6528           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6529                               DAG, Subtarget, dl);
6530       }
6531     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6532       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6533       if (NewOp.getNode()) {
6534         EVT NewVT = NewOp.getValueType();
6535         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6536           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6537                               DAG, Subtarget, dl);
6538       }
6539     }
6540   }
6541   return SDValue();
6542 }
6543
6544 SDValue
6545 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6546   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6547   SDValue V1 = Op.getOperand(0);
6548   SDValue V2 = Op.getOperand(1);
6549   EVT VT = Op.getValueType();
6550   DebugLoc dl = Op.getDebugLoc();
6551   unsigned NumElems = VT.getVectorNumElements();
6552   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6553   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6554   bool V1IsSplat = false;
6555   bool V2IsSplat = false;
6556   bool HasSSE2 = Subtarget->hasSSE2();
6557   bool HasAVX    = Subtarget->hasAVX();
6558   bool HasAVX2   = Subtarget->hasAVX2();
6559   MachineFunction &MF = DAG.getMachineFunction();
6560   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6561
6562   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6563
6564   if (V1IsUndef && V2IsUndef)
6565     return DAG.getUNDEF(VT);
6566
6567   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6568
6569   // Vector shuffle lowering takes 3 steps:
6570   //
6571   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6572   //    narrowing and commutation of operands should be handled.
6573   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6574   //    shuffle nodes.
6575   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6576   //    so the shuffle can be broken into other shuffles and the legalizer can
6577   //    try the lowering again.
6578   //
6579   // The general idea is that no vector_shuffle operation should be left to
6580   // be matched during isel, all of them must be converted to a target specific
6581   // node here.
6582
6583   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6584   // narrowing and commutation of operands should be handled. The actual code
6585   // doesn't include all of those, work in progress...
6586   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6587   if (NewOp.getNode())
6588     return NewOp;
6589
6590   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6591
6592   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6593   // unpckh_undef). Only use pshufd if speed is more important than size.
6594   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6595     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6596   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6597     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6598
6599   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6600       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6601     return getMOVDDup(Op, dl, V1, DAG);
6602
6603   if (isMOVHLPS_v_undef_Mask(M, VT))
6604     return getMOVHighToLow(Op, dl, DAG);
6605
6606   // Use to match splats
6607   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6608       (VT == MVT::v2f64 || VT == MVT::v2i64))
6609     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6610
6611   if (isPSHUFDMask(M, VT)) {
6612     // The actual implementation will match the mask in the if above and then
6613     // during isel it can match several different instructions, not only pshufd
6614     // as its name says, sad but true, emulate the behavior for now...
6615     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6616       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6617
6618     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6619
6620     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6621       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6622
6623     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6624       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6625
6626     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6627                                 TargetMask, DAG);
6628   }
6629
6630   // Check if this can be converted into a logical shift.
6631   bool isLeft = false;
6632   unsigned ShAmt = 0;
6633   SDValue ShVal;
6634   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6635   if (isShift && ShVal.hasOneUse()) {
6636     // If the shifted value has multiple uses, it may be cheaper to use
6637     // v_set0 + movlhps or movhlps, etc.
6638     EVT EltVT = VT.getVectorElementType();
6639     ShAmt *= EltVT.getSizeInBits();
6640     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6641   }
6642
6643   if (isMOVLMask(M, VT)) {
6644     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6645       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6646     if (!isMOVLPMask(M, VT)) {
6647       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6648         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6649
6650       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6651         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6652     }
6653   }
6654
6655   // FIXME: fold these into legal mask.
6656   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6657     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6658
6659   if (isMOVHLPSMask(M, VT))
6660     return getMOVHighToLow(Op, dl, DAG);
6661
6662   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6663     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6664
6665   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6666     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6667
6668   if (isMOVLPMask(M, VT))
6669     return getMOVLP(Op, dl, DAG, HasSSE2);
6670
6671   if (ShouldXformToMOVHLPS(M, VT) ||
6672       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6673     return CommuteVectorShuffle(SVOp, DAG);
6674
6675   if (isShift) {
6676     // No better options. Use a vshldq / vsrldq.
6677     EVT EltVT = VT.getVectorElementType();
6678     ShAmt *= EltVT.getSizeInBits();
6679     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6680   }
6681
6682   bool Commuted = false;
6683   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6684   // 1,1,1,1 -> v8i16 though.
6685   V1IsSplat = isSplatVector(V1.getNode());
6686   V2IsSplat = isSplatVector(V2.getNode());
6687
6688   // Canonicalize the splat or undef, if present, to be on the RHS.
6689   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6690     CommuteVectorShuffleMask(M, NumElems);
6691     std::swap(V1, V2);
6692     std::swap(V1IsSplat, V2IsSplat);
6693     Commuted = true;
6694   }
6695
6696   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6697     // Shuffling low element of v1 into undef, just return v1.
6698     if (V2IsUndef)
6699       return V1;
6700     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6701     // the instruction selector will not match, so get a canonical MOVL with
6702     // swapped operands to undo the commute.
6703     return getMOVL(DAG, dl, VT, V2, V1);
6704   }
6705
6706   if (isUNPCKLMask(M, VT, HasAVX2))
6707     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6708
6709   if (isUNPCKHMask(M, VT, HasAVX2))
6710     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6711
6712   if (V2IsSplat) {
6713     // Normalize mask so all entries that point to V2 points to its first
6714     // element then try to match unpck{h|l} again. If match, return a
6715     // new vector_shuffle with the corrected mask.p
6716     SmallVector<int, 8> NewMask(M.begin(), M.end());
6717     NormalizeMask(NewMask, NumElems);
6718     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6719       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6720     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6721       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6722   }
6723
6724   if (Commuted) {
6725     // Commute is back and try unpck* again.
6726     // FIXME: this seems wrong.
6727     CommuteVectorShuffleMask(M, NumElems);
6728     std::swap(V1, V2);
6729     std::swap(V1IsSplat, V2IsSplat);
6730     Commuted = false;
6731
6732     if (isUNPCKLMask(M, VT, HasAVX2))
6733       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6734
6735     if (isUNPCKHMask(M, VT, HasAVX2))
6736       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6737   }
6738
6739   // Normalize the node to match x86 shuffle ops if needed
6740   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6741     return CommuteVectorShuffle(SVOp, DAG);
6742
6743   // The checks below are all present in isShuffleMaskLegal, but they are
6744   // inlined here right now to enable us to directly emit target specific
6745   // nodes, and remove one by one until they don't return Op anymore.
6746
6747   if (isPALIGNRMask(M, VT, Subtarget))
6748     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6749                                 getShufflePALIGNRImmediate(SVOp),
6750                                 DAG);
6751
6752   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6753       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6754     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6755       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6756   }
6757
6758   if (isPSHUFHWMask(M, VT, HasAVX2))
6759     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6760                                 getShufflePSHUFHWImmediate(SVOp),
6761                                 DAG);
6762
6763   if (isPSHUFLWMask(M, VT, HasAVX2))
6764     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6765                                 getShufflePSHUFLWImmediate(SVOp),
6766                                 DAG);
6767
6768   if (isSHUFPMask(M, VT, HasAVX))
6769     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6770                                 getShuffleSHUFImmediate(SVOp), DAG);
6771
6772   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6773     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6774   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6775     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6776
6777   //===--------------------------------------------------------------------===//
6778   // Generate target specific nodes for 128 or 256-bit shuffles only
6779   // supported in the AVX instruction set.
6780   //
6781
6782   // Handle VMOVDDUPY permutations
6783   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6784     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6785
6786   // Handle VPERMILPS/D* permutations
6787   if (isVPERMILPMask(M, VT, HasAVX)) {
6788     if (HasAVX2 && VT == MVT::v8i32)
6789       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6790                                   getShuffleSHUFImmediate(SVOp), DAG);
6791     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6792                                 getShuffleSHUFImmediate(SVOp), DAG);
6793   }
6794
6795   // Handle VPERM2F128/VPERM2I128 permutations
6796   if (isVPERM2X128Mask(M, VT, HasAVX))
6797     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6798                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6799
6800   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6801   if (BlendOp.getNode())
6802     return BlendOp;
6803
6804   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6805     SmallVector<SDValue, 8> permclMask;
6806     for (unsigned i = 0; i != 8; ++i) {
6807       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6808     }
6809     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6810                                &permclMask[0], 8);
6811     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6812     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6813                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6814   }
6815
6816   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6817     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6818                                 getShuffleCLImmediate(SVOp), DAG);
6819
6820
6821   //===--------------------------------------------------------------------===//
6822   // Since no target specific shuffle was selected for this generic one,
6823   // lower it into other known shuffles. FIXME: this isn't true yet, but
6824   // this is the plan.
6825   //
6826
6827   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6828   if (VT == MVT::v8i16) {
6829     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6830     if (NewOp.getNode())
6831       return NewOp;
6832   }
6833
6834   if (VT == MVT::v16i8) {
6835     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6836     if (NewOp.getNode())
6837       return NewOp;
6838   }
6839
6840   // Handle all 128-bit wide vectors with 4 elements, and match them with
6841   // several different shuffle types.
6842   if (NumElems == 4 && VT.is128BitVector())
6843     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6844
6845   // Handle general 256-bit shuffles
6846   if (VT.is256BitVector())
6847     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6848
6849   return SDValue();
6850 }
6851
6852 SDValue
6853 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6854                                                 SelectionDAG &DAG) const {
6855   EVT VT = Op.getValueType();
6856   DebugLoc dl = Op.getDebugLoc();
6857
6858   if (!Op.getOperand(0).getValueType().is128BitVector())
6859     return SDValue();
6860
6861   if (VT.getSizeInBits() == 8) {
6862     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6863                                     Op.getOperand(0), Op.getOperand(1));
6864     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6865                                     DAG.getValueType(VT));
6866     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6867   }
6868
6869   if (VT.getSizeInBits() == 16) {
6870     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6871     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6872     if (Idx == 0)
6873       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6874                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6875                                      DAG.getNode(ISD::BITCAST, dl,
6876                                                  MVT::v4i32,
6877                                                  Op.getOperand(0)),
6878                                      Op.getOperand(1)));
6879     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6880                                     Op.getOperand(0), Op.getOperand(1));
6881     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6882                                     DAG.getValueType(VT));
6883     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6884   }
6885
6886   if (VT == MVT::f32) {
6887     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6888     // the result back to FR32 register. It's only worth matching if the
6889     // result has a single use which is a store or a bitcast to i32.  And in
6890     // the case of a store, it's not worth it if the index is a constant 0,
6891     // because a MOVSSmr can be used instead, which is smaller and faster.
6892     if (!Op.hasOneUse())
6893       return SDValue();
6894     SDNode *User = *Op.getNode()->use_begin();
6895     if ((User->getOpcode() != ISD::STORE ||
6896          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6897           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6898         (User->getOpcode() != ISD::BITCAST ||
6899          User->getValueType(0) != MVT::i32))
6900       return SDValue();
6901     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6902                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6903                                               Op.getOperand(0)),
6904                                               Op.getOperand(1));
6905     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6906   }
6907
6908   if (VT == MVT::i32 || VT == MVT::i64) {
6909     // ExtractPS/pextrq works with constant index.
6910     if (isa<ConstantSDNode>(Op.getOperand(1)))
6911       return Op;
6912   }
6913   return SDValue();
6914 }
6915
6916
6917 SDValue
6918 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6919                                            SelectionDAG &DAG) const {
6920   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6921     return SDValue();
6922
6923   SDValue Vec = Op.getOperand(0);
6924   EVT VecVT = Vec.getValueType();
6925
6926   // If this is a 256-bit vector result, first extract the 128-bit vector and
6927   // then extract the element from the 128-bit vector.
6928   if (VecVT.is256BitVector()) {
6929     DebugLoc dl = Op.getNode()->getDebugLoc();
6930     unsigned NumElems = VecVT.getVectorNumElements();
6931     SDValue Idx = Op.getOperand(1);
6932     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6933
6934     // Get the 128-bit vector.
6935     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6936
6937     if (IdxVal >= NumElems/2)
6938       IdxVal -= NumElems/2;
6939     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6940                        DAG.getConstant(IdxVal, MVT::i32));
6941   }
6942
6943   assert(VecVT.is128BitVector() && "Unexpected vector length");
6944
6945   if (Subtarget->hasSSE41()) {
6946     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6947     if (Res.getNode())
6948       return Res;
6949   }
6950
6951   EVT VT = Op.getValueType();
6952   DebugLoc dl = Op.getDebugLoc();
6953   // TODO: handle v16i8.
6954   if (VT.getSizeInBits() == 16) {
6955     SDValue Vec = Op.getOperand(0);
6956     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6957     if (Idx == 0)
6958       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6959                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6960                                      DAG.getNode(ISD::BITCAST, dl,
6961                                                  MVT::v4i32, Vec),
6962                                      Op.getOperand(1)));
6963     // Transform it so it match pextrw which produces a 32-bit result.
6964     EVT EltVT = MVT::i32;
6965     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6966                                     Op.getOperand(0), Op.getOperand(1));
6967     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6968                                     DAG.getValueType(VT));
6969     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6970   }
6971
6972   if (VT.getSizeInBits() == 32) {
6973     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6974     if (Idx == 0)
6975       return Op;
6976
6977     // SHUFPS the element to the lowest double word, then movss.
6978     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6979     EVT VVT = Op.getOperand(0).getValueType();
6980     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6981                                        DAG.getUNDEF(VVT), Mask);
6982     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6983                        DAG.getIntPtrConstant(0));
6984   }
6985
6986   if (VT.getSizeInBits() == 64) {
6987     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6988     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6989     //        to match extract_elt for f64.
6990     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6991     if (Idx == 0)
6992       return Op;
6993
6994     // UNPCKHPD the element to the lowest double word, then movsd.
6995     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6996     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6997     int Mask[2] = { 1, -1 };
6998     EVT VVT = Op.getOperand(0).getValueType();
6999     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7000                                        DAG.getUNDEF(VVT), Mask);
7001     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7002                        DAG.getIntPtrConstant(0));
7003   }
7004
7005   return SDValue();
7006 }
7007
7008 SDValue
7009 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7010                                                SelectionDAG &DAG) const {
7011   EVT VT = Op.getValueType();
7012   EVT EltVT = VT.getVectorElementType();
7013   DebugLoc dl = Op.getDebugLoc();
7014
7015   SDValue N0 = Op.getOperand(0);
7016   SDValue N1 = Op.getOperand(1);
7017   SDValue N2 = Op.getOperand(2);
7018
7019   if (!VT.is128BitVector())
7020     return SDValue();
7021
7022   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7023       isa<ConstantSDNode>(N2)) {
7024     unsigned Opc;
7025     if (VT == MVT::v8i16)
7026       Opc = X86ISD::PINSRW;
7027     else if (VT == MVT::v16i8)
7028       Opc = X86ISD::PINSRB;
7029     else
7030       Opc = X86ISD::PINSRB;
7031
7032     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7033     // argument.
7034     if (N1.getValueType() != MVT::i32)
7035       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7036     if (N2.getValueType() != MVT::i32)
7037       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7038     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7039   }
7040
7041   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7042     // Bits [7:6] of the constant are the source select.  This will always be
7043     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7044     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7045     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7046     // Bits [5:4] of the constant are the destination select.  This is the
7047     //  value of the incoming immediate.
7048     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7049     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7050     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7051     // Create this as a scalar to vector..
7052     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7053     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7054   }
7055
7056   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7057     // PINSR* works with constant index.
7058     return Op;
7059   }
7060   return SDValue();
7061 }
7062
7063 SDValue
7064 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7065   EVT VT = Op.getValueType();
7066   EVT EltVT = VT.getVectorElementType();
7067
7068   DebugLoc dl = Op.getDebugLoc();
7069   SDValue N0 = Op.getOperand(0);
7070   SDValue N1 = Op.getOperand(1);
7071   SDValue N2 = Op.getOperand(2);
7072
7073   // If this is a 256-bit vector result, first extract the 128-bit vector,
7074   // insert the element into the extracted half and then place it back.
7075   if (VT.is256BitVector()) {
7076     if (!isa<ConstantSDNode>(N2))
7077       return SDValue();
7078
7079     // Get the desired 128-bit vector half.
7080     unsigned NumElems = VT.getVectorNumElements();
7081     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7082     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7083
7084     // Insert the element into the desired half.
7085     bool Upper = IdxVal >= NumElems/2;
7086     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7087                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7088
7089     // Insert the changed part back to the 256-bit vector
7090     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7091   }
7092
7093   if (Subtarget->hasSSE41())
7094     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7095
7096   if (EltVT == MVT::i8)
7097     return SDValue();
7098
7099   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7100     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7101     // as its second argument.
7102     if (N1.getValueType() != MVT::i32)
7103       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7104     if (N2.getValueType() != MVT::i32)
7105       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7106     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7107   }
7108   return SDValue();
7109 }
7110
7111 SDValue
7112 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7113   LLVMContext *Context = DAG.getContext();
7114   DebugLoc dl = Op.getDebugLoc();
7115   EVT OpVT = Op.getValueType();
7116
7117   // If this is a 256-bit vector result, first insert into a 128-bit
7118   // vector and then insert into the 256-bit vector.
7119   if (!OpVT.is128BitVector()) {
7120     // Insert into a 128-bit vector.
7121     EVT VT128 = EVT::getVectorVT(*Context,
7122                                  OpVT.getVectorElementType(),
7123                                  OpVT.getVectorNumElements() / 2);
7124
7125     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7126
7127     // Insert the 128-bit vector.
7128     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7129   }
7130
7131   if (OpVT == MVT::v1i64 &&
7132       Op.getOperand(0).getValueType() == MVT::i64)
7133     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7134
7135   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7136   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7137   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7138                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7139 }
7140
7141 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7142 // a simple subregister reference or explicit instructions to grab
7143 // upper bits of a vector.
7144 SDValue
7145 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7146   if (Subtarget->hasAVX()) {
7147     DebugLoc dl = Op.getNode()->getDebugLoc();
7148     SDValue Vec = Op.getNode()->getOperand(0);
7149     SDValue Idx = Op.getNode()->getOperand(1);
7150
7151     if (Op.getNode()->getValueType(0).is128BitVector() &&
7152         Vec.getNode()->getValueType(0).is256BitVector() &&
7153         isa<ConstantSDNode>(Idx)) {
7154       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7155       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7156     }
7157   }
7158   return SDValue();
7159 }
7160
7161 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7162 // simple superregister reference or explicit instructions to insert
7163 // the upper bits of a vector.
7164 SDValue
7165 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7166   if (Subtarget->hasAVX()) {
7167     DebugLoc dl = Op.getNode()->getDebugLoc();
7168     SDValue Vec = Op.getNode()->getOperand(0);
7169     SDValue SubVec = Op.getNode()->getOperand(1);
7170     SDValue Idx = Op.getNode()->getOperand(2);
7171
7172     if (Op.getNode()->getValueType(0).is256BitVector() &&
7173         SubVec.getNode()->getValueType(0).is128BitVector() &&
7174         isa<ConstantSDNode>(Idx)) {
7175       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7176       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7177     }
7178   }
7179   return SDValue();
7180 }
7181
7182 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7183 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7184 // one of the above mentioned nodes. It has to be wrapped because otherwise
7185 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7186 // be used to form addressing mode. These wrapped nodes will be selected
7187 // into MOV32ri.
7188 SDValue
7189 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7190   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7191
7192   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7193   // global base reg.
7194   unsigned char OpFlag = 0;
7195   unsigned WrapperKind = X86ISD::Wrapper;
7196   CodeModel::Model M = getTargetMachine().getCodeModel();
7197
7198   if (Subtarget->isPICStyleRIPRel() &&
7199       (M == CodeModel::Small || M == CodeModel::Kernel))
7200     WrapperKind = X86ISD::WrapperRIP;
7201   else if (Subtarget->isPICStyleGOT())
7202     OpFlag = X86II::MO_GOTOFF;
7203   else if (Subtarget->isPICStyleStubPIC())
7204     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7205
7206   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7207                                              CP->getAlignment(),
7208                                              CP->getOffset(), OpFlag);
7209   DebugLoc DL = CP->getDebugLoc();
7210   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7211   // With PIC, the address is actually $g + Offset.
7212   if (OpFlag) {
7213     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7214                          DAG.getNode(X86ISD::GlobalBaseReg,
7215                                      DebugLoc(), getPointerTy()),
7216                          Result);
7217   }
7218
7219   return Result;
7220 }
7221
7222 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7223   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7224
7225   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7226   // global base reg.
7227   unsigned char OpFlag = 0;
7228   unsigned WrapperKind = X86ISD::Wrapper;
7229   CodeModel::Model M = getTargetMachine().getCodeModel();
7230
7231   if (Subtarget->isPICStyleRIPRel() &&
7232       (M == CodeModel::Small || M == CodeModel::Kernel))
7233     WrapperKind = X86ISD::WrapperRIP;
7234   else if (Subtarget->isPICStyleGOT())
7235     OpFlag = X86II::MO_GOTOFF;
7236   else if (Subtarget->isPICStyleStubPIC())
7237     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7238
7239   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7240                                           OpFlag);
7241   DebugLoc DL = JT->getDebugLoc();
7242   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7243
7244   // With PIC, the address is actually $g + Offset.
7245   if (OpFlag)
7246     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7247                          DAG.getNode(X86ISD::GlobalBaseReg,
7248                                      DebugLoc(), getPointerTy()),
7249                          Result);
7250
7251   return Result;
7252 }
7253
7254 SDValue
7255 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7256   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7257
7258   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7259   // global base reg.
7260   unsigned char OpFlag = 0;
7261   unsigned WrapperKind = X86ISD::Wrapper;
7262   CodeModel::Model M = getTargetMachine().getCodeModel();
7263
7264   if (Subtarget->isPICStyleRIPRel() &&
7265       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7266     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7267       OpFlag = X86II::MO_GOTPCREL;
7268     WrapperKind = X86ISD::WrapperRIP;
7269   } else if (Subtarget->isPICStyleGOT()) {
7270     OpFlag = X86II::MO_GOT;
7271   } else if (Subtarget->isPICStyleStubPIC()) {
7272     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7273   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7274     OpFlag = X86II::MO_DARWIN_NONLAZY;
7275   }
7276
7277   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7278
7279   DebugLoc DL = Op.getDebugLoc();
7280   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7281
7282
7283   // With PIC, the address is actually $g + Offset.
7284   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7285       !Subtarget->is64Bit()) {
7286     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7287                          DAG.getNode(X86ISD::GlobalBaseReg,
7288                                      DebugLoc(), getPointerTy()),
7289                          Result);
7290   }
7291
7292   // For symbols that require a load from a stub to get the address, emit the
7293   // load.
7294   if (isGlobalStubReference(OpFlag))
7295     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7296                          MachinePointerInfo::getGOT(), false, false, false, 0);
7297
7298   return Result;
7299 }
7300
7301 SDValue
7302 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7303   // Create the TargetBlockAddressAddress node.
7304   unsigned char OpFlags =
7305     Subtarget->ClassifyBlockAddressReference();
7306   CodeModel::Model M = getTargetMachine().getCodeModel();
7307   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7308   DebugLoc dl = Op.getDebugLoc();
7309   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7310                                        /*isTarget=*/true, OpFlags);
7311
7312   if (Subtarget->isPICStyleRIPRel() &&
7313       (M == CodeModel::Small || M == CodeModel::Kernel))
7314     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7315   else
7316     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7317
7318   // With PIC, the address is actually $g + Offset.
7319   if (isGlobalRelativeToPICBase(OpFlags)) {
7320     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7321                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7322                          Result);
7323   }
7324
7325   return Result;
7326 }
7327
7328 SDValue
7329 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7330                                       int64_t Offset,
7331                                       SelectionDAG &DAG) const {
7332   // Create the TargetGlobalAddress node, folding in the constant
7333   // offset if it is legal.
7334   unsigned char OpFlags =
7335     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7336   CodeModel::Model M = getTargetMachine().getCodeModel();
7337   SDValue Result;
7338   if (OpFlags == X86II::MO_NO_FLAG &&
7339       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7340     // A direct static reference to a global.
7341     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7342     Offset = 0;
7343   } else {
7344     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7345   }
7346
7347   if (Subtarget->isPICStyleRIPRel() &&
7348       (M == CodeModel::Small || M == CodeModel::Kernel))
7349     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7350   else
7351     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7352
7353   // With PIC, the address is actually $g + Offset.
7354   if (isGlobalRelativeToPICBase(OpFlags)) {
7355     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7356                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7357                          Result);
7358   }
7359
7360   // For globals that require a load from a stub to get the address, emit the
7361   // load.
7362   if (isGlobalStubReference(OpFlags))
7363     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7364                          MachinePointerInfo::getGOT(), false, false, false, 0);
7365
7366   // If there was a non-zero offset that we didn't fold, create an explicit
7367   // addition for it.
7368   if (Offset != 0)
7369     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7370                          DAG.getConstant(Offset, getPointerTy()));
7371
7372   return Result;
7373 }
7374
7375 SDValue
7376 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7377   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7378   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7379   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7380 }
7381
7382 static SDValue
7383 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7384            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7385            unsigned char OperandFlags, bool LocalDynamic = false) {
7386   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7387   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7388   DebugLoc dl = GA->getDebugLoc();
7389   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7390                                            GA->getValueType(0),
7391                                            GA->getOffset(),
7392                                            OperandFlags);
7393
7394   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7395                                            : X86ISD::TLSADDR;
7396
7397   if (InFlag) {
7398     SDValue Ops[] = { Chain,  TGA, *InFlag };
7399     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7400   } else {
7401     SDValue Ops[]  = { Chain, TGA };
7402     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7403   }
7404
7405   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7406   MFI->setAdjustsStack(true);
7407
7408   SDValue Flag = Chain.getValue(1);
7409   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7410 }
7411
7412 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7413 static SDValue
7414 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7415                                 const EVT PtrVT) {
7416   SDValue InFlag;
7417   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7418   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7419                                      DAG.getNode(X86ISD::GlobalBaseReg,
7420                                                  DebugLoc(), PtrVT), InFlag);
7421   InFlag = Chain.getValue(1);
7422
7423   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7424 }
7425
7426 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7427 static SDValue
7428 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7429                                 const EVT PtrVT) {
7430   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7431                     X86::RAX, X86II::MO_TLSGD);
7432 }
7433
7434 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7435                                            SelectionDAG &DAG,
7436                                            const EVT PtrVT,
7437                                            bool is64Bit) {
7438   DebugLoc dl = GA->getDebugLoc();
7439
7440   // Get the start address of the TLS block for this module.
7441   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7442       .getInfo<X86MachineFunctionInfo>();
7443   MFI->incNumLocalDynamicTLSAccesses();
7444
7445   SDValue Base;
7446   if (is64Bit) {
7447     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7448                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7449   } else {
7450     SDValue InFlag;
7451     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7452         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7453     InFlag = Chain.getValue(1);
7454     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7455                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7456   }
7457
7458   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7459   // of Base.
7460
7461   // Build x@dtpoff.
7462   unsigned char OperandFlags = X86II::MO_DTPOFF;
7463   unsigned WrapperKind = X86ISD::Wrapper;
7464   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7465                                            GA->getValueType(0),
7466                                            GA->getOffset(), OperandFlags);
7467   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7468
7469   // Add x@dtpoff with the base.
7470   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7471 }
7472
7473 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7474 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7475                                    const EVT PtrVT, TLSModel::Model model,
7476                                    bool is64Bit, bool isPIC) {
7477   DebugLoc dl = GA->getDebugLoc();
7478
7479   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7480   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7481                                                          is64Bit ? 257 : 256));
7482
7483   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7484                                       DAG.getIntPtrConstant(0),
7485                                       MachinePointerInfo(Ptr),
7486                                       false, false, false, 0);
7487
7488   unsigned char OperandFlags = 0;
7489   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7490   // initialexec.
7491   unsigned WrapperKind = X86ISD::Wrapper;
7492   if (model == TLSModel::LocalExec) {
7493     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7494   } else if (model == TLSModel::InitialExec) {
7495     if (is64Bit) {
7496       OperandFlags = X86II::MO_GOTTPOFF;
7497       WrapperKind = X86ISD::WrapperRIP;
7498     } else {
7499       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7500     }
7501   } else {
7502     llvm_unreachable("Unexpected model");
7503   }
7504
7505   // emit "addl x@ntpoff,%eax" (local exec)
7506   // or "addl x@indntpoff,%eax" (initial exec)
7507   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7508   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7509                                            GA->getValueType(0),
7510                                            GA->getOffset(), OperandFlags);
7511   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7512
7513   if (model == TLSModel::InitialExec) {
7514     if (isPIC && !is64Bit) {
7515       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7516                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7517                            Offset);
7518     }
7519
7520     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7521                          MachinePointerInfo::getGOT(), false, false, false,
7522                          0);
7523   }
7524
7525   // The address of the thread local variable is the add of the thread
7526   // pointer with the offset of the variable.
7527   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7528 }
7529
7530 SDValue
7531 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7532
7533   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7534   const GlobalValue *GV = GA->getGlobal();
7535
7536   if (Subtarget->isTargetELF()) {
7537     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7538
7539     switch (model) {
7540       case TLSModel::GeneralDynamic:
7541         if (Subtarget->is64Bit())
7542           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7543         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7544       case TLSModel::LocalDynamic:
7545         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7546                                            Subtarget->is64Bit());
7547       case TLSModel::InitialExec:
7548       case TLSModel::LocalExec:
7549         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7550                                    Subtarget->is64Bit(),
7551                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7552     }
7553     llvm_unreachable("Unknown TLS model.");
7554   }
7555
7556   if (Subtarget->isTargetDarwin()) {
7557     // Darwin only has one model of TLS.  Lower to that.
7558     unsigned char OpFlag = 0;
7559     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7560                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7561
7562     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7563     // global base reg.
7564     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7565                   !Subtarget->is64Bit();
7566     if (PIC32)
7567       OpFlag = X86II::MO_TLVP_PIC_BASE;
7568     else
7569       OpFlag = X86II::MO_TLVP;
7570     DebugLoc DL = Op.getDebugLoc();
7571     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7572                                                 GA->getValueType(0),
7573                                                 GA->getOffset(), OpFlag);
7574     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7575
7576     // With PIC32, the address is actually $g + Offset.
7577     if (PIC32)
7578       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7579                            DAG.getNode(X86ISD::GlobalBaseReg,
7580                                        DebugLoc(), getPointerTy()),
7581                            Offset);
7582
7583     // Lowering the machine isd will make sure everything is in the right
7584     // location.
7585     SDValue Chain = DAG.getEntryNode();
7586     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7587     SDValue Args[] = { Chain, Offset };
7588     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7589
7590     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7591     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7592     MFI->setAdjustsStack(true);
7593
7594     // And our return value (tls address) is in the standard call return value
7595     // location.
7596     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7597     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7598                               Chain.getValue(1));
7599   }
7600
7601   if (Subtarget->isTargetWindows()) {
7602     // Just use the implicit TLS architecture
7603     // Need to generate someting similar to:
7604     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7605     //                                  ; from TEB
7606     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7607     //   mov     rcx, qword [rdx+rcx*8]
7608     //   mov     eax, .tls$:tlsvar
7609     //   [rax+rcx] contains the address
7610     // Windows 64bit: gs:0x58
7611     // Windows 32bit: fs:__tls_array
7612
7613     // If GV is an alias then use the aliasee for determining
7614     // thread-localness.
7615     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7616       GV = GA->resolveAliasedGlobal(false);
7617     DebugLoc dl = GA->getDebugLoc();
7618     SDValue Chain = DAG.getEntryNode();
7619
7620     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7621     // %gs:0x58 (64-bit).
7622     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7623                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7624                                                              256)
7625                                         : Type::getInt32PtrTy(*DAG.getContext(),
7626                                                               257));
7627
7628     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7629                                         Subtarget->is64Bit()
7630                                         ? DAG.getIntPtrConstant(0x58)
7631                                         : DAG.getExternalSymbol("_tls_array",
7632                                                                 getPointerTy()),
7633                                         MachinePointerInfo(Ptr),
7634                                         false, false, false, 0);
7635
7636     // Load the _tls_index variable
7637     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7638     if (Subtarget->is64Bit())
7639       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7640                            IDX, MachinePointerInfo(), MVT::i32,
7641                            false, false, 0);
7642     else
7643       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7644                         false, false, false, 0);
7645
7646     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7647                                     getPointerTy());
7648     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7649
7650     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7651     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7652                       false, false, false, 0);
7653
7654     // Get the offset of start of .tls section
7655     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7656                                              GA->getValueType(0),
7657                                              GA->getOffset(), X86II::MO_SECREL);
7658     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7659
7660     // The address of the thread local variable is the add of the thread
7661     // pointer with the offset of the variable.
7662     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7663   }
7664
7665   llvm_unreachable("TLS not implemented for this target.");
7666 }
7667
7668
7669 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7670 /// and take a 2 x i32 value to shift plus a shift amount.
7671 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7672   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7673   EVT VT = Op.getValueType();
7674   unsigned VTBits = VT.getSizeInBits();
7675   DebugLoc dl = Op.getDebugLoc();
7676   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7677   SDValue ShOpLo = Op.getOperand(0);
7678   SDValue ShOpHi = Op.getOperand(1);
7679   SDValue ShAmt  = Op.getOperand(2);
7680   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7681                                      DAG.getConstant(VTBits - 1, MVT::i8))
7682                        : DAG.getConstant(0, VT);
7683
7684   SDValue Tmp2, Tmp3;
7685   if (Op.getOpcode() == ISD::SHL_PARTS) {
7686     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7687     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7688   } else {
7689     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7690     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7691   }
7692
7693   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7694                                 DAG.getConstant(VTBits, MVT::i8));
7695   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7696                              AndNode, DAG.getConstant(0, MVT::i8));
7697
7698   SDValue Hi, Lo;
7699   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7700   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7701   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7702
7703   if (Op.getOpcode() == ISD::SHL_PARTS) {
7704     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7705     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7706   } else {
7707     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7708     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7709   }
7710
7711   SDValue Ops[2] = { Lo, Hi };
7712   return DAG.getMergeValues(Ops, 2, dl);
7713 }
7714
7715 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7716                                            SelectionDAG &DAG) const {
7717   EVT SrcVT = Op.getOperand(0).getValueType();
7718
7719   if (SrcVT.isVector())
7720     return SDValue();
7721
7722   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7723          "Unknown SINT_TO_FP to lower!");
7724
7725   // These are really Legal; return the operand so the caller accepts it as
7726   // Legal.
7727   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7728     return Op;
7729   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7730       Subtarget->is64Bit()) {
7731     return Op;
7732   }
7733
7734   DebugLoc dl = Op.getDebugLoc();
7735   unsigned Size = SrcVT.getSizeInBits()/8;
7736   MachineFunction &MF = DAG.getMachineFunction();
7737   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7738   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7739   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7740                                StackSlot,
7741                                MachinePointerInfo::getFixedStack(SSFI),
7742                                false, false, 0);
7743   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7744 }
7745
7746 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7747                                      SDValue StackSlot,
7748                                      SelectionDAG &DAG) const {
7749   // Build the FILD
7750   DebugLoc DL = Op.getDebugLoc();
7751   SDVTList Tys;
7752   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7753   if (useSSE)
7754     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7755   else
7756     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7757
7758   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7759
7760   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7761   MachineMemOperand *MMO;
7762   if (FI) {
7763     int SSFI = FI->getIndex();
7764     MMO =
7765       DAG.getMachineFunction()
7766       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7767                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7768   } else {
7769     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7770     StackSlot = StackSlot.getOperand(1);
7771   }
7772   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7773   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7774                                            X86ISD::FILD, DL,
7775                                            Tys, Ops, array_lengthof(Ops),
7776                                            SrcVT, MMO);
7777
7778   if (useSSE) {
7779     Chain = Result.getValue(1);
7780     SDValue InFlag = Result.getValue(2);
7781
7782     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7783     // shouldn't be necessary except that RFP cannot be live across
7784     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7785     MachineFunction &MF = DAG.getMachineFunction();
7786     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7787     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7788     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7789     Tys = DAG.getVTList(MVT::Other);
7790     SDValue Ops[] = {
7791       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7792     };
7793     MachineMemOperand *MMO =
7794       DAG.getMachineFunction()
7795       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7796                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7797
7798     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7799                                     Ops, array_lengthof(Ops),
7800                                     Op.getValueType(), MMO);
7801     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7802                          MachinePointerInfo::getFixedStack(SSFI),
7803                          false, false, false, 0);
7804   }
7805
7806   return Result;
7807 }
7808
7809 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7810 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7811                                                SelectionDAG &DAG) const {
7812   // This algorithm is not obvious. Here it is what we're trying to output:
7813   /*
7814      movq       %rax,  %xmm0
7815      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7816      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7817      #ifdef __SSE3__
7818        haddpd   %xmm0, %xmm0
7819      #else
7820        pshufd   $0x4e, %xmm0, %xmm1
7821        addpd    %xmm1, %xmm0
7822      #endif
7823   */
7824
7825   DebugLoc dl = Op.getDebugLoc();
7826   LLVMContext *Context = DAG.getContext();
7827
7828   // Build some magic constants.
7829   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7830   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7831   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7832
7833   SmallVector<Constant*,2> CV1;
7834   CV1.push_back(
7835         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7836   CV1.push_back(
7837         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7838   Constant *C1 = ConstantVector::get(CV1);
7839   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7840
7841   // Load the 64-bit value into an XMM register.
7842   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7843                             Op.getOperand(0));
7844   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7845                               MachinePointerInfo::getConstantPool(),
7846                               false, false, false, 16);
7847   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7848                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7849                               CLod0);
7850
7851   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7852                               MachinePointerInfo::getConstantPool(),
7853                               false, false, false, 16);
7854   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7855   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7856   SDValue Result;
7857
7858   if (Subtarget->hasSSE3()) {
7859     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7860     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7861   } else {
7862     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7863     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7864                                            S2F, 0x4E, DAG);
7865     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7866                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7867                          Sub);
7868   }
7869
7870   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7871                      DAG.getIntPtrConstant(0));
7872 }
7873
7874 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7875 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7876                                                SelectionDAG &DAG) const {
7877   DebugLoc dl = Op.getDebugLoc();
7878   // FP constant to bias correct the final result.
7879   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7880                                    MVT::f64);
7881
7882   // Load the 32-bit value into an XMM register.
7883   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7884                              Op.getOperand(0));
7885
7886   // Zero out the upper parts of the register.
7887   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7888
7889   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7890                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7891                      DAG.getIntPtrConstant(0));
7892
7893   // Or the load with the bias.
7894   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7895                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7896                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7897                                                    MVT::v2f64, Load)),
7898                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7899                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7900                                                    MVT::v2f64, Bias)));
7901   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7902                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7903                    DAG.getIntPtrConstant(0));
7904
7905   // Subtract the bias.
7906   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7907
7908   // Handle final rounding.
7909   EVT DestVT = Op.getValueType();
7910
7911   if (DestVT.bitsLT(MVT::f64))
7912     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7913                        DAG.getIntPtrConstant(0));
7914   if (DestVT.bitsGT(MVT::f64))
7915     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7916
7917   // Handle final rounding.
7918   return Sub;
7919 }
7920
7921 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7922                                            SelectionDAG &DAG) const {
7923   SDValue N0 = Op.getOperand(0);
7924   DebugLoc dl = Op.getDebugLoc();
7925
7926   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7927   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7928   // the optimization here.
7929   if (DAG.SignBitIsZero(N0))
7930     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7931
7932   EVT SrcVT = N0.getValueType();
7933   EVT DstVT = Op.getValueType();
7934   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7935     return LowerUINT_TO_FP_i64(Op, DAG);
7936   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7937     return LowerUINT_TO_FP_i32(Op, DAG);
7938   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7939     return SDValue();
7940
7941   // Make a 64-bit buffer, and use it to build an FILD.
7942   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7943   if (SrcVT == MVT::i32) {
7944     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7945     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7946                                      getPointerTy(), StackSlot, WordOff);
7947     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7948                                   StackSlot, MachinePointerInfo(),
7949                                   false, false, 0);
7950     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7951                                   OffsetSlot, MachinePointerInfo(),
7952                                   false, false, 0);
7953     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7954     return Fild;
7955   }
7956
7957   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7958   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7959                                StackSlot, MachinePointerInfo(),
7960                                false, false, 0);
7961   // For i64 source, we need to add the appropriate power of 2 if the input
7962   // was negative.  This is the same as the optimization in
7963   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7964   // we must be careful to do the computation in x87 extended precision, not
7965   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7966   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7967   MachineMemOperand *MMO =
7968     DAG.getMachineFunction()
7969     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7970                           MachineMemOperand::MOLoad, 8, 8);
7971
7972   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7973   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7974   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7975                                          MVT::i64, MMO);
7976
7977   APInt FF(32, 0x5F800000ULL);
7978
7979   // Check whether the sign bit is set.
7980   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7981                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7982                                  ISD::SETLT);
7983
7984   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7985   SDValue FudgePtr = DAG.getConstantPool(
7986                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7987                                          getPointerTy());
7988
7989   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7990   SDValue Zero = DAG.getIntPtrConstant(0);
7991   SDValue Four = DAG.getIntPtrConstant(4);
7992   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7993                                Zero, Four);
7994   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7995
7996   // Load the value out, extending it from f32 to f80.
7997   // FIXME: Avoid the extend by constructing the right constant pool?
7998   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7999                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8000                                  MVT::f32, false, false, 4);
8001   // Extend everything to 80 bits to force it to be done on x87.
8002   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8003   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8004 }
8005
8006 std::pair<SDValue,SDValue> X86TargetLowering::
8007 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8008   DebugLoc DL = Op.getDebugLoc();
8009
8010   EVT DstTy = Op.getValueType();
8011
8012   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8013     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8014     DstTy = MVT::i64;
8015   }
8016
8017   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8018          DstTy.getSimpleVT() >= MVT::i16 &&
8019          "Unknown FP_TO_INT to lower!");
8020
8021   // These are really Legal.
8022   if (DstTy == MVT::i32 &&
8023       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8024     return std::make_pair(SDValue(), SDValue());
8025   if (Subtarget->is64Bit() &&
8026       DstTy == MVT::i64 &&
8027       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8028     return std::make_pair(SDValue(), SDValue());
8029
8030   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8031   // stack slot, or into the FTOL runtime function.
8032   MachineFunction &MF = DAG.getMachineFunction();
8033   unsigned MemSize = DstTy.getSizeInBits()/8;
8034   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8035   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8036
8037   unsigned Opc;
8038   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8039     Opc = X86ISD::WIN_FTOL;
8040   else
8041     switch (DstTy.getSimpleVT().SimpleTy) {
8042     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8043     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8044     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8045     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8046     }
8047
8048   SDValue Chain = DAG.getEntryNode();
8049   SDValue Value = Op.getOperand(0);
8050   EVT TheVT = Op.getOperand(0).getValueType();
8051   // FIXME This causes a redundant load/store if the SSE-class value is already
8052   // in memory, such as if it is on the callstack.
8053   if (isScalarFPTypeInSSEReg(TheVT)) {
8054     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8055     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8056                          MachinePointerInfo::getFixedStack(SSFI),
8057                          false, false, 0);
8058     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8059     SDValue Ops[] = {
8060       Chain, StackSlot, DAG.getValueType(TheVT)
8061     };
8062
8063     MachineMemOperand *MMO =
8064       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8065                               MachineMemOperand::MOLoad, MemSize, MemSize);
8066     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8067                                     DstTy, MMO);
8068     Chain = Value.getValue(1);
8069     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8070     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8071   }
8072
8073   MachineMemOperand *MMO =
8074     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8075                             MachineMemOperand::MOStore, MemSize, MemSize);
8076
8077   if (Opc != X86ISD::WIN_FTOL) {
8078     // Build the FP_TO_INT*_IN_MEM
8079     SDValue Ops[] = { Chain, Value, StackSlot };
8080     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8081                                            Ops, 3, DstTy, MMO);
8082     return std::make_pair(FIST, StackSlot);
8083   } else {
8084     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8085       DAG.getVTList(MVT::Other, MVT::Glue),
8086       Chain, Value);
8087     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8088       MVT::i32, ftol.getValue(1));
8089     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8090       MVT::i32, eax.getValue(2));
8091     SDValue Ops[] = { eax, edx };
8092     SDValue pair = IsReplace
8093       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8094       : DAG.getMergeValues(Ops, 2, DL);
8095     return std::make_pair(pair, SDValue());
8096   }
8097 }
8098
8099 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8100                                            SelectionDAG &DAG) const {
8101   if (Op.getValueType().isVector())
8102     return SDValue();
8103
8104   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8105     /*IsSigned=*/ true, /*IsReplace=*/ false);
8106   SDValue FIST = Vals.first, StackSlot = Vals.second;
8107   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8108   if (FIST.getNode() == 0) return Op;
8109
8110   if (StackSlot.getNode())
8111     // Load the result.
8112     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8113                        FIST, StackSlot, MachinePointerInfo(),
8114                        false, false, false, 0);
8115
8116   // The node is the result.
8117   return FIST;
8118 }
8119
8120 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8121                                            SelectionDAG &DAG) const {
8122   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8123     /*IsSigned=*/ false, /*IsReplace=*/ false);
8124   SDValue FIST = Vals.first, StackSlot = Vals.second;
8125   assert(FIST.getNode() && "Unexpected failure");
8126
8127   if (StackSlot.getNode())
8128     // Load the result.
8129     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8130                        FIST, StackSlot, MachinePointerInfo(),
8131                        false, false, false, 0);
8132
8133   // The node is the result.
8134   return FIST;
8135 }
8136
8137 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8138                                      SelectionDAG &DAG) const {
8139   LLVMContext *Context = DAG.getContext();
8140   DebugLoc dl = Op.getDebugLoc();
8141   EVT VT = Op.getValueType();
8142   EVT EltVT = VT;
8143   if (VT.isVector())
8144     EltVT = VT.getVectorElementType();
8145   Constant *C;
8146   if (EltVT == MVT::f64) {
8147     C = ConstantVector::getSplat(2,
8148                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8149   } else {
8150     C = ConstantVector::getSplat(4,
8151                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8152   }
8153   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8154   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8155                              MachinePointerInfo::getConstantPool(),
8156                              false, false, false, 16);
8157   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8158 }
8159
8160 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8161   LLVMContext *Context = DAG.getContext();
8162   DebugLoc dl = Op.getDebugLoc();
8163   EVT VT = Op.getValueType();
8164   EVT EltVT = VT;
8165   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8166   if (VT.isVector()) {
8167     EltVT = VT.getVectorElementType();
8168     NumElts = VT.getVectorNumElements();
8169   }
8170   Constant *C;
8171   if (EltVT == MVT::f64)
8172     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8173   else
8174     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8175   C = ConstantVector::getSplat(NumElts, C);
8176   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8177   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8178                              MachinePointerInfo::getConstantPool(),
8179                              false, false, false, 16);
8180   if (VT.isVector()) {
8181     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8182     return DAG.getNode(ISD::BITCAST, dl, VT,
8183                        DAG.getNode(ISD::XOR, dl, XORVT,
8184                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8185                                                Op.getOperand(0)),
8186                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8187   }
8188
8189   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8190 }
8191
8192 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8193   LLVMContext *Context = DAG.getContext();
8194   SDValue Op0 = Op.getOperand(0);
8195   SDValue Op1 = Op.getOperand(1);
8196   DebugLoc dl = Op.getDebugLoc();
8197   EVT VT = Op.getValueType();
8198   EVT SrcVT = Op1.getValueType();
8199
8200   // If second operand is smaller, extend it first.
8201   if (SrcVT.bitsLT(VT)) {
8202     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8203     SrcVT = VT;
8204   }
8205   // And if it is bigger, shrink it first.
8206   if (SrcVT.bitsGT(VT)) {
8207     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8208     SrcVT = VT;
8209   }
8210
8211   // At this point the operands and the result should have the same
8212   // type, and that won't be f80 since that is not custom lowered.
8213
8214   // First get the sign bit of second operand.
8215   SmallVector<Constant*,4> CV;
8216   if (SrcVT == MVT::f64) {
8217     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8218     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8219   } else {
8220     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8221     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8222     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8223     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8224   }
8225   Constant *C = ConstantVector::get(CV);
8226   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8227   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8228                               MachinePointerInfo::getConstantPool(),
8229                               false, false, false, 16);
8230   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8231
8232   // Shift sign bit right or left if the two operands have different types.
8233   if (SrcVT.bitsGT(VT)) {
8234     // Op0 is MVT::f32, Op1 is MVT::f64.
8235     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8236     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8237                           DAG.getConstant(32, MVT::i32));
8238     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8239     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8240                           DAG.getIntPtrConstant(0));
8241   }
8242
8243   // Clear first operand sign bit.
8244   CV.clear();
8245   if (VT == MVT::f64) {
8246     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8247     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8248   } else {
8249     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8250     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8251     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8252     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8253   }
8254   C = ConstantVector::get(CV);
8255   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8256   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8257                               MachinePointerInfo::getConstantPool(),
8258                               false, false, false, 16);
8259   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8260
8261   // Or the value with the sign bit.
8262   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8263 }
8264
8265 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8266   SDValue N0 = Op.getOperand(0);
8267   DebugLoc dl = Op.getDebugLoc();
8268   EVT VT = Op.getValueType();
8269
8270   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8271   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8272                                   DAG.getConstant(1, VT));
8273   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8274 }
8275
8276 /// Emit nodes that will be selected as "test Op0,Op0", or something
8277 /// equivalent.
8278 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8279                                     SelectionDAG &DAG) const {
8280   DebugLoc dl = Op.getDebugLoc();
8281
8282   // CF and OF aren't always set the way we want. Determine which
8283   // of these we need.
8284   bool NeedCF = false;
8285   bool NeedOF = false;
8286   switch (X86CC) {
8287   default: break;
8288   case X86::COND_A: case X86::COND_AE:
8289   case X86::COND_B: case X86::COND_BE:
8290     NeedCF = true;
8291     break;
8292   case X86::COND_G: case X86::COND_GE:
8293   case X86::COND_L: case X86::COND_LE:
8294   case X86::COND_O: case X86::COND_NO:
8295     NeedOF = true;
8296     break;
8297   }
8298
8299   // See if we can use the EFLAGS value from the operand instead of
8300   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8301   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8302   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8303     // Emit a CMP with 0, which is the TEST pattern.
8304     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8305                        DAG.getConstant(0, Op.getValueType()));
8306
8307   unsigned Opcode = 0;
8308   unsigned NumOperands = 0;
8309
8310   // Truncate operations may prevent the merge of the SETCC instruction
8311   // and the arithmetic intruction before it. Attempt to truncate the operands
8312   // of the arithmetic instruction and use a reduced bit-width instruction.
8313   bool NeedTruncation = false;
8314   SDValue ArithOp = Op;
8315   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8316     SDValue Arith = Op->getOperand(0);
8317     // Both the trunc and the arithmetic op need to have one user each.
8318     if (Arith->hasOneUse())
8319       switch (Arith.getOpcode()) {
8320         default: break;
8321         case ISD::ADD:
8322         case ISD::SUB:
8323         case ISD::AND:
8324         case ISD::OR:
8325         case ISD::XOR: {
8326           NeedTruncation = true;
8327           ArithOp = Arith;
8328         }
8329       }
8330   }
8331
8332   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8333   // which may be the result of a CAST.  We use the variable 'Op', which is the
8334   // non-casted variable when we check for possible users.
8335   switch (ArithOp.getOpcode()) {
8336   case ISD::ADD:
8337     // Due to an isel shortcoming, be conservative if this add is likely to be
8338     // selected as part of a load-modify-store instruction. When the root node
8339     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8340     // uses of other nodes in the match, such as the ADD in this case. This
8341     // leads to the ADD being left around and reselected, with the result being
8342     // two adds in the output.  Alas, even if none our users are stores, that
8343     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8344     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8345     // climbing the DAG back to the root, and it doesn't seem to be worth the
8346     // effort.
8347     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8348          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8349       if (UI->getOpcode() != ISD::CopyToReg &&
8350           UI->getOpcode() != ISD::SETCC &&
8351           UI->getOpcode() != ISD::STORE)
8352         goto default_case;
8353
8354     if (ConstantSDNode *C =
8355         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8356       // An add of one will be selected as an INC.
8357       if (C->getAPIntValue() == 1) {
8358         Opcode = X86ISD::INC;
8359         NumOperands = 1;
8360         break;
8361       }
8362
8363       // An add of negative one (subtract of one) will be selected as a DEC.
8364       if (C->getAPIntValue().isAllOnesValue()) {
8365         Opcode = X86ISD::DEC;
8366         NumOperands = 1;
8367         break;
8368       }
8369     }
8370
8371     // Otherwise use a regular EFLAGS-setting add.
8372     Opcode = X86ISD::ADD;
8373     NumOperands = 2;
8374     break;
8375   case ISD::AND: {
8376     // If the primary and result isn't used, don't bother using X86ISD::AND,
8377     // because a TEST instruction will be better.
8378     bool NonFlagUse = false;
8379     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8380            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8381       SDNode *User = *UI;
8382       unsigned UOpNo = UI.getOperandNo();
8383       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8384         // Look pass truncate.
8385         UOpNo = User->use_begin().getOperandNo();
8386         User = *User->use_begin();
8387       }
8388
8389       if (User->getOpcode() != ISD::BRCOND &&
8390           User->getOpcode() != ISD::SETCC &&
8391           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8392         NonFlagUse = true;
8393         break;
8394       }
8395     }
8396
8397     if (!NonFlagUse)
8398       break;
8399   }
8400     // FALL THROUGH
8401   case ISD::SUB:
8402   case ISD::OR:
8403   case ISD::XOR:
8404     // Due to the ISEL shortcoming noted above, be conservative if this op is
8405     // likely to be selected as part of a load-modify-store instruction.
8406     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8407            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8408       if (UI->getOpcode() == ISD::STORE)
8409         goto default_case;
8410
8411     // Otherwise use a regular EFLAGS-setting instruction.
8412     switch (ArithOp.getOpcode()) {
8413     default: llvm_unreachable("unexpected operator!");
8414     case ISD::SUB: Opcode = X86ISD::SUB; break;
8415     case ISD::OR:  Opcode = X86ISD::OR;  break;
8416     case ISD::XOR: Opcode = X86ISD::XOR; break;
8417     case ISD::AND: Opcode = X86ISD::AND; break;
8418     }
8419
8420     NumOperands = 2;
8421     break;
8422   case X86ISD::ADD:
8423   case X86ISD::SUB:
8424   case X86ISD::INC:
8425   case X86ISD::DEC:
8426   case X86ISD::OR:
8427   case X86ISD::XOR:
8428   case X86ISD::AND:
8429     return SDValue(Op.getNode(), 1);
8430   default:
8431   default_case:
8432     break;
8433   }
8434
8435   // If we found that truncation is beneficial, perform the truncation and
8436   // update 'Op'.
8437   if (NeedTruncation) {
8438     EVT VT = Op.getValueType();
8439     SDValue WideVal = Op->getOperand(0);
8440     EVT WideVT = WideVal.getValueType();
8441     unsigned ConvertedOp = 0;
8442     // Use a target machine opcode to prevent further DAGCombine
8443     // optimizations that may separate the arithmetic operations
8444     // from the setcc node.
8445     switch (WideVal.getOpcode()) {
8446       default: break;
8447       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8448       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8449       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8450       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8451       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8452     }
8453
8454     if (ConvertedOp) {
8455       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8456       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8457         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8458         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8459         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8460       }
8461     }
8462   }
8463
8464   if (Opcode == 0)
8465     // Emit a CMP with 0, which is the TEST pattern.
8466     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8467                        DAG.getConstant(0, Op.getValueType()));
8468
8469   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8470   SmallVector<SDValue, 4> Ops;
8471   for (unsigned i = 0; i != NumOperands; ++i)
8472     Ops.push_back(Op.getOperand(i));
8473
8474   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8475   DAG.ReplaceAllUsesWith(Op, New);
8476   return SDValue(New.getNode(), 1);
8477 }
8478
8479 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8480 /// equivalent.
8481 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8482                                    SelectionDAG &DAG) const {
8483   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8484     if (C->getAPIntValue() == 0)
8485       return EmitTest(Op0, X86CC, DAG);
8486
8487   DebugLoc dl = Op0.getDebugLoc();
8488   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8489        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8490     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8491     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8492     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8493                               Op0, Op1);
8494     return SDValue(Sub.getNode(), 1);
8495   }
8496   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8497 }
8498
8499 /// Convert a comparison if required by the subtarget.
8500 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8501                                                  SelectionDAG &DAG) const {
8502   // If the subtarget does not support the FUCOMI instruction, floating-point
8503   // comparisons have to be converted.
8504   if (Subtarget->hasCMov() ||
8505       Cmp.getOpcode() != X86ISD::CMP ||
8506       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8507       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8508     return Cmp;
8509
8510   // The instruction selector will select an FUCOM instruction instead of
8511   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8512   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8513   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8514   DebugLoc dl = Cmp.getDebugLoc();
8515   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8516   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8517   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8518                             DAG.getConstant(8, MVT::i8));
8519   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8520   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8521 }
8522
8523 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8524 /// if it's possible.
8525 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8526                                      DebugLoc dl, SelectionDAG &DAG) const {
8527   SDValue Op0 = And.getOperand(0);
8528   SDValue Op1 = And.getOperand(1);
8529   if (Op0.getOpcode() == ISD::TRUNCATE)
8530     Op0 = Op0.getOperand(0);
8531   if (Op1.getOpcode() == ISD::TRUNCATE)
8532     Op1 = Op1.getOperand(0);
8533
8534   SDValue LHS, RHS;
8535   if (Op1.getOpcode() == ISD::SHL)
8536     std::swap(Op0, Op1);
8537   if (Op0.getOpcode() == ISD::SHL) {
8538     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8539       if (And00C->getZExtValue() == 1) {
8540         // If we looked past a truncate, check that it's only truncating away
8541         // known zeros.
8542         unsigned BitWidth = Op0.getValueSizeInBits();
8543         unsigned AndBitWidth = And.getValueSizeInBits();
8544         if (BitWidth > AndBitWidth) {
8545           APInt Zeros, Ones;
8546           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8547           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8548             return SDValue();
8549         }
8550         LHS = Op1;
8551         RHS = Op0.getOperand(1);
8552       }
8553   } else if (Op1.getOpcode() == ISD::Constant) {
8554     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8555     uint64_t AndRHSVal = AndRHS->getZExtValue();
8556     SDValue AndLHS = Op0;
8557
8558     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8559       LHS = AndLHS.getOperand(0);
8560       RHS = AndLHS.getOperand(1);
8561     }
8562
8563     // Use BT if the immediate can't be encoded in a TEST instruction.
8564     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8565       LHS = AndLHS;
8566       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8567     }
8568   }
8569
8570   if (LHS.getNode()) {
8571     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8572     // instruction.  Since the shift amount is in-range-or-undefined, we know
8573     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8574     // the encoding for the i16 version is larger than the i32 version.
8575     // Also promote i16 to i32 for performance / code size reason.
8576     if (LHS.getValueType() == MVT::i8 ||
8577         LHS.getValueType() == MVT::i16)
8578       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8579
8580     // If the operand types disagree, extend the shift amount to match.  Since
8581     // BT ignores high bits (like shifts) we can use anyextend.
8582     if (LHS.getValueType() != RHS.getValueType())
8583       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8584
8585     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8586     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8587     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8588                        DAG.getConstant(Cond, MVT::i8), BT);
8589   }
8590
8591   return SDValue();
8592 }
8593
8594 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8595
8596   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8597
8598   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8599   SDValue Op0 = Op.getOperand(0);
8600   SDValue Op1 = Op.getOperand(1);
8601   DebugLoc dl = Op.getDebugLoc();
8602   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8603
8604   // Optimize to BT if possible.
8605   // Lower (X & (1 << N)) == 0 to BT(X, N).
8606   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8607   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8608   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8609       Op1.getOpcode() == ISD::Constant &&
8610       cast<ConstantSDNode>(Op1)->isNullValue() &&
8611       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8612     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8613     if (NewSetCC.getNode())
8614       return NewSetCC;
8615   }
8616
8617   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8618   // these.
8619   if (Op1.getOpcode() == ISD::Constant &&
8620       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8621        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8622       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8623
8624     // If the input is a setcc, then reuse the input setcc or use a new one with
8625     // the inverted condition.
8626     if (Op0.getOpcode() == X86ISD::SETCC) {
8627       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8628       bool Invert = (CC == ISD::SETNE) ^
8629         cast<ConstantSDNode>(Op1)->isNullValue();
8630       if (!Invert) return Op0;
8631
8632       CCode = X86::GetOppositeBranchCondition(CCode);
8633       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8634                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8635     }
8636   }
8637
8638   bool isFP = Op1.getValueType().isFloatingPoint();
8639   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8640   if (X86CC == X86::COND_INVALID)
8641     return SDValue();
8642
8643   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8644   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8645   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8646                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8647 }
8648
8649 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8650 // ones, and then concatenate the result back.
8651 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8652   EVT VT = Op.getValueType();
8653
8654   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8655          "Unsupported value type for operation");
8656
8657   unsigned NumElems = VT.getVectorNumElements();
8658   DebugLoc dl = Op.getDebugLoc();
8659   SDValue CC = Op.getOperand(2);
8660
8661   // Extract the LHS vectors
8662   SDValue LHS = Op.getOperand(0);
8663   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8664   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8665
8666   // Extract the RHS vectors
8667   SDValue RHS = Op.getOperand(1);
8668   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8669   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8670
8671   // Issue the operation on the smaller types and concatenate the result back
8672   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8673   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8674   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8675                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8676                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8677 }
8678
8679
8680 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8681   SDValue Cond;
8682   SDValue Op0 = Op.getOperand(0);
8683   SDValue Op1 = Op.getOperand(1);
8684   SDValue CC = Op.getOperand(2);
8685   EVT VT = Op.getValueType();
8686   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8687   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8688   DebugLoc dl = Op.getDebugLoc();
8689
8690   if (isFP) {
8691 #ifndef NDEBUG
8692     EVT EltVT = Op0.getValueType().getVectorElementType();
8693     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8694 #endif
8695
8696     unsigned SSECC;
8697     bool Swap = false;
8698
8699     // SSE Condition code mapping:
8700     //  0 - EQ
8701     //  1 - LT
8702     //  2 - LE
8703     //  3 - UNORD
8704     //  4 - NEQ
8705     //  5 - NLT
8706     //  6 - NLE
8707     //  7 - ORD
8708     switch (SetCCOpcode) {
8709     default: llvm_unreachable("Unexpected SETCC condition");
8710     case ISD::SETOEQ:
8711     case ISD::SETEQ:  SSECC = 0; break;
8712     case ISD::SETOGT:
8713     case ISD::SETGT: Swap = true; // Fallthrough
8714     case ISD::SETLT:
8715     case ISD::SETOLT: SSECC = 1; break;
8716     case ISD::SETOGE:
8717     case ISD::SETGE: Swap = true; // Fallthrough
8718     case ISD::SETLE:
8719     case ISD::SETOLE: SSECC = 2; break;
8720     case ISD::SETUO:  SSECC = 3; break;
8721     case ISD::SETUNE:
8722     case ISD::SETNE:  SSECC = 4; break;
8723     case ISD::SETULE: Swap = true; // Fallthrough
8724     case ISD::SETUGE: SSECC = 5; break;
8725     case ISD::SETULT: Swap = true; // Fallthrough
8726     case ISD::SETUGT: SSECC = 6; break;
8727     case ISD::SETO:   SSECC = 7; break;
8728     case ISD::SETUEQ:
8729     case ISD::SETONE: SSECC = 8; break;
8730     }
8731     if (Swap)
8732       std::swap(Op0, Op1);
8733
8734     // In the two special cases we can't handle, emit two comparisons.
8735     if (SSECC == 8) {
8736       unsigned CC0, CC1;
8737       unsigned CombineOpc;
8738       if (SetCCOpcode == ISD::SETUEQ) {
8739         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8740       } else {
8741         assert(SetCCOpcode == ISD::SETONE);
8742         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8743       }
8744
8745       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8746                                  DAG.getConstant(CC0, MVT::i8));
8747       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8748                                  DAG.getConstant(CC1, MVT::i8));
8749       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8750     }
8751     // Handle all other FP comparisons here.
8752     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8753                        DAG.getConstant(SSECC, MVT::i8));
8754   }
8755
8756   // Break 256-bit integer vector compare into smaller ones.
8757   if (VT.is256BitVector() && !Subtarget->hasAVX2())
8758     return Lower256IntVSETCC(Op, DAG);
8759
8760   // We are handling one of the integer comparisons here.  Since SSE only has
8761   // GT and EQ comparisons for integer, swapping operands and multiple
8762   // operations may be required for some comparisons.
8763   unsigned Opc;
8764   bool Swap = false, Invert = false, FlipSigns = false;
8765
8766   switch (SetCCOpcode) {
8767   default: llvm_unreachable("Unexpected SETCC condition");
8768   case ISD::SETNE:  Invert = true;
8769   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8770   case ISD::SETLT:  Swap = true;
8771   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8772   case ISD::SETGE:  Swap = true;
8773   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8774   case ISD::SETULT: Swap = true;
8775   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8776   case ISD::SETUGE: Swap = true;
8777   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8778   }
8779   if (Swap)
8780     std::swap(Op0, Op1);
8781
8782   // Check that the operation in question is available (most are plain SSE2,
8783   // but PCMPGTQ and PCMPEQQ have different requirements).
8784   if (VT == MVT::v2i64) {
8785     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8786       return SDValue();
8787     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8788       return SDValue();
8789   }
8790
8791   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8792   // bits of the inputs before performing those operations.
8793   if (FlipSigns) {
8794     EVT EltVT = VT.getVectorElementType();
8795     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8796                                       EltVT);
8797     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8798     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8799                                     SignBits.size());
8800     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8801     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8802   }
8803
8804   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8805
8806   // If the logical-not of the result is required, perform that now.
8807   if (Invert)
8808     Result = DAG.getNOT(dl, Result, VT);
8809
8810   return Result;
8811 }
8812
8813 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8814 static bool isX86LogicalCmp(SDValue Op) {
8815   unsigned Opc = Op.getNode()->getOpcode();
8816   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8817       Opc == X86ISD::SAHF)
8818     return true;
8819   if (Op.getResNo() == 1 &&
8820       (Opc == X86ISD::ADD ||
8821        Opc == X86ISD::SUB ||
8822        Opc == X86ISD::ADC ||
8823        Opc == X86ISD::SBB ||
8824        Opc == X86ISD::SMUL ||
8825        Opc == X86ISD::UMUL ||
8826        Opc == X86ISD::INC ||
8827        Opc == X86ISD::DEC ||
8828        Opc == X86ISD::OR ||
8829        Opc == X86ISD::XOR ||
8830        Opc == X86ISD::AND))
8831     return true;
8832
8833   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8834     return true;
8835
8836   return false;
8837 }
8838
8839 static bool isZero(SDValue V) {
8840   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8841   return C && C->isNullValue();
8842 }
8843
8844 static bool isAllOnes(SDValue V) {
8845   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8846   return C && C->isAllOnesValue();
8847 }
8848
8849 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8850   if (V.getOpcode() != ISD::TRUNCATE)
8851     return false;
8852
8853   SDValue VOp0 = V.getOperand(0);
8854   unsigned InBits = VOp0.getValueSizeInBits();
8855   unsigned Bits = V.getValueSizeInBits();
8856   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8857 }
8858
8859 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8860   bool addTest = true;
8861   SDValue Cond  = Op.getOperand(0);
8862   SDValue Op1 = Op.getOperand(1);
8863   SDValue Op2 = Op.getOperand(2);
8864   DebugLoc DL = Op.getDebugLoc();
8865   SDValue CC;
8866
8867   if (Cond.getOpcode() == ISD::SETCC) {
8868     SDValue NewCond = LowerSETCC(Cond, DAG);
8869     if (NewCond.getNode())
8870       Cond = NewCond;
8871   }
8872
8873   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8874   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8875   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8876   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8877   if (Cond.getOpcode() == X86ISD::SETCC &&
8878       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8879       isZero(Cond.getOperand(1).getOperand(1))) {
8880     SDValue Cmp = Cond.getOperand(1);
8881
8882     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8883
8884     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8885         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8886       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8887
8888       SDValue CmpOp0 = Cmp.getOperand(0);
8889       // Apply further optimizations for special cases
8890       // (select (x != 0), -1, 0) -> neg & sbb
8891       // (select (x == 0), 0, -1) -> neg & sbb
8892       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8893         if (YC->isNullValue() &&
8894             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8895           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8896           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8897                                     DAG.getConstant(0, CmpOp0.getValueType()),
8898                                     CmpOp0);
8899           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8900                                     DAG.getConstant(X86::COND_B, MVT::i8),
8901                                     SDValue(Neg.getNode(), 1));
8902           return Res;
8903         }
8904
8905       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8906                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8907       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8908
8909       SDValue Res =   // Res = 0 or -1.
8910         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8911                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8912
8913       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8914         Res = DAG.getNOT(DL, Res, Res.getValueType());
8915
8916       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8917       if (N2C == 0 || !N2C->isNullValue())
8918         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8919       return Res;
8920     }
8921   }
8922
8923   // Look past (and (setcc_carry (cmp ...)), 1).
8924   if (Cond.getOpcode() == ISD::AND &&
8925       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8926     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8927     if (C && C->getAPIntValue() == 1)
8928       Cond = Cond.getOperand(0);
8929   }
8930
8931   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8932   // setting operand in place of the X86ISD::SETCC.
8933   unsigned CondOpcode = Cond.getOpcode();
8934   if (CondOpcode == X86ISD::SETCC ||
8935       CondOpcode == X86ISD::SETCC_CARRY) {
8936     CC = Cond.getOperand(0);
8937
8938     SDValue Cmp = Cond.getOperand(1);
8939     unsigned Opc = Cmp.getOpcode();
8940     EVT VT = Op.getValueType();
8941
8942     bool IllegalFPCMov = false;
8943     if (VT.isFloatingPoint() && !VT.isVector() &&
8944         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8945       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8946
8947     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8948         Opc == X86ISD::BT) { // FIXME
8949       Cond = Cmp;
8950       addTest = false;
8951     }
8952   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8953              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8954              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8955               Cond.getOperand(0).getValueType() != MVT::i8)) {
8956     SDValue LHS = Cond.getOperand(0);
8957     SDValue RHS = Cond.getOperand(1);
8958     unsigned X86Opcode;
8959     unsigned X86Cond;
8960     SDVTList VTs;
8961     switch (CondOpcode) {
8962     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8963     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8964     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8965     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8966     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8967     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8968     default: llvm_unreachable("unexpected overflowing operator");
8969     }
8970     if (CondOpcode == ISD::UMULO)
8971       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8972                           MVT::i32);
8973     else
8974       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8975
8976     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8977
8978     if (CondOpcode == ISD::UMULO)
8979       Cond = X86Op.getValue(2);
8980     else
8981       Cond = X86Op.getValue(1);
8982
8983     CC = DAG.getConstant(X86Cond, MVT::i8);
8984     addTest = false;
8985   }
8986
8987   if (addTest) {
8988     // Look pass the truncate if the high bits are known zero.
8989     if (isTruncWithZeroHighBitsInput(Cond, DAG))
8990         Cond = Cond.getOperand(0);
8991
8992     // We know the result of AND is compared against zero. Try to match
8993     // it to BT.
8994     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8995       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8996       if (NewSetCC.getNode()) {
8997         CC = NewSetCC.getOperand(0);
8998         Cond = NewSetCC.getOperand(1);
8999         addTest = false;
9000       }
9001     }
9002   }
9003
9004   if (addTest) {
9005     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9006     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9007   }
9008
9009   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9010   // a <  b ?  0 : -1 -> RES = setcc_carry
9011   // a >= b ? -1 :  0 -> RES = setcc_carry
9012   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9013   if (Cond.getOpcode() == X86ISD::SUB) {
9014     Cond = ConvertCmpIfNecessary(Cond, DAG);
9015     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9016
9017     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9018         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9019       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9020                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9021       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9022         return DAG.getNOT(DL, Res, Res.getValueType());
9023       return Res;
9024     }
9025   }
9026
9027   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9028   // condition is true.
9029   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9030   SDValue Ops[] = { Op2, Op1, CC, Cond };
9031   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9032 }
9033
9034 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9035 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9036 // from the AND / OR.
9037 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9038   Opc = Op.getOpcode();
9039   if (Opc != ISD::OR && Opc != ISD::AND)
9040     return false;
9041   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9042           Op.getOperand(0).hasOneUse() &&
9043           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9044           Op.getOperand(1).hasOneUse());
9045 }
9046
9047 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9048 // 1 and that the SETCC node has a single use.
9049 static bool isXor1OfSetCC(SDValue Op) {
9050   if (Op.getOpcode() != ISD::XOR)
9051     return false;
9052   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9053   if (N1C && N1C->getAPIntValue() == 1) {
9054     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9055       Op.getOperand(0).hasOneUse();
9056   }
9057   return false;
9058 }
9059
9060 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9061   bool addTest = true;
9062   SDValue Chain = Op.getOperand(0);
9063   SDValue Cond  = Op.getOperand(1);
9064   SDValue Dest  = Op.getOperand(2);
9065   DebugLoc dl = Op.getDebugLoc();
9066   SDValue CC;
9067   bool Inverted = false;
9068
9069   if (Cond.getOpcode() == ISD::SETCC) {
9070     // Check for setcc([su]{add,sub,mul}o == 0).
9071     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9072         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9073         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9074         Cond.getOperand(0).getResNo() == 1 &&
9075         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9076          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9077          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9078          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9079          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9080          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9081       Inverted = true;
9082       Cond = Cond.getOperand(0);
9083     } else {
9084       SDValue NewCond = LowerSETCC(Cond, DAG);
9085       if (NewCond.getNode())
9086         Cond = NewCond;
9087     }
9088   }
9089 #if 0
9090   // FIXME: LowerXALUO doesn't handle these!!
9091   else if (Cond.getOpcode() == X86ISD::ADD  ||
9092            Cond.getOpcode() == X86ISD::SUB  ||
9093            Cond.getOpcode() == X86ISD::SMUL ||
9094            Cond.getOpcode() == X86ISD::UMUL)
9095     Cond = LowerXALUO(Cond, DAG);
9096 #endif
9097
9098   // Look pass (and (setcc_carry (cmp ...)), 1).
9099   if (Cond.getOpcode() == ISD::AND &&
9100       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9101     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9102     if (C && C->getAPIntValue() == 1)
9103       Cond = Cond.getOperand(0);
9104   }
9105
9106   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9107   // setting operand in place of the X86ISD::SETCC.
9108   unsigned CondOpcode = Cond.getOpcode();
9109   if (CondOpcode == X86ISD::SETCC ||
9110       CondOpcode == X86ISD::SETCC_CARRY) {
9111     CC = Cond.getOperand(0);
9112
9113     SDValue Cmp = Cond.getOperand(1);
9114     unsigned Opc = Cmp.getOpcode();
9115     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9116     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9117       Cond = Cmp;
9118       addTest = false;
9119     } else {
9120       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9121       default: break;
9122       case X86::COND_O:
9123       case X86::COND_B:
9124         // These can only come from an arithmetic instruction with overflow,
9125         // e.g. SADDO, UADDO.
9126         Cond = Cond.getNode()->getOperand(1);
9127         addTest = false;
9128         break;
9129       }
9130     }
9131   }
9132   CondOpcode = Cond.getOpcode();
9133   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9134       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9135       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9136        Cond.getOperand(0).getValueType() != MVT::i8)) {
9137     SDValue LHS = Cond.getOperand(0);
9138     SDValue RHS = Cond.getOperand(1);
9139     unsigned X86Opcode;
9140     unsigned X86Cond;
9141     SDVTList VTs;
9142     switch (CondOpcode) {
9143     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9144     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9145     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9146     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9147     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9148     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9149     default: llvm_unreachable("unexpected overflowing operator");
9150     }
9151     if (Inverted)
9152       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9153     if (CondOpcode == ISD::UMULO)
9154       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9155                           MVT::i32);
9156     else
9157       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9158
9159     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9160
9161     if (CondOpcode == ISD::UMULO)
9162       Cond = X86Op.getValue(2);
9163     else
9164       Cond = X86Op.getValue(1);
9165
9166     CC = DAG.getConstant(X86Cond, MVT::i8);
9167     addTest = false;
9168   } else {
9169     unsigned CondOpc;
9170     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9171       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9172       if (CondOpc == ISD::OR) {
9173         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9174         // two branches instead of an explicit OR instruction with a
9175         // separate test.
9176         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9177             isX86LogicalCmp(Cmp)) {
9178           CC = Cond.getOperand(0).getOperand(0);
9179           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9180                               Chain, Dest, CC, Cmp);
9181           CC = Cond.getOperand(1).getOperand(0);
9182           Cond = Cmp;
9183           addTest = false;
9184         }
9185       } else { // ISD::AND
9186         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9187         // two branches instead of an explicit AND instruction with a
9188         // separate test. However, we only do this if this block doesn't
9189         // have a fall-through edge, because this requires an explicit
9190         // jmp when the condition is false.
9191         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9192             isX86LogicalCmp(Cmp) &&
9193             Op.getNode()->hasOneUse()) {
9194           X86::CondCode CCode =
9195             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9196           CCode = X86::GetOppositeBranchCondition(CCode);
9197           CC = DAG.getConstant(CCode, MVT::i8);
9198           SDNode *User = *Op.getNode()->use_begin();
9199           // Look for an unconditional branch following this conditional branch.
9200           // We need this because we need to reverse the successors in order
9201           // to implement FCMP_OEQ.
9202           if (User->getOpcode() == ISD::BR) {
9203             SDValue FalseBB = User->getOperand(1);
9204             SDNode *NewBR =
9205               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9206             assert(NewBR == User);
9207             (void)NewBR;
9208             Dest = FalseBB;
9209
9210             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9211                                 Chain, Dest, CC, Cmp);
9212             X86::CondCode CCode =
9213               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9214             CCode = X86::GetOppositeBranchCondition(CCode);
9215             CC = DAG.getConstant(CCode, MVT::i8);
9216             Cond = Cmp;
9217             addTest = false;
9218           }
9219         }
9220       }
9221     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9222       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9223       // It should be transformed during dag combiner except when the condition
9224       // is set by a arithmetics with overflow node.
9225       X86::CondCode CCode =
9226         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9227       CCode = X86::GetOppositeBranchCondition(CCode);
9228       CC = DAG.getConstant(CCode, MVT::i8);
9229       Cond = Cond.getOperand(0).getOperand(1);
9230       addTest = false;
9231     } else if (Cond.getOpcode() == ISD::SETCC &&
9232                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9233       // For FCMP_OEQ, we can emit
9234       // two branches instead of an explicit AND instruction with a
9235       // separate test. However, we only do this if this block doesn't
9236       // have a fall-through edge, because this requires an explicit
9237       // jmp when the condition is false.
9238       if (Op.getNode()->hasOneUse()) {
9239         SDNode *User = *Op.getNode()->use_begin();
9240         // Look for an unconditional branch following this conditional branch.
9241         // We need this because we need to reverse the successors in order
9242         // to implement FCMP_OEQ.
9243         if (User->getOpcode() == ISD::BR) {
9244           SDValue FalseBB = User->getOperand(1);
9245           SDNode *NewBR =
9246             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9247           assert(NewBR == User);
9248           (void)NewBR;
9249           Dest = FalseBB;
9250
9251           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9252                                     Cond.getOperand(0), Cond.getOperand(1));
9253           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9254           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9255           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9256                               Chain, Dest, CC, Cmp);
9257           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9258           Cond = Cmp;
9259           addTest = false;
9260         }
9261       }
9262     } else if (Cond.getOpcode() == ISD::SETCC &&
9263                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9264       // For FCMP_UNE, we can emit
9265       // two branches instead of an explicit AND instruction with a
9266       // separate test. However, we only do this if this block doesn't
9267       // have a fall-through edge, because this requires an explicit
9268       // jmp when the condition is false.
9269       if (Op.getNode()->hasOneUse()) {
9270         SDNode *User = *Op.getNode()->use_begin();
9271         // Look for an unconditional branch following this conditional branch.
9272         // We need this because we need to reverse the successors in order
9273         // to implement FCMP_UNE.
9274         if (User->getOpcode() == ISD::BR) {
9275           SDValue FalseBB = User->getOperand(1);
9276           SDNode *NewBR =
9277             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9278           assert(NewBR == User);
9279           (void)NewBR;
9280
9281           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9282                                     Cond.getOperand(0), Cond.getOperand(1));
9283           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9284           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9285           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9286                               Chain, Dest, CC, Cmp);
9287           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9288           Cond = Cmp;
9289           addTest = false;
9290           Dest = FalseBB;
9291         }
9292       }
9293     }
9294   }
9295
9296   if (addTest) {
9297     // Look pass the truncate if the high bits are known zero.
9298     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9299         Cond = Cond.getOperand(0);
9300
9301     // We know the result of AND is compared against zero. Try to match
9302     // it to BT.
9303     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9304       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9305       if (NewSetCC.getNode()) {
9306         CC = NewSetCC.getOperand(0);
9307         Cond = NewSetCC.getOperand(1);
9308         addTest = false;
9309       }
9310     }
9311   }
9312
9313   if (addTest) {
9314     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9315     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9316   }
9317   Cond = ConvertCmpIfNecessary(Cond, DAG);
9318   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9319                      Chain, Dest, CC, Cond);
9320 }
9321
9322
9323 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9324 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9325 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9326 // that the guard pages used by the OS virtual memory manager are allocated in
9327 // correct sequence.
9328 SDValue
9329 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9330                                            SelectionDAG &DAG) const {
9331   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9332           getTargetMachine().Options.EnableSegmentedStacks) &&
9333          "This should be used only on Windows targets or when segmented stacks "
9334          "are being used");
9335   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9336   DebugLoc dl = Op.getDebugLoc();
9337
9338   // Get the inputs.
9339   SDValue Chain = Op.getOperand(0);
9340   SDValue Size  = Op.getOperand(1);
9341   // FIXME: Ensure alignment here
9342
9343   bool Is64Bit = Subtarget->is64Bit();
9344   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9345
9346   if (getTargetMachine().Options.EnableSegmentedStacks) {
9347     MachineFunction &MF = DAG.getMachineFunction();
9348     MachineRegisterInfo &MRI = MF.getRegInfo();
9349
9350     if (Is64Bit) {
9351       // The 64 bit implementation of segmented stacks needs to clobber both r10
9352       // r11. This makes it impossible to use it along with nested parameters.
9353       const Function *F = MF.getFunction();
9354
9355       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9356            I != E; ++I)
9357         if (I->hasNestAttr())
9358           report_fatal_error("Cannot use segmented stacks with functions that "
9359                              "have nested arguments.");
9360     }
9361
9362     const TargetRegisterClass *AddrRegClass =
9363       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9364     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9365     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9366     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9367                                 DAG.getRegister(Vreg, SPTy));
9368     SDValue Ops1[2] = { Value, Chain };
9369     return DAG.getMergeValues(Ops1, 2, dl);
9370   } else {
9371     SDValue Flag;
9372     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9373
9374     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9375     Flag = Chain.getValue(1);
9376     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9377
9378     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9379     Flag = Chain.getValue(1);
9380
9381     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9382
9383     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9384     return DAG.getMergeValues(Ops1, 2, dl);
9385   }
9386 }
9387
9388 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9389   MachineFunction &MF = DAG.getMachineFunction();
9390   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9391
9392   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9393   DebugLoc DL = Op.getDebugLoc();
9394
9395   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9396     // vastart just stores the address of the VarArgsFrameIndex slot into the
9397     // memory location argument.
9398     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9399                                    getPointerTy());
9400     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9401                         MachinePointerInfo(SV), false, false, 0);
9402   }
9403
9404   // __va_list_tag:
9405   //   gp_offset         (0 - 6 * 8)
9406   //   fp_offset         (48 - 48 + 8 * 16)
9407   //   overflow_arg_area (point to parameters coming in memory).
9408   //   reg_save_area
9409   SmallVector<SDValue, 8> MemOps;
9410   SDValue FIN = Op.getOperand(1);
9411   // Store gp_offset
9412   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9413                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9414                                                MVT::i32),
9415                                FIN, MachinePointerInfo(SV), false, false, 0);
9416   MemOps.push_back(Store);
9417
9418   // Store fp_offset
9419   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9420                     FIN, DAG.getIntPtrConstant(4));
9421   Store = DAG.getStore(Op.getOperand(0), DL,
9422                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9423                                        MVT::i32),
9424                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9425   MemOps.push_back(Store);
9426
9427   // Store ptr to overflow_arg_area
9428   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9429                     FIN, DAG.getIntPtrConstant(4));
9430   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9431                                     getPointerTy());
9432   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9433                        MachinePointerInfo(SV, 8),
9434                        false, false, 0);
9435   MemOps.push_back(Store);
9436
9437   // Store ptr to reg_save_area.
9438   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9439                     FIN, DAG.getIntPtrConstant(8));
9440   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9441                                     getPointerTy());
9442   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9443                        MachinePointerInfo(SV, 16), false, false, 0);
9444   MemOps.push_back(Store);
9445   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9446                      &MemOps[0], MemOps.size());
9447 }
9448
9449 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9450   assert(Subtarget->is64Bit() &&
9451          "LowerVAARG only handles 64-bit va_arg!");
9452   assert((Subtarget->isTargetLinux() ||
9453           Subtarget->isTargetDarwin()) &&
9454           "Unhandled target in LowerVAARG");
9455   assert(Op.getNode()->getNumOperands() == 4);
9456   SDValue Chain = Op.getOperand(0);
9457   SDValue SrcPtr = Op.getOperand(1);
9458   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9459   unsigned Align = Op.getConstantOperandVal(3);
9460   DebugLoc dl = Op.getDebugLoc();
9461
9462   EVT ArgVT = Op.getNode()->getValueType(0);
9463   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9464   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9465   uint8_t ArgMode;
9466
9467   // Decide which area this value should be read from.
9468   // TODO: Implement the AMD64 ABI in its entirety. This simple
9469   // selection mechanism works only for the basic types.
9470   if (ArgVT == MVT::f80) {
9471     llvm_unreachable("va_arg for f80 not yet implemented");
9472   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9473     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9474   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9475     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9476   } else {
9477     llvm_unreachable("Unhandled argument type in LowerVAARG");
9478   }
9479
9480   if (ArgMode == 2) {
9481     // Sanity Check: Make sure using fp_offset makes sense.
9482     assert(!getTargetMachine().Options.UseSoftFloat &&
9483            !(DAG.getMachineFunction()
9484                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9485            Subtarget->hasSSE1());
9486   }
9487
9488   // Insert VAARG_64 node into the DAG
9489   // VAARG_64 returns two values: Variable Argument Address, Chain
9490   SmallVector<SDValue, 11> InstOps;
9491   InstOps.push_back(Chain);
9492   InstOps.push_back(SrcPtr);
9493   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9494   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9495   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9496   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9497   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9498                                           VTs, &InstOps[0], InstOps.size(),
9499                                           MVT::i64,
9500                                           MachinePointerInfo(SV),
9501                                           /*Align=*/0,
9502                                           /*Volatile=*/false,
9503                                           /*ReadMem=*/true,
9504                                           /*WriteMem=*/true);
9505   Chain = VAARG.getValue(1);
9506
9507   // Load the next argument and return it
9508   return DAG.getLoad(ArgVT, dl,
9509                      Chain,
9510                      VAARG,
9511                      MachinePointerInfo(),
9512                      false, false, false, 0);
9513 }
9514
9515 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9516   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9517   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9518   SDValue Chain = Op.getOperand(0);
9519   SDValue DstPtr = Op.getOperand(1);
9520   SDValue SrcPtr = Op.getOperand(2);
9521   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9522   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9523   DebugLoc DL = Op.getDebugLoc();
9524
9525   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9526                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9527                        false,
9528                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9529 }
9530
9531 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9532 // may or may not be a constant. Takes immediate version of shift as input.
9533 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9534                                    SDValue SrcOp, SDValue ShAmt,
9535                                    SelectionDAG &DAG) {
9536   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9537
9538   if (isa<ConstantSDNode>(ShAmt)) {
9539     // Constant may be a TargetConstant. Use a regular constant.
9540     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9541     switch (Opc) {
9542       default: llvm_unreachable("Unknown target vector shift node");
9543       case X86ISD::VSHLI:
9544       case X86ISD::VSRLI:
9545       case X86ISD::VSRAI:
9546         return DAG.getNode(Opc, dl, VT, SrcOp,
9547                            DAG.getConstant(ShiftAmt, MVT::i32));
9548     }
9549   }
9550
9551   // Change opcode to non-immediate version
9552   switch (Opc) {
9553     default: llvm_unreachable("Unknown target vector shift node");
9554     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9555     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9556     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9557   }
9558
9559   // Need to build a vector containing shift amount
9560   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9561   SDValue ShOps[4];
9562   ShOps[0] = ShAmt;
9563   ShOps[1] = DAG.getConstant(0, MVT::i32);
9564   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9565   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9566
9567   // The return type has to be a 128-bit type with the same element
9568   // type as the input type.
9569   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9570   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9571
9572   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9573   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9574 }
9575
9576 SDValue
9577 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9578   DebugLoc dl = Op.getDebugLoc();
9579   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9580   switch (IntNo) {
9581   default: return SDValue();    // Don't custom lower most intrinsics.
9582   // Comparison intrinsics.
9583   case Intrinsic::x86_sse_comieq_ss:
9584   case Intrinsic::x86_sse_comilt_ss:
9585   case Intrinsic::x86_sse_comile_ss:
9586   case Intrinsic::x86_sse_comigt_ss:
9587   case Intrinsic::x86_sse_comige_ss:
9588   case Intrinsic::x86_sse_comineq_ss:
9589   case Intrinsic::x86_sse_ucomieq_ss:
9590   case Intrinsic::x86_sse_ucomilt_ss:
9591   case Intrinsic::x86_sse_ucomile_ss:
9592   case Intrinsic::x86_sse_ucomigt_ss:
9593   case Intrinsic::x86_sse_ucomige_ss:
9594   case Intrinsic::x86_sse_ucomineq_ss:
9595   case Intrinsic::x86_sse2_comieq_sd:
9596   case Intrinsic::x86_sse2_comilt_sd:
9597   case Intrinsic::x86_sse2_comile_sd:
9598   case Intrinsic::x86_sse2_comigt_sd:
9599   case Intrinsic::x86_sse2_comige_sd:
9600   case Intrinsic::x86_sse2_comineq_sd:
9601   case Intrinsic::x86_sse2_ucomieq_sd:
9602   case Intrinsic::x86_sse2_ucomilt_sd:
9603   case Intrinsic::x86_sse2_ucomile_sd:
9604   case Intrinsic::x86_sse2_ucomigt_sd:
9605   case Intrinsic::x86_sse2_ucomige_sd:
9606   case Intrinsic::x86_sse2_ucomineq_sd: {
9607     unsigned Opc;
9608     ISD::CondCode CC;
9609     switch (IntNo) {
9610     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9611     case Intrinsic::x86_sse_comieq_ss:
9612     case Intrinsic::x86_sse2_comieq_sd:
9613       Opc = X86ISD::COMI;
9614       CC = ISD::SETEQ;
9615       break;
9616     case Intrinsic::x86_sse_comilt_ss:
9617     case Intrinsic::x86_sse2_comilt_sd:
9618       Opc = X86ISD::COMI;
9619       CC = ISD::SETLT;
9620       break;
9621     case Intrinsic::x86_sse_comile_ss:
9622     case Intrinsic::x86_sse2_comile_sd:
9623       Opc = X86ISD::COMI;
9624       CC = ISD::SETLE;
9625       break;
9626     case Intrinsic::x86_sse_comigt_ss:
9627     case Intrinsic::x86_sse2_comigt_sd:
9628       Opc = X86ISD::COMI;
9629       CC = ISD::SETGT;
9630       break;
9631     case Intrinsic::x86_sse_comige_ss:
9632     case Intrinsic::x86_sse2_comige_sd:
9633       Opc = X86ISD::COMI;
9634       CC = ISD::SETGE;
9635       break;
9636     case Intrinsic::x86_sse_comineq_ss:
9637     case Intrinsic::x86_sse2_comineq_sd:
9638       Opc = X86ISD::COMI;
9639       CC = ISD::SETNE;
9640       break;
9641     case Intrinsic::x86_sse_ucomieq_ss:
9642     case Intrinsic::x86_sse2_ucomieq_sd:
9643       Opc = X86ISD::UCOMI;
9644       CC = ISD::SETEQ;
9645       break;
9646     case Intrinsic::x86_sse_ucomilt_ss:
9647     case Intrinsic::x86_sse2_ucomilt_sd:
9648       Opc = X86ISD::UCOMI;
9649       CC = ISD::SETLT;
9650       break;
9651     case Intrinsic::x86_sse_ucomile_ss:
9652     case Intrinsic::x86_sse2_ucomile_sd:
9653       Opc = X86ISD::UCOMI;
9654       CC = ISD::SETLE;
9655       break;
9656     case Intrinsic::x86_sse_ucomigt_ss:
9657     case Intrinsic::x86_sse2_ucomigt_sd:
9658       Opc = X86ISD::UCOMI;
9659       CC = ISD::SETGT;
9660       break;
9661     case Intrinsic::x86_sse_ucomige_ss:
9662     case Intrinsic::x86_sse2_ucomige_sd:
9663       Opc = X86ISD::UCOMI;
9664       CC = ISD::SETGE;
9665       break;
9666     case Intrinsic::x86_sse_ucomineq_ss:
9667     case Intrinsic::x86_sse2_ucomineq_sd:
9668       Opc = X86ISD::UCOMI;
9669       CC = ISD::SETNE;
9670       break;
9671     }
9672
9673     SDValue LHS = Op.getOperand(1);
9674     SDValue RHS = Op.getOperand(2);
9675     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9676     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9677     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9678     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9679                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9680     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9681   }
9682
9683   // Arithmetic intrinsics.
9684   case Intrinsic::x86_sse2_pmulu_dq:
9685   case Intrinsic::x86_avx2_pmulu_dq:
9686     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9687                        Op.getOperand(1), Op.getOperand(2));
9688
9689   // SSE3/AVX horizontal add/sub intrinsics
9690   case Intrinsic::x86_sse3_hadd_ps:
9691   case Intrinsic::x86_sse3_hadd_pd:
9692   case Intrinsic::x86_avx_hadd_ps_256:
9693   case Intrinsic::x86_avx_hadd_pd_256:
9694   case Intrinsic::x86_sse3_hsub_ps:
9695   case Intrinsic::x86_sse3_hsub_pd:
9696   case Intrinsic::x86_avx_hsub_ps_256:
9697   case Intrinsic::x86_avx_hsub_pd_256:
9698   case Intrinsic::x86_ssse3_phadd_w_128:
9699   case Intrinsic::x86_ssse3_phadd_d_128:
9700   case Intrinsic::x86_avx2_phadd_w:
9701   case Intrinsic::x86_avx2_phadd_d:
9702   case Intrinsic::x86_ssse3_phsub_w_128:
9703   case Intrinsic::x86_ssse3_phsub_d_128:
9704   case Intrinsic::x86_avx2_phsub_w:
9705   case Intrinsic::x86_avx2_phsub_d: {
9706     unsigned Opcode;
9707     switch (IntNo) {
9708     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9709     case Intrinsic::x86_sse3_hadd_ps:
9710     case Intrinsic::x86_sse3_hadd_pd:
9711     case Intrinsic::x86_avx_hadd_ps_256:
9712     case Intrinsic::x86_avx_hadd_pd_256:
9713       Opcode = X86ISD::FHADD;
9714       break;
9715     case Intrinsic::x86_sse3_hsub_ps:
9716     case Intrinsic::x86_sse3_hsub_pd:
9717     case Intrinsic::x86_avx_hsub_ps_256:
9718     case Intrinsic::x86_avx_hsub_pd_256:
9719       Opcode = X86ISD::FHSUB;
9720       break;
9721     case Intrinsic::x86_ssse3_phadd_w_128:
9722     case Intrinsic::x86_ssse3_phadd_d_128:
9723     case Intrinsic::x86_avx2_phadd_w:
9724     case Intrinsic::x86_avx2_phadd_d:
9725       Opcode = X86ISD::HADD;
9726       break;
9727     case Intrinsic::x86_ssse3_phsub_w_128:
9728     case Intrinsic::x86_ssse3_phsub_d_128:
9729     case Intrinsic::x86_avx2_phsub_w:
9730     case Intrinsic::x86_avx2_phsub_d:
9731       Opcode = X86ISD::HSUB;
9732       break;
9733     }
9734     return DAG.getNode(Opcode, dl, Op.getValueType(),
9735                        Op.getOperand(1), Op.getOperand(2));
9736   }
9737
9738   // AVX2 variable shift intrinsics
9739   case Intrinsic::x86_avx2_psllv_d:
9740   case Intrinsic::x86_avx2_psllv_q:
9741   case Intrinsic::x86_avx2_psllv_d_256:
9742   case Intrinsic::x86_avx2_psllv_q_256:
9743   case Intrinsic::x86_avx2_psrlv_d:
9744   case Intrinsic::x86_avx2_psrlv_q:
9745   case Intrinsic::x86_avx2_psrlv_d_256:
9746   case Intrinsic::x86_avx2_psrlv_q_256:
9747   case Intrinsic::x86_avx2_psrav_d:
9748   case Intrinsic::x86_avx2_psrav_d_256: {
9749     unsigned Opcode;
9750     switch (IntNo) {
9751     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9752     case Intrinsic::x86_avx2_psllv_d:
9753     case Intrinsic::x86_avx2_psllv_q:
9754     case Intrinsic::x86_avx2_psllv_d_256:
9755     case Intrinsic::x86_avx2_psllv_q_256:
9756       Opcode = ISD::SHL;
9757       break;
9758     case Intrinsic::x86_avx2_psrlv_d:
9759     case Intrinsic::x86_avx2_psrlv_q:
9760     case Intrinsic::x86_avx2_psrlv_d_256:
9761     case Intrinsic::x86_avx2_psrlv_q_256:
9762       Opcode = ISD::SRL;
9763       break;
9764     case Intrinsic::x86_avx2_psrav_d:
9765     case Intrinsic::x86_avx2_psrav_d_256:
9766       Opcode = ISD::SRA;
9767       break;
9768     }
9769     return DAG.getNode(Opcode, dl, Op.getValueType(),
9770                        Op.getOperand(1), Op.getOperand(2));
9771   }
9772
9773   case Intrinsic::x86_ssse3_pshuf_b_128:
9774   case Intrinsic::x86_avx2_pshuf_b:
9775     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9776                        Op.getOperand(1), Op.getOperand(2));
9777
9778   case Intrinsic::x86_ssse3_psign_b_128:
9779   case Intrinsic::x86_ssse3_psign_w_128:
9780   case Intrinsic::x86_ssse3_psign_d_128:
9781   case Intrinsic::x86_avx2_psign_b:
9782   case Intrinsic::x86_avx2_psign_w:
9783   case Intrinsic::x86_avx2_psign_d:
9784     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9785                        Op.getOperand(1), Op.getOperand(2));
9786
9787   case Intrinsic::x86_sse41_insertps:
9788     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9789                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9790
9791   case Intrinsic::x86_avx_vperm2f128_ps_256:
9792   case Intrinsic::x86_avx_vperm2f128_pd_256:
9793   case Intrinsic::x86_avx_vperm2f128_si_256:
9794   case Intrinsic::x86_avx2_vperm2i128:
9795     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9796                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9797
9798   case Intrinsic::x86_avx2_permd:
9799   case Intrinsic::x86_avx2_permps:
9800     // Operands intentionally swapped. Mask is last operand to intrinsic,
9801     // but second operand for node/intruction.
9802     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9803                        Op.getOperand(2), Op.getOperand(1));
9804
9805   // ptest and testp intrinsics. The intrinsic these come from are designed to
9806   // return an integer value, not just an instruction so lower it to the ptest
9807   // or testp pattern and a setcc for the result.
9808   case Intrinsic::x86_sse41_ptestz:
9809   case Intrinsic::x86_sse41_ptestc:
9810   case Intrinsic::x86_sse41_ptestnzc:
9811   case Intrinsic::x86_avx_ptestz_256:
9812   case Intrinsic::x86_avx_ptestc_256:
9813   case Intrinsic::x86_avx_ptestnzc_256:
9814   case Intrinsic::x86_avx_vtestz_ps:
9815   case Intrinsic::x86_avx_vtestc_ps:
9816   case Intrinsic::x86_avx_vtestnzc_ps:
9817   case Intrinsic::x86_avx_vtestz_pd:
9818   case Intrinsic::x86_avx_vtestc_pd:
9819   case Intrinsic::x86_avx_vtestnzc_pd:
9820   case Intrinsic::x86_avx_vtestz_ps_256:
9821   case Intrinsic::x86_avx_vtestc_ps_256:
9822   case Intrinsic::x86_avx_vtestnzc_ps_256:
9823   case Intrinsic::x86_avx_vtestz_pd_256:
9824   case Intrinsic::x86_avx_vtestc_pd_256:
9825   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9826     bool IsTestPacked = false;
9827     unsigned X86CC;
9828     switch (IntNo) {
9829     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9830     case Intrinsic::x86_avx_vtestz_ps:
9831     case Intrinsic::x86_avx_vtestz_pd:
9832     case Intrinsic::x86_avx_vtestz_ps_256:
9833     case Intrinsic::x86_avx_vtestz_pd_256:
9834       IsTestPacked = true; // Fallthrough
9835     case Intrinsic::x86_sse41_ptestz:
9836     case Intrinsic::x86_avx_ptestz_256:
9837       // ZF = 1
9838       X86CC = X86::COND_E;
9839       break;
9840     case Intrinsic::x86_avx_vtestc_ps:
9841     case Intrinsic::x86_avx_vtestc_pd:
9842     case Intrinsic::x86_avx_vtestc_ps_256:
9843     case Intrinsic::x86_avx_vtestc_pd_256:
9844       IsTestPacked = true; // Fallthrough
9845     case Intrinsic::x86_sse41_ptestc:
9846     case Intrinsic::x86_avx_ptestc_256:
9847       // CF = 1
9848       X86CC = X86::COND_B;
9849       break;
9850     case Intrinsic::x86_avx_vtestnzc_ps:
9851     case Intrinsic::x86_avx_vtestnzc_pd:
9852     case Intrinsic::x86_avx_vtestnzc_ps_256:
9853     case Intrinsic::x86_avx_vtestnzc_pd_256:
9854       IsTestPacked = true; // Fallthrough
9855     case Intrinsic::x86_sse41_ptestnzc:
9856     case Intrinsic::x86_avx_ptestnzc_256:
9857       // ZF and CF = 0
9858       X86CC = X86::COND_A;
9859       break;
9860     }
9861
9862     SDValue LHS = Op.getOperand(1);
9863     SDValue RHS = Op.getOperand(2);
9864     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9865     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9866     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9867     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9868     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9869   }
9870
9871   // SSE/AVX shift intrinsics
9872   case Intrinsic::x86_sse2_psll_w:
9873   case Intrinsic::x86_sse2_psll_d:
9874   case Intrinsic::x86_sse2_psll_q:
9875   case Intrinsic::x86_avx2_psll_w:
9876   case Intrinsic::x86_avx2_psll_d:
9877   case Intrinsic::x86_avx2_psll_q:
9878   case Intrinsic::x86_sse2_psrl_w:
9879   case Intrinsic::x86_sse2_psrl_d:
9880   case Intrinsic::x86_sse2_psrl_q:
9881   case Intrinsic::x86_avx2_psrl_w:
9882   case Intrinsic::x86_avx2_psrl_d:
9883   case Intrinsic::x86_avx2_psrl_q:
9884   case Intrinsic::x86_sse2_psra_w:
9885   case Intrinsic::x86_sse2_psra_d:
9886   case Intrinsic::x86_avx2_psra_w:
9887   case Intrinsic::x86_avx2_psra_d: {
9888     unsigned Opcode;
9889     switch (IntNo) {
9890     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9891     case Intrinsic::x86_sse2_psll_w:
9892     case Intrinsic::x86_sse2_psll_d:
9893     case Intrinsic::x86_sse2_psll_q:
9894     case Intrinsic::x86_avx2_psll_w:
9895     case Intrinsic::x86_avx2_psll_d:
9896     case Intrinsic::x86_avx2_psll_q:
9897       Opcode = X86ISD::VSHL;
9898       break;
9899     case Intrinsic::x86_sse2_psrl_w:
9900     case Intrinsic::x86_sse2_psrl_d:
9901     case Intrinsic::x86_sse2_psrl_q:
9902     case Intrinsic::x86_avx2_psrl_w:
9903     case Intrinsic::x86_avx2_psrl_d:
9904     case Intrinsic::x86_avx2_psrl_q:
9905       Opcode = X86ISD::VSRL;
9906       break;
9907     case Intrinsic::x86_sse2_psra_w:
9908     case Intrinsic::x86_sse2_psra_d:
9909     case Intrinsic::x86_avx2_psra_w:
9910     case Intrinsic::x86_avx2_psra_d:
9911       Opcode = X86ISD::VSRA;
9912       break;
9913     }
9914     return DAG.getNode(Opcode, dl, Op.getValueType(),
9915                        Op.getOperand(1), Op.getOperand(2));
9916   }
9917
9918   // SSE/AVX immediate shift intrinsics
9919   case Intrinsic::x86_sse2_pslli_w:
9920   case Intrinsic::x86_sse2_pslli_d:
9921   case Intrinsic::x86_sse2_pslli_q:
9922   case Intrinsic::x86_avx2_pslli_w:
9923   case Intrinsic::x86_avx2_pslli_d:
9924   case Intrinsic::x86_avx2_pslli_q:
9925   case Intrinsic::x86_sse2_psrli_w:
9926   case Intrinsic::x86_sse2_psrli_d:
9927   case Intrinsic::x86_sse2_psrli_q:
9928   case Intrinsic::x86_avx2_psrli_w:
9929   case Intrinsic::x86_avx2_psrli_d:
9930   case Intrinsic::x86_avx2_psrli_q:
9931   case Intrinsic::x86_sse2_psrai_w:
9932   case Intrinsic::x86_sse2_psrai_d:
9933   case Intrinsic::x86_avx2_psrai_w:
9934   case Intrinsic::x86_avx2_psrai_d: {
9935     unsigned Opcode;
9936     switch (IntNo) {
9937     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9938     case Intrinsic::x86_sse2_pslli_w:
9939     case Intrinsic::x86_sse2_pslli_d:
9940     case Intrinsic::x86_sse2_pslli_q:
9941     case Intrinsic::x86_avx2_pslli_w:
9942     case Intrinsic::x86_avx2_pslli_d:
9943     case Intrinsic::x86_avx2_pslli_q:
9944       Opcode = X86ISD::VSHLI;
9945       break;
9946     case Intrinsic::x86_sse2_psrli_w:
9947     case Intrinsic::x86_sse2_psrli_d:
9948     case Intrinsic::x86_sse2_psrli_q:
9949     case Intrinsic::x86_avx2_psrli_w:
9950     case Intrinsic::x86_avx2_psrli_d:
9951     case Intrinsic::x86_avx2_psrli_q:
9952       Opcode = X86ISD::VSRLI;
9953       break;
9954     case Intrinsic::x86_sse2_psrai_w:
9955     case Intrinsic::x86_sse2_psrai_d:
9956     case Intrinsic::x86_avx2_psrai_w:
9957     case Intrinsic::x86_avx2_psrai_d:
9958       Opcode = X86ISD::VSRAI;
9959       break;
9960     }
9961     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
9962                                Op.getOperand(1), Op.getOperand(2), DAG);
9963   }
9964
9965   case Intrinsic::x86_sse42_pcmpistria128:
9966   case Intrinsic::x86_sse42_pcmpestria128:
9967   case Intrinsic::x86_sse42_pcmpistric128:
9968   case Intrinsic::x86_sse42_pcmpestric128:
9969   case Intrinsic::x86_sse42_pcmpistrio128:
9970   case Intrinsic::x86_sse42_pcmpestrio128:
9971   case Intrinsic::x86_sse42_pcmpistris128:
9972   case Intrinsic::x86_sse42_pcmpestris128:
9973   case Intrinsic::x86_sse42_pcmpistriz128:
9974   case Intrinsic::x86_sse42_pcmpestriz128: {
9975     unsigned Opcode;
9976     unsigned X86CC;
9977     switch (IntNo) {
9978     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9979     case Intrinsic::x86_sse42_pcmpistria128:
9980       Opcode = X86ISD::PCMPISTRI;
9981       X86CC = X86::COND_A;
9982       break;
9983     case Intrinsic::x86_sse42_pcmpestria128:
9984       Opcode = X86ISD::PCMPESTRI;
9985       X86CC = X86::COND_A;
9986       break;
9987     case Intrinsic::x86_sse42_pcmpistric128:
9988       Opcode = X86ISD::PCMPISTRI;
9989       X86CC = X86::COND_B;
9990       break;
9991     case Intrinsic::x86_sse42_pcmpestric128:
9992       Opcode = X86ISD::PCMPESTRI;
9993       X86CC = X86::COND_B;
9994       break;
9995     case Intrinsic::x86_sse42_pcmpistrio128:
9996       Opcode = X86ISD::PCMPISTRI;
9997       X86CC = X86::COND_O;
9998       break;
9999     case Intrinsic::x86_sse42_pcmpestrio128:
10000       Opcode = X86ISD::PCMPESTRI;
10001       X86CC = X86::COND_O;
10002       break;
10003     case Intrinsic::x86_sse42_pcmpistris128:
10004       Opcode = X86ISD::PCMPISTRI;
10005       X86CC = X86::COND_S;
10006       break;
10007     case Intrinsic::x86_sse42_pcmpestris128:
10008       Opcode = X86ISD::PCMPESTRI;
10009       X86CC = X86::COND_S;
10010       break;
10011     case Intrinsic::x86_sse42_pcmpistriz128:
10012       Opcode = X86ISD::PCMPISTRI;
10013       X86CC = X86::COND_E;
10014       break;
10015     case Intrinsic::x86_sse42_pcmpestriz128:
10016       Opcode = X86ISD::PCMPESTRI;
10017       X86CC = X86::COND_E;
10018       break;
10019     }
10020     SmallVector<SDValue, 5> NewOps;
10021     NewOps.append(Op->op_begin()+1, Op->op_end());
10022     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10023     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10024     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10025                                 DAG.getConstant(X86CC, MVT::i8),
10026                                 SDValue(PCMP.getNode(), 1));
10027     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10028   }
10029
10030   case Intrinsic::x86_sse42_pcmpistri128:
10031   case Intrinsic::x86_sse42_pcmpestri128: {
10032     unsigned Opcode;
10033     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10034       Opcode = X86ISD::PCMPISTRI;
10035     else
10036       Opcode = X86ISD::PCMPESTRI;
10037
10038     SmallVector<SDValue, 5> NewOps;
10039     NewOps.append(Op->op_begin()+1, Op->op_end());
10040     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10041     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10042   }
10043   case Intrinsic::x86_fma_vfmadd_ps:
10044   case Intrinsic::x86_fma_vfmadd_pd:
10045   case Intrinsic::x86_fma_vfmsub_ps:
10046   case Intrinsic::x86_fma_vfmsub_pd:
10047   case Intrinsic::x86_fma_vfnmadd_ps:
10048   case Intrinsic::x86_fma_vfnmadd_pd:
10049   case Intrinsic::x86_fma_vfnmsub_ps:
10050   case Intrinsic::x86_fma_vfnmsub_pd:
10051   case Intrinsic::x86_fma_vfmaddsub_ps:
10052   case Intrinsic::x86_fma_vfmaddsub_pd:
10053   case Intrinsic::x86_fma_vfmsubadd_ps:
10054   case Intrinsic::x86_fma_vfmsubadd_pd:
10055   case Intrinsic::x86_fma_vfmadd_ps_256:
10056   case Intrinsic::x86_fma_vfmadd_pd_256:
10057   case Intrinsic::x86_fma_vfmsub_ps_256:
10058   case Intrinsic::x86_fma_vfmsub_pd_256:
10059   case Intrinsic::x86_fma_vfnmadd_ps_256:
10060   case Intrinsic::x86_fma_vfnmadd_pd_256:
10061   case Intrinsic::x86_fma_vfnmsub_ps_256:
10062   case Intrinsic::x86_fma_vfnmsub_pd_256:
10063   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10064   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10065   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10066   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10067     unsigned Opc;
10068     switch (IntNo) {
10069     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10070     case Intrinsic::x86_fma_vfmadd_ps:
10071     case Intrinsic::x86_fma_vfmadd_pd:
10072     case Intrinsic::x86_fma_vfmadd_ps_256:
10073     case Intrinsic::x86_fma_vfmadd_pd_256:
10074       Opc = X86ISD::FMADD;
10075       break;
10076     case Intrinsic::x86_fma_vfmsub_ps:
10077     case Intrinsic::x86_fma_vfmsub_pd:
10078     case Intrinsic::x86_fma_vfmsub_ps_256:
10079     case Intrinsic::x86_fma_vfmsub_pd_256:
10080       Opc = X86ISD::FMSUB;
10081       break;
10082     case Intrinsic::x86_fma_vfnmadd_ps:
10083     case Intrinsic::x86_fma_vfnmadd_pd:
10084     case Intrinsic::x86_fma_vfnmadd_ps_256:
10085     case Intrinsic::x86_fma_vfnmadd_pd_256:
10086       Opc = X86ISD::FNMADD;
10087       break;
10088     case Intrinsic::x86_fma_vfnmsub_ps:
10089     case Intrinsic::x86_fma_vfnmsub_pd:
10090     case Intrinsic::x86_fma_vfnmsub_ps_256:
10091     case Intrinsic::x86_fma_vfnmsub_pd_256:
10092       Opc = X86ISD::FNMSUB;
10093       break;
10094     case Intrinsic::x86_fma_vfmaddsub_ps:
10095     case Intrinsic::x86_fma_vfmaddsub_pd:
10096     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10097     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10098       Opc = X86ISD::FMADDSUB;
10099       break;
10100     case Intrinsic::x86_fma_vfmsubadd_ps:
10101     case Intrinsic::x86_fma_vfmsubadd_pd:
10102     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10103     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10104       Opc = X86ISD::FMSUBADD;
10105       break;
10106     }
10107
10108     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10109                        Op.getOperand(2), Op.getOperand(3));
10110   }
10111   }
10112 }
10113
10114 SDValue
10115 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
10116   DebugLoc dl = Op.getDebugLoc();
10117   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10118   switch (IntNo) {
10119   default: return SDValue();    // Don't custom lower most intrinsics.
10120
10121   // RDRAND intrinsics.
10122   case Intrinsic::x86_rdrand_16:
10123   case Intrinsic::x86_rdrand_32:
10124   case Intrinsic::x86_rdrand_64: {
10125     // Emit the node with the right value type.
10126     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10127     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10128
10129     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10130     // return the value from Rand, which is always 0, casted to i32.
10131     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10132                       DAG.getConstant(1, Op->getValueType(1)),
10133                       DAG.getConstant(X86::COND_B, MVT::i32),
10134                       SDValue(Result.getNode(), 1) };
10135     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10136                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10137                                   Ops, 4);
10138
10139     // Return { result, isValid, chain }.
10140     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10141                        SDValue(Result.getNode(), 2));
10142   }
10143   }
10144 }
10145
10146 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10147                                            SelectionDAG &DAG) const {
10148   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10149   MFI->setReturnAddressIsTaken(true);
10150
10151   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10152   DebugLoc dl = Op.getDebugLoc();
10153
10154   if (Depth > 0) {
10155     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10156     SDValue Offset =
10157       DAG.getConstant(TD->getPointerSize(),
10158                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10159     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10160                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10161                                    FrameAddr, Offset),
10162                        MachinePointerInfo(), false, false, false, 0);
10163   }
10164
10165   // Just load the return address.
10166   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10167   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10168                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10169 }
10170
10171 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10172   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10173   MFI->setFrameAddressIsTaken(true);
10174
10175   EVT VT = Op.getValueType();
10176   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10177   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10178   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10179   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10180   while (Depth--)
10181     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10182                             MachinePointerInfo(),
10183                             false, false, false, 0);
10184   return FrameAddr;
10185 }
10186
10187 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10188                                                      SelectionDAG &DAG) const {
10189   return DAG.getIntPtrConstant(2*TD->getPointerSize());
10190 }
10191
10192 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10193   SDValue Chain     = Op.getOperand(0);
10194   SDValue Offset    = Op.getOperand(1);
10195   SDValue Handler   = Op.getOperand(2);
10196   DebugLoc dl       = Op.getDebugLoc();
10197
10198   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10199                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10200                                      getPointerTy());
10201   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10202
10203   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10204                                   DAG.getIntPtrConstant(TD->getPointerSize()));
10205   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10206   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10207                        false, false, 0);
10208   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10209
10210   return DAG.getNode(X86ISD::EH_RETURN, dl,
10211                      MVT::Other,
10212                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10213 }
10214
10215 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10216                                                   SelectionDAG &DAG) const {
10217   return Op.getOperand(0);
10218 }
10219
10220 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10221                                                 SelectionDAG &DAG) const {
10222   SDValue Root = Op.getOperand(0);
10223   SDValue Trmp = Op.getOperand(1); // trampoline
10224   SDValue FPtr = Op.getOperand(2); // nested function
10225   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10226   DebugLoc dl  = Op.getDebugLoc();
10227
10228   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10229
10230   if (Subtarget->is64Bit()) {
10231     SDValue OutChains[6];
10232
10233     // Large code-model.
10234     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10235     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10236
10237     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10238     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10239
10240     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10241
10242     // Load the pointer to the nested function into R11.
10243     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10244     SDValue Addr = Trmp;
10245     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10246                                 Addr, MachinePointerInfo(TrmpAddr),
10247                                 false, false, 0);
10248
10249     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10250                        DAG.getConstant(2, MVT::i64));
10251     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10252                                 MachinePointerInfo(TrmpAddr, 2),
10253                                 false, false, 2);
10254
10255     // Load the 'nest' parameter value into R10.
10256     // R10 is specified in X86CallingConv.td
10257     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10258     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10259                        DAG.getConstant(10, MVT::i64));
10260     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10261                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10262                                 false, false, 0);
10263
10264     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10265                        DAG.getConstant(12, MVT::i64));
10266     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10267                                 MachinePointerInfo(TrmpAddr, 12),
10268                                 false, false, 2);
10269
10270     // Jump to the nested function.
10271     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10272     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10273                        DAG.getConstant(20, MVT::i64));
10274     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10275                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10276                                 false, false, 0);
10277
10278     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10279     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10280                        DAG.getConstant(22, MVT::i64));
10281     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10282                                 MachinePointerInfo(TrmpAddr, 22),
10283                                 false, false, 0);
10284
10285     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10286   } else {
10287     const Function *Func =
10288       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10289     CallingConv::ID CC = Func->getCallingConv();
10290     unsigned NestReg;
10291
10292     switch (CC) {
10293     default:
10294       llvm_unreachable("Unsupported calling convention");
10295     case CallingConv::C:
10296     case CallingConv::X86_StdCall: {
10297       // Pass 'nest' parameter in ECX.
10298       // Must be kept in sync with X86CallingConv.td
10299       NestReg = X86::ECX;
10300
10301       // Check that ECX wasn't needed by an 'inreg' parameter.
10302       FunctionType *FTy = Func->getFunctionType();
10303       const AttrListPtr &Attrs = Func->getAttributes();
10304
10305       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10306         unsigned InRegCount = 0;
10307         unsigned Idx = 1;
10308
10309         for (FunctionType::param_iterator I = FTy->param_begin(),
10310              E = FTy->param_end(); I != E; ++I, ++Idx)
10311           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10312             // FIXME: should only count parameters that are lowered to integers.
10313             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10314
10315         if (InRegCount > 2) {
10316           report_fatal_error("Nest register in use - reduce number of inreg"
10317                              " parameters!");
10318         }
10319       }
10320       break;
10321     }
10322     case CallingConv::X86_FastCall:
10323     case CallingConv::X86_ThisCall:
10324     case CallingConv::Fast:
10325       // Pass 'nest' parameter in EAX.
10326       // Must be kept in sync with X86CallingConv.td
10327       NestReg = X86::EAX;
10328       break;
10329     }
10330
10331     SDValue OutChains[4];
10332     SDValue Addr, Disp;
10333
10334     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10335                        DAG.getConstant(10, MVT::i32));
10336     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10337
10338     // This is storing the opcode for MOV32ri.
10339     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10340     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10341     OutChains[0] = DAG.getStore(Root, dl,
10342                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10343                                 Trmp, MachinePointerInfo(TrmpAddr),
10344                                 false, false, 0);
10345
10346     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10347                        DAG.getConstant(1, MVT::i32));
10348     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10349                                 MachinePointerInfo(TrmpAddr, 1),
10350                                 false, false, 1);
10351
10352     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10353     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10354                        DAG.getConstant(5, MVT::i32));
10355     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10356                                 MachinePointerInfo(TrmpAddr, 5),
10357                                 false, false, 1);
10358
10359     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10360                        DAG.getConstant(6, MVT::i32));
10361     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10362                                 MachinePointerInfo(TrmpAddr, 6),
10363                                 false, false, 1);
10364
10365     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10366   }
10367 }
10368
10369 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10370                                             SelectionDAG &DAG) const {
10371   /*
10372    The rounding mode is in bits 11:10 of FPSR, and has the following
10373    settings:
10374      00 Round to nearest
10375      01 Round to -inf
10376      10 Round to +inf
10377      11 Round to 0
10378
10379   FLT_ROUNDS, on the other hand, expects the following:
10380     -1 Undefined
10381      0 Round to 0
10382      1 Round to nearest
10383      2 Round to +inf
10384      3 Round to -inf
10385
10386   To perform the conversion, we do:
10387     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10388   */
10389
10390   MachineFunction &MF = DAG.getMachineFunction();
10391   const TargetMachine &TM = MF.getTarget();
10392   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10393   unsigned StackAlignment = TFI.getStackAlignment();
10394   EVT VT = Op.getValueType();
10395   DebugLoc DL = Op.getDebugLoc();
10396
10397   // Save FP Control Word to stack slot
10398   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10399   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10400
10401
10402   MachineMemOperand *MMO =
10403    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10404                            MachineMemOperand::MOStore, 2, 2);
10405
10406   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10407   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10408                                           DAG.getVTList(MVT::Other),
10409                                           Ops, 2, MVT::i16, MMO);
10410
10411   // Load FP Control Word from stack slot
10412   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10413                             MachinePointerInfo(), false, false, false, 0);
10414
10415   // Transform as necessary
10416   SDValue CWD1 =
10417     DAG.getNode(ISD::SRL, DL, MVT::i16,
10418                 DAG.getNode(ISD::AND, DL, MVT::i16,
10419                             CWD, DAG.getConstant(0x800, MVT::i16)),
10420                 DAG.getConstant(11, MVT::i8));
10421   SDValue CWD2 =
10422     DAG.getNode(ISD::SRL, DL, MVT::i16,
10423                 DAG.getNode(ISD::AND, DL, MVT::i16,
10424                             CWD, DAG.getConstant(0x400, MVT::i16)),
10425                 DAG.getConstant(9, MVT::i8));
10426
10427   SDValue RetVal =
10428     DAG.getNode(ISD::AND, DL, MVT::i16,
10429                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10430                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10431                             DAG.getConstant(1, MVT::i16)),
10432                 DAG.getConstant(3, MVT::i16));
10433
10434
10435   return DAG.getNode((VT.getSizeInBits() < 16 ?
10436                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10437 }
10438
10439 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10440   EVT VT = Op.getValueType();
10441   EVT OpVT = VT;
10442   unsigned NumBits = VT.getSizeInBits();
10443   DebugLoc dl = Op.getDebugLoc();
10444
10445   Op = Op.getOperand(0);
10446   if (VT == MVT::i8) {
10447     // Zero extend to i32 since there is not an i8 bsr.
10448     OpVT = MVT::i32;
10449     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10450   }
10451
10452   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10453   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10454   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10455
10456   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10457   SDValue Ops[] = {
10458     Op,
10459     DAG.getConstant(NumBits+NumBits-1, OpVT),
10460     DAG.getConstant(X86::COND_E, MVT::i8),
10461     Op.getValue(1)
10462   };
10463   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10464
10465   // Finally xor with NumBits-1.
10466   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10467
10468   if (VT == MVT::i8)
10469     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10470   return Op;
10471 }
10472
10473 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10474                                                 SelectionDAG &DAG) const {
10475   EVT VT = Op.getValueType();
10476   EVT OpVT = VT;
10477   unsigned NumBits = VT.getSizeInBits();
10478   DebugLoc dl = Op.getDebugLoc();
10479
10480   Op = Op.getOperand(0);
10481   if (VT == MVT::i8) {
10482     // Zero extend to i32 since there is not an i8 bsr.
10483     OpVT = MVT::i32;
10484     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10485   }
10486
10487   // Issue a bsr (scan bits in reverse).
10488   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10489   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10490
10491   // And xor with NumBits-1.
10492   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10493
10494   if (VT == MVT::i8)
10495     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10496   return Op;
10497 }
10498
10499 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10500   EVT VT = Op.getValueType();
10501   unsigned NumBits = VT.getSizeInBits();
10502   DebugLoc dl = Op.getDebugLoc();
10503   Op = Op.getOperand(0);
10504
10505   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10506   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10507   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10508
10509   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10510   SDValue Ops[] = {
10511     Op,
10512     DAG.getConstant(NumBits, VT),
10513     DAG.getConstant(X86::COND_E, MVT::i8),
10514     Op.getValue(1)
10515   };
10516   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10517 }
10518
10519 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10520 // ones, and then concatenate the result back.
10521 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10522   EVT VT = Op.getValueType();
10523
10524   assert(VT.is256BitVector() && VT.isInteger() &&
10525          "Unsupported value type for operation");
10526
10527   unsigned NumElems = VT.getVectorNumElements();
10528   DebugLoc dl = Op.getDebugLoc();
10529
10530   // Extract the LHS vectors
10531   SDValue LHS = Op.getOperand(0);
10532   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10533   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10534
10535   // Extract the RHS vectors
10536   SDValue RHS = Op.getOperand(1);
10537   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10538   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10539
10540   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10541   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10542
10543   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10544                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10545                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10546 }
10547
10548 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10549   assert(Op.getValueType().is256BitVector() &&
10550          Op.getValueType().isInteger() &&
10551          "Only handle AVX 256-bit vector integer operation");
10552   return Lower256IntArith(Op, DAG);
10553 }
10554
10555 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10556   assert(Op.getValueType().is256BitVector() &&
10557          Op.getValueType().isInteger() &&
10558          "Only handle AVX 256-bit vector integer operation");
10559   return Lower256IntArith(Op, DAG);
10560 }
10561
10562 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10563   EVT VT = Op.getValueType();
10564
10565   // Decompose 256-bit ops into smaller 128-bit ops.
10566   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10567     return Lower256IntArith(Op, DAG);
10568
10569   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10570          "Only know how to lower V2I64/V4I64 multiply");
10571
10572   DebugLoc dl = Op.getDebugLoc();
10573
10574   //  Ahi = psrlqi(a, 32);
10575   //  Bhi = psrlqi(b, 32);
10576   //
10577   //  AloBlo = pmuludq(a, b);
10578   //  AloBhi = pmuludq(a, Bhi);
10579   //  AhiBlo = pmuludq(Ahi, b);
10580
10581   //  AloBhi = psllqi(AloBhi, 32);
10582   //  AhiBlo = psllqi(AhiBlo, 32);
10583   //  return AloBlo + AloBhi + AhiBlo;
10584
10585   SDValue A = Op.getOperand(0);
10586   SDValue B = Op.getOperand(1);
10587
10588   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10589
10590   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10591   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10592
10593   // Bit cast to 32-bit vectors for MULUDQ
10594   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10595   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10596   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10597   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10598   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10599
10600   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10601   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10602   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10603
10604   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10605   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10606
10607   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10608   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10609 }
10610
10611 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10612
10613   EVT VT = Op.getValueType();
10614   DebugLoc dl = Op.getDebugLoc();
10615   SDValue R = Op.getOperand(0);
10616   SDValue Amt = Op.getOperand(1);
10617   LLVMContext *Context = DAG.getContext();
10618
10619   if (!Subtarget->hasSSE2())
10620     return SDValue();
10621
10622   // Optimize shl/srl/sra with constant shift amount.
10623   if (isSplatVector(Amt.getNode())) {
10624     SDValue SclrAmt = Amt->getOperand(0);
10625     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10626       uint64_t ShiftAmt = C->getZExtValue();
10627
10628       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10629           (Subtarget->hasAVX2() &&
10630            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10631         if (Op.getOpcode() == ISD::SHL)
10632           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10633                              DAG.getConstant(ShiftAmt, MVT::i32));
10634         if (Op.getOpcode() == ISD::SRL)
10635           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10636                              DAG.getConstant(ShiftAmt, MVT::i32));
10637         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10638           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10639                              DAG.getConstant(ShiftAmt, MVT::i32));
10640       }
10641
10642       if (VT == MVT::v16i8) {
10643         if (Op.getOpcode() == ISD::SHL) {
10644           // Make a large shift.
10645           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10646                                     DAG.getConstant(ShiftAmt, MVT::i32));
10647           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10648           // Zero out the rightmost bits.
10649           SmallVector<SDValue, 16> V(16,
10650                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10651                                                      MVT::i8));
10652           return DAG.getNode(ISD::AND, dl, VT, SHL,
10653                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10654         }
10655         if (Op.getOpcode() == ISD::SRL) {
10656           // Make a large shift.
10657           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10658                                     DAG.getConstant(ShiftAmt, MVT::i32));
10659           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10660           // Zero out the leftmost bits.
10661           SmallVector<SDValue, 16> V(16,
10662                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10663                                                      MVT::i8));
10664           return DAG.getNode(ISD::AND, dl, VT, SRL,
10665                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10666         }
10667         if (Op.getOpcode() == ISD::SRA) {
10668           if (ShiftAmt == 7) {
10669             // R s>> 7  ===  R s< 0
10670             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10671             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10672           }
10673
10674           // R s>> a === ((R u>> a) ^ m) - m
10675           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10676           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10677                                                          MVT::i8));
10678           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10679           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10680           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10681           return Res;
10682         }
10683         llvm_unreachable("Unknown shift opcode.");
10684       }
10685
10686       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10687         if (Op.getOpcode() == ISD::SHL) {
10688           // Make a large shift.
10689           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10690                                     DAG.getConstant(ShiftAmt, MVT::i32));
10691           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10692           // Zero out the rightmost bits.
10693           SmallVector<SDValue, 32> V(32,
10694                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10695                                                      MVT::i8));
10696           return DAG.getNode(ISD::AND, dl, VT, SHL,
10697                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10698         }
10699         if (Op.getOpcode() == ISD::SRL) {
10700           // Make a large shift.
10701           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10702                                     DAG.getConstant(ShiftAmt, MVT::i32));
10703           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10704           // Zero out the leftmost bits.
10705           SmallVector<SDValue, 32> V(32,
10706                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10707                                                      MVT::i8));
10708           return DAG.getNode(ISD::AND, dl, VT, SRL,
10709                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10710         }
10711         if (Op.getOpcode() == ISD::SRA) {
10712           if (ShiftAmt == 7) {
10713             // R s>> 7  ===  R s< 0
10714             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10715             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10716           }
10717
10718           // R s>> a === ((R u>> a) ^ m) - m
10719           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10720           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10721                                                          MVT::i8));
10722           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10723           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10724           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10725           return Res;
10726         }
10727         llvm_unreachable("Unknown shift opcode.");
10728       }
10729     }
10730   }
10731
10732   // Lower SHL with variable shift amount.
10733   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10734     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10735                      DAG.getConstant(23, MVT::i32));
10736
10737     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10738     Constant *C = ConstantDataVector::get(*Context, CV);
10739     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10740     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10741                                  MachinePointerInfo::getConstantPool(),
10742                                  false, false, false, 16);
10743
10744     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10745     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10746     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10747     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10748   }
10749   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10750     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10751
10752     // a = a << 5;
10753     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10754                      DAG.getConstant(5, MVT::i32));
10755     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10756
10757     // Turn 'a' into a mask suitable for VSELECT
10758     SDValue VSelM = DAG.getConstant(0x80, VT);
10759     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10760     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10761
10762     SDValue CM1 = DAG.getConstant(0x0f, VT);
10763     SDValue CM2 = DAG.getConstant(0x3f, VT);
10764
10765     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10766     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10767     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10768                             DAG.getConstant(4, MVT::i32), DAG);
10769     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10770     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10771
10772     // a += a
10773     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10774     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10775     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10776
10777     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10778     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10779     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10780                             DAG.getConstant(2, MVT::i32), DAG);
10781     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10782     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10783
10784     // a += a
10785     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10786     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10787     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10788
10789     // return VSELECT(r, r+r, a);
10790     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10791                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10792     return R;
10793   }
10794
10795   // Decompose 256-bit shifts into smaller 128-bit shifts.
10796   if (VT.is256BitVector()) {
10797     unsigned NumElems = VT.getVectorNumElements();
10798     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10799     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10800
10801     // Extract the two vectors
10802     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10803     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10804
10805     // Recreate the shift amount vectors
10806     SDValue Amt1, Amt2;
10807     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10808       // Constant shift amount
10809       SmallVector<SDValue, 4> Amt1Csts;
10810       SmallVector<SDValue, 4> Amt2Csts;
10811       for (unsigned i = 0; i != NumElems/2; ++i)
10812         Amt1Csts.push_back(Amt->getOperand(i));
10813       for (unsigned i = NumElems/2; i != NumElems; ++i)
10814         Amt2Csts.push_back(Amt->getOperand(i));
10815
10816       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10817                                  &Amt1Csts[0], NumElems/2);
10818       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10819                                  &Amt2Csts[0], NumElems/2);
10820     } else {
10821       // Variable shift amount
10822       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10823       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10824     }
10825
10826     // Issue new vector shifts for the smaller types
10827     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10828     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10829
10830     // Concatenate the result back
10831     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10832   }
10833
10834   return SDValue();
10835 }
10836
10837 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10838   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10839   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10840   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10841   // has only one use.
10842   SDNode *N = Op.getNode();
10843   SDValue LHS = N->getOperand(0);
10844   SDValue RHS = N->getOperand(1);
10845   unsigned BaseOp = 0;
10846   unsigned Cond = 0;
10847   DebugLoc DL = Op.getDebugLoc();
10848   switch (Op.getOpcode()) {
10849   default: llvm_unreachable("Unknown ovf instruction!");
10850   case ISD::SADDO:
10851     // A subtract of one will be selected as a INC. Note that INC doesn't
10852     // set CF, so we can't do this for UADDO.
10853     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10854       if (C->isOne()) {
10855         BaseOp = X86ISD::INC;
10856         Cond = X86::COND_O;
10857         break;
10858       }
10859     BaseOp = X86ISD::ADD;
10860     Cond = X86::COND_O;
10861     break;
10862   case ISD::UADDO:
10863     BaseOp = X86ISD::ADD;
10864     Cond = X86::COND_B;
10865     break;
10866   case ISD::SSUBO:
10867     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10868     // set CF, so we can't do this for USUBO.
10869     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10870       if (C->isOne()) {
10871         BaseOp = X86ISD::DEC;
10872         Cond = X86::COND_O;
10873         break;
10874       }
10875     BaseOp = X86ISD::SUB;
10876     Cond = X86::COND_O;
10877     break;
10878   case ISD::USUBO:
10879     BaseOp = X86ISD::SUB;
10880     Cond = X86::COND_B;
10881     break;
10882   case ISD::SMULO:
10883     BaseOp = X86ISD::SMUL;
10884     Cond = X86::COND_O;
10885     break;
10886   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10887     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10888                                  MVT::i32);
10889     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10890
10891     SDValue SetCC =
10892       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10893                   DAG.getConstant(X86::COND_O, MVT::i32),
10894                   SDValue(Sum.getNode(), 2));
10895
10896     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10897   }
10898   }
10899
10900   // Also sets EFLAGS.
10901   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10902   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10903
10904   SDValue SetCC =
10905     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10906                 DAG.getConstant(Cond, MVT::i32),
10907                 SDValue(Sum.getNode(), 1));
10908
10909   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10910 }
10911
10912 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10913                                                   SelectionDAG &DAG) const {
10914   DebugLoc dl = Op.getDebugLoc();
10915   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10916   EVT VT = Op.getValueType();
10917
10918   if (!Subtarget->hasSSE2() || !VT.isVector())
10919     return SDValue();
10920
10921   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10922                       ExtraVT.getScalarType().getSizeInBits();
10923   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10924
10925   switch (VT.getSimpleVT().SimpleTy) {
10926     default: return SDValue();
10927     case MVT::v8i32:
10928     case MVT::v16i16:
10929       if (!Subtarget->hasAVX())
10930         return SDValue();
10931       if (!Subtarget->hasAVX2()) {
10932         // needs to be split
10933         unsigned NumElems = VT.getVectorNumElements();
10934
10935         // Extract the LHS vectors
10936         SDValue LHS = Op.getOperand(0);
10937         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10938         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10939
10940         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10941         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10942
10943         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10944         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10945         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10946                                    ExtraNumElems/2);
10947         SDValue Extra = DAG.getValueType(ExtraVT);
10948
10949         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10950         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10951
10952         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10953       }
10954       // fall through
10955     case MVT::v4i32:
10956     case MVT::v8i16: {
10957       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10958                                          Op.getOperand(0), ShAmt, DAG);
10959       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10960     }
10961   }
10962 }
10963
10964
10965 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10966   DebugLoc dl = Op.getDebugLoc();
10967
10968   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10969   // There isn't any reason to disable it if the target processor supports it.
10970   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10971     SDValue Chain = Op.getOperand(0);
10972     SDValue Zero = DAG.getConstant(0, MVT::i32);
10973     SDValue Ops[] = {
10974       DAG.getRegister(X86::ESP, MVT::i32), // Base
10975       DAG.getTargetConstant(1, MVT::i8),   // Scale
10976       DAG.getRegister(0, MVT::i32),        // Index
10977       DAG.getTargetConstant(0, MVT::i32),  // Disp
10978       DAG.getRegister(0, MVT::i32),        // Segment.
10979       Zero,
10980       Chain
10981     };
10982     SDNode *Res =
10983       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10984                           array_lengthof(Ops));
10985     return SDValue(Res, 0);
10986   }
10987
10988   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10989   if (!isDev)
10990     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10991
10992   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10993   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10994   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10995   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10996
10997   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10998   if (!Op1 && !Op2 && !Op3 && Op4)
10999     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11000
11001   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11002   if (Op1 && !Op2 && !Op3 && !Op4)
11003     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11004
11005   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11006   //           (MFENCE)>;
11007   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11008 }
11009
11010 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
11011                                              SelectionDAG &DAG) const {
11012   DebugLoc dl = Op.getDebugLoc();
11013   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11014     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11015   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11016     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11017
11018   // The only fence that needs an instruction is a sequentially-consistent
11019   // cross-thread fence.
11020   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11021     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11022     // no-sse2). There isn't any reason to disable it if the target processor
11023     // supports it.
11024     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11025       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11026
11027     SDValue Chain = Op.getOperand(0);
11028     SDValue Zero = DAG.getConstant(0, MVT::i32);
11029     SDValue Ops[] = {
11030       DAG.getRegister(X86::ESP, MVT::i32), // Base
11031       DAG.getTargetConstant(1, MVT::i8),   // Scale
11032       DAG.getRegister(0, MVT::i32),        // Index
11033       DAG.getTargetConstant(0, MVT::i32),  // Disp
11034       DAG.getRegister(0, MVT::i32),        // Segment.
11035       Zero,
11036       Chain
11037     };
11038     SDNode *Res =
11039       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11040                          array_lengthof(Ops));
11041     return SDValue(Res, 0);
11042   }
11043
11044   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11045   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11046 }
11047
11048
11049 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
11050   EVT T = Op.getValueType();
11051   DebugLoc DL = Op.getDebugLoc();
11052   unsigned Reg = 0;
11053   unsigned size = 0;
11054   switch(T.getSimpleVT().SimpleTy) {
11055   default: llvm_unreachable("Invalid value type!");
11056   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11057   case MVT::i16: Reg = X86::AX;  size = 2; break;
11058   case MVT::i32: Reg = X86::EAX; size = 4; break;
11059   case MVT::i64:
11060     assert(Subtarget->is64Bit() && "Node not type legal!");
11061     Reg = X86::RAX; size = 8;
11062     break;
11063   }
11064   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11065                                     Op.getOperand(2), SDValue());
11066   SDValue Ops[] = { cpIn.getValue(0),
11067                     Op.getOperand(1),
11068                     Op.getOperand(3),
11069                     DAG.getTargetConstant(size, MVT::i8),
11070                     cpIn.getValue(1) };
11071   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11072   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11073   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11074                                            Ops, 5, T, MMO);
11075   SDValue cpOut =
11076     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11077   return cpOut;
11078 }
11079
11080 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
11081                                                  SelectionDAG &DAG) const {
11082   assert(Subtarget->is64Bit() && "Result not type legalized?");
11083   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11084   SDValue TheChain = Op.getOperand(0);
11085   DebugLoc dl = Op.getDebugLoc();
11086   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11087   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11088   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11089                                    rax.getValue(2));
11090   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11091                             DAG.getConstant(32, MVT::i8));
11092   SDValue Ops[] = {
11093     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11094     rdx.getValue(1)
11095   };
11096   return DAG.getMergeValues(Ops, 2, dl);
11097 }
11098
11099 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
11100                                             SelectionDAG &DAG) const {
11101   EVT SrcVT = Op.getOperand(0).getValueType();
11102   EVT DstVT = Op.getValueType();
11103   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11104          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11105   assert((DstVT == MVT::i64 ||
11106           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11107          "Unexpected custom BITCAST");
11108   // i64 <=> MMX conversions are Legal.
11109   if (SrcVT==MVT::i64 && DstVT.isVector())
11110     return Op;
11111   if (DstVT==MVT::i64 && SrcVT.isVector())
11112     return Op;
11113   // MMX <=> MMX conversions are Legal.
11114   if (SrcVT.isVector() && DstVT.isVector())
11115     return Op;
11116   // All other conversions need to be expanded.
11117   return SDValue();
11118 }
11119
11120 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
11121   SDNode *Node = Op.getNode();
11122   DebugLoc dl = Node->getDebugLoc();
11123   EVT T = Node->getValueType(0);
11124   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11125                               DAG.getConstant(0, T), Node->getOperand(2));
11126   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11127                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11128                        Node->getOperand(0),
11129                        Node->getOperand(1), negOp,
11130                        cast<AtomicSDNode>(Node)->getSrcValue(),
11131                        cast<AtomicSDNode>(Node)->getAlignment(),
11132                        cast<AtomicSDNode>(Node)->getOrdering(),
11133                        cast<AtomicSDNode>(Node)->getSynchScope());
11134 }
11135
11136 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11137   SDNode *Node = Op.getNode();
11138   DebugLoc dl = Node->getDebugLoc();
11139   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11140
11141   // Convert seq_cst store -> xchg
11142   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11143   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11144   //        (The only way to get a 16-byte store is cmpxchg16b)
11145   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11146   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11147       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11148     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11149                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11150                                  Node->getOperand(0),
11151                                  Node->getOperand(1), Node->getOperand(2),
11152                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11153                                  cast<AtomicSDNode>(Node)->getOrdering(),
11154                                  cast<AtomicSDNode>(Node)->getSynchScope());
11155     return Swap.getValue(1);
11156   }
11157   // Other atomic stores have a simple pattern.
11158   return Op;
11159 }
11160
11161 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11162   EVT VT = Op.getNode()->getValueType(0);
11163
11164   // Let legalize expand this if it isn't a legal type yet.
11165   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11166     return SDValue();
11167
11168   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11169
11170   unsigned Opc;
11171   bool ExtraOp = false;
11172   switch (Op.getOpcode()) {
11173   default: llvm_unreachable("Invalid code");
11174   case ISD::ADDC: Opc = X86ISD::ADD; break;
11175   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11176   case ISD::SUBC: Opc = X86ISD::SUB; break;
11177   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11178   }
11179
11180   if (!ExtraOp)
11181     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11182                        Op.getOperand(1));
11183   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11184                      Op.getOperand(1), Op.getOperand(2));
11185 }
11186
11187 /// LowerOperation - Provide custom lowering hooks for some operations.
11188 ///
11189 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11190   switch (Op.getOpcode()) {
11191   default: llvm_unreachable("Should not custom lower this!");
11192   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11193   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
11194   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
11195   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
11196   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11197   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11198   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11199   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11200   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11201   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11202   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11203   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
11204   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
11205   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11206   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11207   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11208   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11209   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11210   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11211   case ISD::SHL_PARTS:
11212   case ISD::SRA_PARTS:
11213   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11214   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11215   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11216   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11217   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11218   case ISD::FABS:               return LowerFABS(Op, DAG);
11219   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11220   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11221   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11222   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11223   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11224   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11225   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11226   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11227   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11228   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11229   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11230   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11231   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11232   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11233   case ISD::FRAME_TO_ARGS_OFFSET:
11234                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11235   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11236   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11237   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11238   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11239   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11240   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11241   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11242   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11243   case ISD::MUL:                return LowerMUL(Op, DAG);
11244   case ISD::SRA:
11245   case ISD::SRL:
11246   case ISD::SHL:                return LowerShift(Op, DAG);
11247   case ISD::SADDO:
11248   case ISD::UADDO:
11249   case ISD::SSUBO:
11250   case ISD::USUBO:
11251   case ISD::SMULO:
11252   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11253   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
11254   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11255   case ISD::ADDC:
11256   case ISD::ADDE:
11257   case ISD::SUBC:
11258   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11259   case ISD::ADD:                return LowerADD(Op, DAG);
11260   case ISD::SUB:                return LowerSUB(Op, DAG);
11261   }
11262 }
11263
11264 static void ReplaceATOMIC_LOAD(SDNode *Node,
11265                                   SmallVectorImpl<SDValue> &Results,
11266                                   SelectionDAG &DAG) {
11267   DebugLoc dl = Node->getDebugLoc();
11268   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11269
11270   // Convert wide load -> cmpxchg8b/cmpxchg16b
11271   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11272   //        (The only way to get a 16-byte load is cmpxchg16b)
11273   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11274   SDValue Zero = DAG.getConstant(0, VT);
11275   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11276                                Node->getOperand(0),
11277                                Node->getOperand(1), Zero, Zero,
11278                                cast<AtomicSDNode>(Node)->getMemOperand(),
11279                                cast<AtomicSDNode>(Node)->getOrdering(),
11280                                cast<AtomicSDNode>(Node)->getSynchScope());
11281   Results.push_back(Swap.getValue(0));
11282   Results.push_back(Swap.getValue(1));
11283 }
11284
11285 static void
11286 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11287                         SelectionDAG &DAG, unsigned NewOp) {
11288   DebugLoc dl = Node->getDebugLoc();
11289   assert (Node->getValueType(0) == MVT::i64 &&
11290           "Only know how to expand i64 atomics");
11291
11292   SDValue Chain = Node->getOperand(0);
11293   SDValue In1 = Node->getOperand(1);
11294   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11295                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11296   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11297                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11298   SDValue Ops[] = { Chain, In1, In2L, In2H };
11299   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11300   SDValue Result =
11301     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11302                             cast<MemSDNode>(Node)->getMemOperand());
11303   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11304   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11305   Results.push_back(Result.getValue(2));
11306 }
11307
11308 /// ReplaceNodeResults - Replace a node with an illegal result type
11309 /// with a new node built out of custom code.
11310 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11311                                            SmallVectorImpl<SDValue>&Results,
11312                                            SelectionDAG &DAG) const {
11313   DebugLoc dl = N->getDebugLoc();
11314   switch (N->getOpcode()) {
11315   default:
11316     llvm_unreachable("Do not know how to custom type legalize this operation!");
11317   case ISD::SIGN_EXTEND_INREG:
11318   case ISD::ADDC:
11319   case ISD::ADDE:
11320   case ISD::SUBC:
11321   case ISD::SUBE:
11322     // We don't want to expand or promote these.
11323     return;
11324   case ISD::FP_TO_SINT:
11325   case ISD::FP_TO_UINT: {
11326     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11327
11328     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11329       return;
11330
11331     std::pair<SDValue,SDValue> Vals =
11332         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11333     SDValue FIST = Vals.first, StackSlot = Vals.second;
11334     if (FIST.getNode() != 0) {
11335       EVT VT = N->getValueType(0);
11336       // Return a load from the stack slot.
11337       if (StackSlot.getNode() != 0)
11338         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11339                                       MachinePointerInfo(),
11340                                       false, false, false, 0));
11341       else
11342         Results.push_back(FIST);
11343     }
11344     return;
11345   }
11346   case ISD::READCYCLECOUNTER: {
11347     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11348     SDValue TheChain = N->getOperand(0);
11349     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11350     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11351                                      rd.getValue(1));
11352     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11353                                      eax.getValue(2));
11354     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11355     SDValue Ops[] = { eax, edx };
11356     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11357     Results.push_back(edx.getValue(1));
11358     return;
11359   }
11360   case ISD::ATOMIC_CMP_SWAP: {
11361     EVT T = N->getValueType(0);
11362     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11363     bool Regs64bit = T == MVT::i128;
11364     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11365     SDValue cpInL, cpInH;
11366     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11367                         DAG.getConstant(0, HalfT));
11368     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11369                         DAG.getConstant(1, HalfT));
11370     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11371                              Regs64bit ? X86::RAX : X86::EAX,
11372                              cpInL, SDValue());
11373     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11374                              Regs64bit ? X86::RDX : X86::EDX,
11375                              cpInH, cpInL.getValue(1));
11376     SDValue swapInL, swapInH;
11377     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11378                           DAG.getConstant(0, HalfT));
11379     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11380                           DAG.getConstant(1, HalfT));
11381     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11382                                Regs64bit ? X86::RBX : X86::EBX,
11383                                swapInL, cpInH.getValue(1));
11384     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11385                                Regs64bit ? X86::RCX : X86::ECX,
11386                                swapInH, swapInL.getValue(1));
11387     SDValue Ops[] = { swapInH.getValue(0),
11388                       N->getOperand(1),
11389                       swapInH.getValue(1) };
11390     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11391     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11392     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11393                                   X86ISD::LCMPXCHG8_DAG;
11394     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11395                                              Ops, 3, T, MMO);
11396     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11397                                         Regs64bit ? X86::RAX : X86::EAX,
11398                                         HalfT, Result.getValue(1));
11399     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11400                                         Regs64bit ? X86::RDX : X86::EDX,
11401                                         HalfT, cpOutL.getValue(2));
11402     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11403     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11404     Results.push_back(cpOutH.getValue(1));
11405     return;
11406   }
11407   case ISD::ATOMIC_LOAD_ADD:
11408   case ISD::ATOMIC_LOAD_AND:
11409   case ISD::ATOMIC_LOAD_NAND:
11410   case ISD::ATOMIC_LOAD_OR:
11411   case ISD::ATOMIC_LOAD_SUB:
11412   case ISD::ATOMIC_LOAD_XOR:
11413   case ISD::ATOMIC_SWAP: {
11414     unsigned Opc;
11415     switch (N->getOpcode()) {
11416     default: llvm_unreachable("Unexpected opcode");
11417     case ISD::ATOMIC_LOAD_ADD:
11418       Opc = X86ISD::ATOMADD64_DAG;
11419       break;
11420     case ISD::ATOMIC_LOAD_AND:
11421       Opc = X86ISD::ATOMAND64_DAG;
11422       break;
11423     case ISD::ATOMIC_LOAD_NAND:
11424       Opc = X86ISD::ATOMNAND64_DAG;
11425       break;
11426     case ISD::ATOMIC_LOAD_OR:
11427       Opc = X86ISD::ATOMOR64_DAG;
11428       break;
11429     case ISD::ATOMIC_LOAD_SUB:
11430       Opc = X86ISD::ATOMSUB64_DAG;
11431       break;
11432     case ISD::ATOMIC_LOAD_XOR:
11433       Opc = X86ISD::ATOMXOR64_DAG;
11434       break;
11435     case ISD::ATOMIC_SWAP:
11436       Opc = X86ISD::ATOMSWAP64_DAG;
11437       break;
11438     }
11439     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11440     return;
11441   }
11442   case ISD::ATOMIC_LOAD:
11443     ReplaceATOMIC_LOAD(N, Results, DAG);
11444   }
11445 }
11446
11447 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11448   switch (Opcode) {
11449   default: return NULL;
11450   case X86ISD::BSF:                return "X86ISD::BSF";
11451   case X86ISD::BSR:                return "X86ISD::BSR";
11452   case X86ISD::SHLD:               return "X86ISD::SHLD";
11453   case X86ISD::SHRD:               return "X86ISD::SHRD";
11454   case X86ISD::FAND:               return "X86ISD::FAND";
11455   case X86ISD::FOR:                return "X86ISD::FOR";
11456   case X86ISD::FXOR:               return "X86ISD::FXOR";
11457   case X86ISD::FSRL:               return "X86ISD::FSRL";
11458   case X86ISD::FILD:               return "X86ISD::FILD";
11459   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11460   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11461   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11462   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11463   case X86ISD::FLD:                return "X86ISD::FLD";
11464   case X86ISD::FST:                return "X86ISD::FST";
11465   case X86ISD::CALL:               return "X86ISD::CALL";
11466   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11467   case X86ISD::BT:                 return "X86ISD::BT";
11468   case X86ISD::CMP:                return "X86ISD::CMP";
11469   case X86ISD::COMI:               return "X86ISD::COMI";
11470   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11471   case X86ISD::SETCC:              return "X86ISD::SETCC";
11472   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11473   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11474   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11475   case X86ISD::CMOV:               return "X86ISD::CMOV";
11476   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11477   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11478   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11479   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11480   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11481   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11482   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11483   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11484   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11485   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11486   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11487   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11488   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11489   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11490   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11491   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11492   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11493   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11494   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11495   case X86ISD::HADD:               return "X86ISD::HADD";
11496   case X86ISD::HSUB:               return "X86ISD::HSUB";
11497   case X86ISD::FHADD:              return "X86ISD::FHADD";
11498   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11499   case X86ISD::FMAX:               return "X86ISD::FMAX";
11500   case X86ISD::FMIN:               return "X86ISD::FMIN";
11501   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11502   case X86ISD::FMINC:              return "X86ISD::FMINC";
11503   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11504   case X86ISD::FRCP:               return "X86ISD::FRCP";
11505   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11506   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11507   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11508   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11509   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11510   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11511   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11512   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11513   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11514   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11515   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11516   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11517   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11518   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11519   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11520   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11521   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11522   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11523   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11524   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11525   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11526   case X86ISD::VSHL:               return "X86ISD::VSHL";
11527   case X86ISD::VSRL:               return "X86ISD::VSRL";
11528   case X86ISD::VSRA:               return "X86ISD::VSRA";
11529   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11530   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11531   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11532   case X86ISD::CMPP:               return "X86ISD::CMPP";
11533   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11534   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11535   case X86ISD::ADD:                return "X86ISD::ADD";
11536   case X86ISD::SUB:                return "X86ISD::SUB";
11537   case X86ISD::ADC:                return "X86ISD::ADC";
11538   case X86ISD::SBB:                return "X86ISD::SBB";
11539   case X86ISD::SMUL:               return "X86ISD::SMUL";
11540   case X86ISD::UMUL:               return "X86ISD::UMUL";
11541   case X86ISD::INC:                return "X86ISD::INC";
11542   case X86ISD::DEC:                return "X86ISD::DEC";
11543   case X86ISD::OR:                 return "X86ISD::OR";
11544   case X86ISD::XOR:                return "X86ISD::XOR";
11545   case X86ISD::AND:                return "X86ISD::AND";
11546   case X86ISD::ANDN:               return "X86ISD::ANDN";
11547   case X86ISD::BLSI:               return "X86ISD::BLSI";
11548   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11549   case X86ISD::BLSR:               return "X86ISD::BLSR";
11550   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11551   case X86ISD::PTEST:              return "X86ISD::PTEST";
11552   case X86ISD::TESTP:              return "X86ISD::TESTP";
11553   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11554   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11555   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11556   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11557   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11558   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11559   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11560   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11561   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11562   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11563   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11564   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11565   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11566   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11567   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11568   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11569   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11570   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11571   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11572   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11573   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11574   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11575   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11576   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11577   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11578   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11579   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11580   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11581   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11582   case X86ISD::SAHF:               return "X86ISD::SAHF";
11583   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11584   case X86ISD::FMADD:              return "X86ISD::FMADD";
11585   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11586   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11587   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11588   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11589   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11590   }
11591 }
11592
11593 // isLegalAddressingMode - Return true if the addressing mode represented
11594 // by AM is legal for this target, for a load/store of the specified type.
11595 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11596                                               Type *Ty) const {
11597   // X86 supports extremely general addressing modes.
11598   CodeModel::Model M = getTargetMachine().getCodeModel();
11599   Reloc::Model R = getTargetMachine().getRelocationModel();
11600
11601   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11602   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11603     return false;
11604
11605   if (AM.BaseGV) {
11606     unsigned GVFlags =
11607       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11608
11609     // If a reference to this global requires an extra load, we can't fold it.
11610     if (isGlobalStubReference(GVFlags))
11611       return false;
11612
11613     // If BaseGV requires a register for the PIC base, we cannot also have a
11614     // BaseReg specified.
11615     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11616       return false;
11617
11618     // If lower 4G is not available, then we must use rip-relative addressing.
11619     if ((M != CodeModel::Small || R != Reloc::Static) &&
11620         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11621       return false;
11622   }
11623
11624   switch (AM.Scale) {
11625   case 0:
11626   case 1:
11627   case 2:
11628   case 4:
11629   case 8:
11630     // These scales always work.
11631     break;
11632   case 3:
11633   case 5:
11634   case 9:
11635     // These scales are formed with basereg+scalereg.  Only accept if there is
11636     // no basereg yet.
11637     if (AM.HasBaseReg)
11638       return false;
11639     break;
11640   default:  // Other stuff never works.
11641     return false;
11642   }
11643
11644   return true;
11645 }
11646
11647
11648 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11649   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11650     return false;
11651   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11652   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11653   if (NumBits1 <= NumBits2)
11654     return false;
11655   return true;
11656 }
11657
11658 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11659   return Imm == (int32_t)Imm;
11660 }
11661
11662 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11663   // Can also use sub to handle negated immediates.
11664   return Imm == (int32_t)Imm;
11665 }
11666
11667 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11668   if (!VT1.isInteger() || !VT2.isInteger())
11669     return false;
11670   unsigned NumBits1 = VT1.getSizeInBits();
11671   unsigned NumBits2 = VT2.getSizeInBits();
11672   if (NumBits1 <= NumBits2)
11673     return false;
11674   return true;
11675 }
11676
11677 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11678   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11679   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11680 }
11681
11682 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11683   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11684   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11685 }
11686
11687 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11688   // i16 instructions are longer (0x66 prefix) and potentially slower.
11689   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11690 }
11691
11692 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11693 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11694 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11695 /// are assumed to be legal.
11696 bool
11697 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11698                                       EVT VT) const {
11699   // Very little shuffling can be done for 64-bit vectors right now.
11700   if (VT.getSizeInBits() == 64)
11701     return false;
11702
11703   // FIXME: pshufb, blends, shifts.
11704   return (VT.getVectorNumElements() == 2 ||
11705           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11706           isMOVLMask(M, VT) ||
11707           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11708           isPSHUFDMask(M, VT) ||
11709           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11710           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11711           isPALIGNRMask(M, VT, Subtarget) ||
11712           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11713           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11714           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11715           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11716 }
11717
11718 bool
11719 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11720                                           EVT VT) const {
11721   unsigned NumElts = VT.getVectorNumElements();
11722   // FIXME: This collection of masks seems suspect.
11723   if (NumElts == 2)
11724     return true;
11725   if (NumElts == 4 && VT.is128BitVector()) {
11726     return (isMOVLMask(Mask, VT)  ||
11727             isCommutedMOVLMask(Mask, VT, true) ||
11728             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11729             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11730   }
11731   return false;
11732 }
11733
11734 //===----------------------------------------------------------------------===//
11735 //                           X86 Scheduler Hooks
11736 //===----------------------------------------------------------------------===//
11737
11738 // private utility function
11739 MachineBasicBlock *
11740 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11741                                                        MachineBasicBlock *MBB,
11742                                                        unsigned regOpc,
11743                                                        unsigned immOpc,
11744                                                        unsigned LoadOpc,
11745                                                        unsigned CXchgOpc,
11746                                                        unsigned notOpc,
11747                                                        unsigned EAXreg,
11748                                                  const TargetRegisterClass *RC,
11749                                                        bool Invert) const {
11750   // For the atomic bitwise operator, we generate
11751   //   thisMBB:
11752   //   newMBB:
11753   //     ld  t1 = [bitinstr.addr]
11754   //     op  t2 = t1, [bitinstr.val]
11755   //     not t3 = t2  (if Invert)
11756   //     mov EAX = t1
11757   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11758   //     bz  newMBB
11759   //     fallthrough -->nextMBB
11760   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11761   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11762   MachineFunction::iterator MBBIter = MBB;
11763   ++MBBIter;
11764
11765   /// First build the CFG
11766   MachineFunction *F = MBB->getParent();
11767   MachineBasicBlock *thisMBB = MBB;
11768   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11769   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11770   F->insert(MBBIter, newMBB);
11771   F->insert(MBBIter, nextMBB);
11772
11773   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11774   nextMBB->splice(nextMBB->begin(), thisMBB,
11775                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11776                   thisMBB->end());
11777   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11778
11779   // Update thisMBB to fall through to newMBB
11780   thisMBB->addSuccessor(newMBB);
11781
11782   // newMBB jumps to itself and fall through to nextMBB
11783   newMBB->addSuccessor(nextMBB);
11784   newMBB->addSuccessor(newMBB);
11785
11786   // Insert instructions into newMBB based on incoming instruction
11787   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11788          "unexpected number of operands");
11789   DebugLoc dl = bInstr->getDebugLoc();
11790   MachineOperand& destOper = bInstr->getOperand(0);
11791   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11792   int numArgs = bInstr->getNumOperands() - 1;
11793   for (int i=0; i < numArgs; ++i)
11794     argOpers[i] = &bInstr->getOperand(i+1);
11795
11796   // x86 address has 4 operands: base, index, scale, and displacement
11797   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11798   int valArgIndx = lastAddrIndx + 1;
11799
11800   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11801   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11802   for (int i=0; i <= lastAddrIndx; ++i)
11803     (*MIB).addOperand(*argOpers[i]);
11804
11805   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11806   assert((argOpers[valArgIndx]->isReg() ||
11807           argOpers[valArgIndx]->isImm()) &&
11808          "invalid operand");
11809   if (argOpers[valArgIndx]->isReg())
11810     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11811   else
11812     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11813   MIB.addReg(t1);
11814   (*MIB).addOperand(*argOpers[valArgIndx]);
11815
11816   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11817   if (Invert) {
11818     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11819   }
11820   else
11821     t3 = t2;
11822
11823   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11824   MIB.addReg(t1);
11825
11826   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11827   for (int i=0; i <= lastAddrIndx; ++i)
11828     (*MIB).addOperand(*argOpers[i]);
11829   MIB.addReg(t3);
11830   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11831   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11832                     bInstr->memoperands_end());
11833
11834   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11835   MIB.addReg(EAXreg);
11836
11837   // insert branch
11838   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11839
11840   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11841   return nextMBB;
11842 }
11843
11844 // private utility function:  64 bit atomics on 32 bit host.
11845 MachineBasicBlock *
11846 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11847                                                        MachineBasicBlock *MBB,
11848                                                        unsigned regOpcL,
11849                                                        unsigned regOpcH,
11850                                                        unsigned immOpcL,
11851                                                        unsigned immOpcH,
11852                                                        bool Invert) const {
11853   // For the atomic bitwise operator, we generate
11854   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11855   //     ld t1,t2 = [bitinstr.addr]
11856   //   newMBB:
11857   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11858   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11859   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11860   //     neg t7, t8 < t5, t6  (if Invert)
11861   //     mov ECX, EBX <- t5, t6
11862   //     mov EAX, EDX <- t1, t2
11863   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11864   //     mov t3, t4 <- EAX, EDX
11865   //     bz  newMBB
11866   //     result in out1, out2
11867   //     fallthrough -->nextMBB
11868
11869   const TargetRegisterClass *RC = &X86::GR32RegClass;
11870   const unsigned LoadOpc = X86::MOV32rm;
11871   const unsigned NotOpc = X86::NOT32r;
11872   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11873   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11874   MachineFunction::iterator MBBIter = MBB;
11875   ++MBBIter;
11876
11877   /// First build the CFG
11878   MachineFunction *F = MBB->getParent();
11879   MachineBasicBlock *thisMBB = MBB;
11880   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11881   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11882   F->insert(MBBIter, newMBB);
11883   F->insert(MBBIter, nextMBB);
11884
11885   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11886   nextMBB->splice(nextMBB->begin(), thisMBB,
11887                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11888                   thisMBB->end());
11889   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11890
11891   // Update thisMBB to fall through to newMBB
11892   thisMBB->addSuccessor(newMBB);
11893
11894   // newMBB jumps to itself and fall through to nextMBB
11895   newMBB->addSuccessor(nextMBB);
11896   newMBB->addSuccessor(newMBB);
11897
11898   DebugLoc dl = bInstr->getDebugLoc();
11899   // Insert instructions into newMBB based on incoming instruction
11900   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11901   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11902          "unexpected number of operands");
11903   MachineOperand& dest1Oper = bInstr->getOperand(0);
11904   MachineOperand& dest2Oper = bInstr->getOperand(1);
11905   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11906   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11907     argOpers[i] = &bInstr->getOperand(i+2);
11908
11909     // We use some of the operands multiple times, so conservatively just
11910     // clear any kill flags that might be present.
11911     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11912       argOpers[i]->setIsKill(false);
11913   }
11914
11915   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11916   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11917
11918   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11919   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11920   for (int i=0; i <= lastAddrIndx; ++i)
11921     (*MIB).addOperand(*argOpers[i]);
11922   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11923   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11924   // add 4 to displacement.
11925   for (int i=0; i <= lastAddrIndx-2; ++i)
11926     (*MIB).addOperand(*argOpers[i]);
11927   MachineOperand newOp3 = *(argOpers[3]);
11928   if (newOp3.isImm())
11929     newOp3.setImm(newOp3.getImm()+4);
11930   else
11931     newOp3.setOffset(newOp3.getOffset()+4);
11932   (*MIB).addOperand(newOp3);
11933   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11934
11935   // t3/4 are defined later, at the bottom of the loop
11936   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11937   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11938   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11939     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11940   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11941     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11942
11943   // The subsequent operations should be using the destination registers of
11944   // the PHI instructions.
11945   t1 = dest1Oper.getReg();
11946   t2 = dest2Oper.getReg();
11947
11948   int valArgIndx = lastAddrIndx + 1;
11949   assert((argOpers[valArgIndx]->isReg() ||
11950           argOpers[valArgIndx]->isImm()) &&
11951          "invalid operand");
11952   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11953   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11954   if (argOpers[valArgIndx]->isReg())
11955     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11956   else
11957     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11958   if (regOpcL != X86::MOV32rr)
11959     MIB.addReg(t1);
11960   (*MIB).addOperand(*argOpers[valArgIndx]);
11961   assert(argOpers[valArgIndx + 1]->isReg() ==
11962          argOpers[valArgIndx]->isReg());
11963   assert(argOpers[valArgIndx + 1]->isImm() ==
11964          argOpers[valArgIndx]->isImm());
11965   if (argOpers[valArgIndx + 1]->isReg())
11966     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11967   else
11968     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11969   if (regOpcH != X86::MOV32rr)
11970     MIB.addReg(t2);
11971   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11972
11973   unsigned t7, t8;
11974   if (Invert) {
11975     t7 = F->getRegInfo().createVirtualRegister(RC);
11976     t8 = F->getRegInfo().createVirtualRegister(RC);
11977     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11978     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11979   } else {
11980     t7 = t5;
11981     t8 = t6;
11982   }
11983
11984   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11985   MIB.addReg(t1);
11986   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11987   MIB.addReg(t2);
11988
11989   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11990   MIB.addReg(t7);
11991   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11992   MIB.addReg(t8);
11993
11994   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11995   for (int i=0; i <= lastAddrIndx; ++i)
11996     (*MIB).addOperand(*argOpers[i]);
11997
11998   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11999   (*MIB).setMemRefs(bInstr->memoperands_begin(),
12000                     bInstr->memoperands_end());
12001
12002   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
12003   MIB.addReg(X86::EAX);
12004   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
12005   MIB.addReg(X86::EDX);
12006
12007   // insert branch
12008   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12009
12010   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
12011   return nextMBB;
12012 }
12013
12014 // private utility function
12015 MachineBasicBlock *
12016 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
12017                                                       MachineBasicBlock *MBB,
12018                                                       unsigned cmovOpc) const {
12019   // For the atomic min/max operator, we generate
12020   //   thisMBB:
12021   //   newMBB:
12022   //     ld t1 = [min/max.addr]
12023   //     mov t2 = [min/max.val]
12024   //     cmp  t1, t2
12025   //     cmov[cond] t2 = t1
12026   //     mov EAX = t1
12027   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
12028   //     bz   newMBB
12029   //     fallthrough -->nextMBB
12030   //
12031   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12032   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12033   MachineFunction::iterator MBBIter = MBB;
12034   ++MBBIter;
12035
12036   /// First build the CFG
12037   MachineFunction *F = MBB->getParent();
12038   MachineBasicBlock *thisMBB = MBB;
12039   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12040   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12041   F->insert(MBBIter, newMBB);
12042   F->insert(MBBIter, nextMBB);
12043
12044   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12045   nextMBB->splice(nextMBB->begin(), thisMBB,
12046                   llvm::next(MachineBasicBlock::iterator(mInstr)),
12047                   thisMBB->end());
12048   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12049
12050   // Update thisMBB to fall through to newMBB
12051   thisMBB->addSuccessor(newMBB);
12052
12053   // newMBB jumps to newMBB and fall through to nextMBB
12054   newMBB->addSuccessor(nextMBB);
12055   newMBB->addSuccessor(newMBB);
12056
12057   DebugLoc dl = mInstr->getDebugLoc();
12058   // Insert instructions into newMBB based on incoming instruction
12059   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
12060          "unexpected number of operands");
12061   MachineOperand& destOper = mInstr->getOperand(0);
12062   MachineOperand* argOpers[2 + X86::AddrNumOperands];
12063   int numArgs = mInstr->getNumOperands() - 1;
12064   for (int i=0; i < numArgs; ++i)
12065     argOpers[i] = &mInstr->getOperand(i+1);
12066
12067   // x86 address has 4 operands: base, index, scale, and displacement
12068   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12069   int valArgIndx = lastAddrIndx + 1;
12070
12071   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12072   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
12073   for (int i=0; i <= lastAddrIndx; ++i)
12074     (*MIB).addOperand(*argOpers[i]);
12075
12076   // We only support register and immediate values
12077   assert((argOpers[valArgIndx]->isReg() ||
12078           argOpers[valArgIndx]->isImm()) &&
12079          "invalid operand");
12080
12081   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12082   if (argOpers[valArgIndx]->isReg())
12083     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
12084   else
12085     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
12086   (*MIB).addOperand(*argOpers[valArgIndx]);
12087
12088   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12089   MIB.addReg(t1);
12090
12091   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
12092   MIB.addReg(t1);
12093   MIB.addReg(t2);
12094
12095   // Generate movc
12096   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12097   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
12098   MIB.addReg(t2);
12099   MIB.addReg(t1);
12100
12101   // Cmp and exchange if none has modified the memory location
12102   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
12103   for (int i=0; i <= lastAddrIndx; ++i)
12104     (*MIB).addOperand(*argOpers[i]);
12105   MIB.addReg(t3);
12106   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12107   (*MIB).setMemRefs(mInstr->memoperands_begin(),
12108                     mInstr->memoperands_end());
12109
12110   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12111   MIB.addReg(X86::EAX);
12112
12113   // insert branch
12114   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12115
12116   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
12117   return nextMBB;
12118 }
12119
12120 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12121 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12122 // in the .td file.
12123 MachineBasicBlock *
12124 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12125                             unsigned numArgs, bool memArg) const {
12126   assert(Subtarget->hasSSE42() &&
12127          "Target must have SSE4.2 or AVX features enabled");
12128
12129   DebugLoc dl = MI->getDebugLoc();
12130   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12131   unsigned Opc;
12132   if (!Subtarget->hasAVX()) {
12133     if (memArg)
12134       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12135     else
12136       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12137   } else {
12138     if (memArg)
12139       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12140     else
12141       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12142   }
12143
12144   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12145   for (unsigned i = 0; i < numArgs; ++i) {
12146     MachineOperand &Op = MI->getOperand(i+1);
12147     if (!(Op.isReg() && Op.isImplicit()))
12148       MIB.addOperand(Op);
12149   }
12150   BuildMI(*BB, MI, dl,
12151     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12152     .addReg(X86::XMM0);
12153
12154   MI->eraseFromParent();
12155   return BB;
12156 }
12157
12158 MachineBasicBlock *
12159 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12160   DebugLoc dl = MI->getDebugLoc();
12161   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12162
12163   // Address into RAX/EAX, other two args into ECX, EDX.
12164   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12165   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12166   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12167   for (int i = 0; i < X86::AddrNumOperands; ++i)
12168     MIB.addOperand(MI->getOperand(i));
12169
12170   unsigned ValOps = X86::AddrNumOperands;
12171   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12172     .addReg(MI->getOperand(ValOps).getReg());
12173   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12174     .addReg(MI->getOperand(ValOps+1).getReg());
12175
12176   // The instruction doesn't actually take any operands though.
12177   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12178
12179   MI->eraseFromParent(); // The pseudo is gone now.
12180   return BB;
12181 }
12182
12183 MachineBasicBlock *
12184 X86TargetLowering::EmitVAARG64WithCustomInserter(
12185                    MachineInstr *MI,
12186                    MachineBasicBlock *MBB) const {
12187   // Emit va_arg instruction on X86-64.
12188
12189   // Operands to this pseudo-instruction:
12190   // 0  ) Output        : destination address (reg)
12191   // 1-5) Input         : va_list address (addr, i64mem)
12192   // 6  ) ArgSize       : Size (in bytes) of vararg type
12193   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12194   // 8  ) Align         : Alignment of type
12195   // 9  ) EFLAGS (implicit-def)
12196
12197   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12198   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12199
12200   unsigned DestReg = MI->getOperand(0).getReg();
12201   MachineOperand &Base = MI->getOperand(1);
12202   MachineOperand &Scale = MI->getOperand(2);
12203   MachineOperand &Index = MI->getOperand(3);
12204   MachineOperand &Disp = MI->getOperand(4);
12205   MachineOperand &Segment = MI->getOperand(5);
12206   unsigned ArgSize = MI->getOperand(6).getImm();
12207   unsigned ArgMode = MI->getOperand(7).getImm();
12208   unsigned Align = MI->getOperand(8).getImm();
12209
12210   // Memory Reference
12211   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12212   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12213   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12214
12215   // Machine Information
12216   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12217   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12218   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12219   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12220   DebugLoc DL = MI->getDebugLoc();
12221
12222   // struct va_list {
12223   //   i32   gp_offset
12224   //   i32   fp_offset
12225   //   i64   overflow_area (address)
12226   //   i64   reg_save_area (address)
12227   // }
12228   // sizeof(va_list) = 24
12229   // alignment(va_list) = 8
12230
12231   unsigned TotalNumIntRegs = 6;
12232   unsigned TotalNumXMMRegs = 8;
12233   bool UseGPOffset = (ArgMode == 1);
12234   bool UseFPOffset = (ArgMode == 2);
12235   unsigned MaxOffset = TotalNumIntRegs * 8 +
12236                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12237
12238   /* Align ArgSize to a multiple of 8 */
12239   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12240   bool NeedsAlign = (Align > 8);
12241
12242   MachineBasicBlock *thisMBB = MBB;
12243   MachineBasicBlock *overflowMBB;
12244   MachineBasicBlock *offsetMBB;
12245   MachineBasicBlock *endMBB;
12246
12247   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12248   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12249   unsigned OffsetReg = 0;
12250
12251   if (!UseGPOffset && !UseFPOffset) {
12252     // If we only pull from the overflow region, we don't create a branch.
12253     // We don't need to alter control flow.
12254     OffsetDestReg = 0; // unused
12255     OverflowDestReg = DestReg;
12256
12257     offsetMBB = NULL;
12258     overflowMBB = thisMBB;
12259     endMBB = thisMBB;
12260   } else {
12261     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12262     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12263     // If not, pull from overflow_area. (branch to overflowMBB)
12264     //
12265     //       thisMBB
12266     //         |     .
12267     //         |        .
12268     //     offsetMBB   overflowMBB
12269     //         |        .
12270     //         |     .
12271     //        endMBB
12272
12273     // Registers for the PHI in endMBB
12274     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12275     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12276
12277     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12278     MachineFunction *MF = MBB->getParent();
12279     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12280     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12281     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12282
12283     MachineFunction::iterator MBBIter = MBB;
12284     ++MBBIter;
12285
12286     // Insert the new basic blocks
12287     MF->insert(MBBIter, offsetMBB);
12288     MF->insert(MBBIter, overflowMBB);
12289     MF->insert(MBBIter, endMBB);
12290
12291     // Transfer the remainder of MBB and its successor edges to endMBB.
12292     endMBB->splice(endMBB->begin(), thisMBB,
12293                     llvm::next(MachineBasicBlock::iterator(MI)),
12294                     thisMBB->end());
12295     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12296
12297     // Make offsetMBB and overflowMBB successors of thisMBB
12298     thisMBB->addSuccessor(offsetMBB);
12299     thisMBB->addSuccessor(overflowMBB);
12300
12301     // endMBB is a successor of both offsetMBB and overflowMBB
12302     offsetMBB->addSuccessor(endMBB);
12303     overflowMBB->addSuccessor(endMBB);
12304
12305     // Load the offset value into a register
12306     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12307     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12308       .addOperand(Base)
12309       .addOperand(Scale)
12310       .addOperand(Index)
12311       .addDisp(Disp, UseFPOffset ? 4 : 0)
12312       .addOperand(Segment)
12313       .setMemRefs(MMOBegin, MMOEnd);
12314
12315     // Check if there is enough room left to pull this argument.
12316     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12317       .addReg(OffsetReg)
12318       .addImm(MaxOffset + 8 - ArgSizeA8);
12319
12320     // Branch to "overflowMBB" if offset >= max
12321     // Fall through to "offsetMBB" otherwise
12322     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12323       .addMBB(overflowMBB);
12324   }
12325
12326   // In offsetMBB, emit code to use the reg_save_area.
12327   if (offsetMBB) {
12328     assert(OffsetReg != 0);
12329
12330     // Read the reg_save_area address.
12331     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12332     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12333       .addOperand(Base)
12334       .addOperand(Scale)
12335       .addOperand(Index)
12336       .addDisp(Disp, 16)
12337       .addOperand(Segment)
12338       .setMemRefs(MMOBegin, MMOEnd);
12339
12340     // Zero-extend the offset
12341     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12342       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12343         .addImm(0)
12344         .addReg(OffsetReg)
12345         .addImm(X86::sub_32bit);
12346
12347     // Add the offset to the reg_save_area to get the final address.
12348     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12349       .addReg(OffsetReg64)
12350       .addReg(RegSaveReg);
12351
12352     // Compute the offset for the next argument
12353     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12354     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12355       .addReg(OffsetReg)
12356       .addImm(UseFPOffset ? 16 : 8);
12357
12358     // Store it back into the va_list.
12359     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12360       .addOperand(Base)
12361       .addOperand(Scale)
12362       .addOperand(Index)
12363       .addDisp(Disp, UseFPOffset ? 4 : 0)
12364       .addOperand(Segment)
12365       .addReg(NextOffsetReg)
12366       .setMemRefs(MMOBegin, MMOEnd);
12367
12368     // Jump to endMBB
12369     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12370       .addMBB(endMBB);
12371   }
12372
12373   //
12374   // Emit code to use overflow area
12375   //
12376
12377   // Load the overflow_area address into a register.
12378   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12379   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12380     .addOperand(Base)
12381     .addOperand(Scale)
12382     .addOperand(Index)
12383     .addDisp(Disp, 8)
12384     .addOperand(Segment)
12385     .setMemRefs(MMOBegin, MMOEnd);
12386
12387   // If we need to align it, do so. Otherwise, just copy the address
12388   // to OverflowDestReg.
12389   if (NeedsAlign) {
12390     // Align the overflow address
12391     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12392     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12393
12394     // aligned_addr = (addr + (align-1)) & ~(align-1)
12395     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12396       .addReg(OverflowAddrReg)
12397       .addImm(Align-1);
12398
12399     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12400       .addReg(TmpReg)
12401       .addImm(~(uint64_t)(Align-1));
12402   } else {
12403     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12404       .addReg(OverflowAddrReg);
12405   }
12406
12407   // Compute the next overflow address after this argument.
12408   // (the overflow address should be kept 8-byte aligned)
12409   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12410   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12411     .addReg(OverflowDestReg)
12412     .addImm(ArgSizeA8);
12413
12414   // Store the new overflow address.
12415   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12416     .addOperand(Base)
12417     .addOperand(Scale)
12418     .addOperand(Index)
12419     .addDisp(Disp, 8)
12420     .addOperand(Segment)
12421     .addReg(NextAddrReg)
12422     .setMemRefs(MMOBegin, MMOEnd);
12423
12424   // If we branched, emit the PHI to the front of endMBB.
12425   if (offsetMBB) {
12426     BuildMI(*endMBB, endMBB->begin(), DL,
12427             TII->get(X86::PHI), DestReg)
12428       .addReg(OffsetDestReg).addMBB(offsetMBB)
12429       .addReg(OverflowDestReg).addMBB(overflowMBB);
12430   }
12431
12432   // Erase the pseudo instruction
12433   MI->eraseFromParent();
12434
12435   return endMBB;
12436 }
12437
12438 MachineBasicBlock *
12439 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12440                                                  MachineInstr *MI,
12441                                                  MachineBasicBlock *MBB) const {
12442   // Emit code to save XMM registers to the stack. The ABI says that the
12443   // number of registers to save is given in %al, so it's theoretically
12444   // possible to do an indirect jump trick to avoid saving all of them,
12445   // however this code takes a simpler approach and just executes all
12446   // of the stores if %al is non-zero. It's less code, and it's probably
12447   // easier on the hardware branch predictor, and stores aren't all that
12448   // expensive anyway.
12449
12450   // Create the new basic blocks. One block contains all the XMM stores,
12451   // and one block is the final destination regardless of whether any
12452   // stores were performed.
12453   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12454   MachineFunction *F = MBB->getParent();
12455   MachineFunction::iterator MBBIter = MBB;
12456   ++MBBIter;
12457   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12458   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12459   F->insert(MBBIter, XMMSaveMBB);
12460   F->insert(MBBIter, EndMBB);
12461
12462   // Transfer the remainder of MBB and its successor edges to EndMBB.
12463   EndMBB->splice(EndMBB->begin(), MBB,
12464                  llvm::next(MachineBasicBlock::iterator(MI)),
12465                  MBB->end());
12466   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12467
12468   // The original block will now fall through to the XMM save block.
12469   MBB->addSuccessor(XMMSaveMBB);
12470   // The XMMSaveMBB will fall through to the end block.
12471   XMMSaveMBB->addSuccessor(EndMBB);
12472
12473   // Now add the instructions.
12474   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12475   DebugLoc DL = MI->getDebugLoc();
12476
12477   unsigned CountReg = MI->getOperand(0).getReg();
12478   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12479   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12480
12481   if (!Subtarget->isTargetWin64()) {
12482     // If %al is 0, branch around the XMM save block.
12483     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12484     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12485     MBB->addSuccessor(EndMBB);
12486   }
12487
12488   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12489   // In the XMM save block, save all the XMM argument registers.
12490   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12491     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12492     MachineMemOperand *MMO =
12493       F->getMachineMemOperand(
12494           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12495         MachineMemOperand::MOStore,
12496         /*Size=*/16, /*Align=*/16);
12497     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12498       .addFrameIndex(RegSaveFrameIndex)
12499       .addImm(/*Scale=*/1)
12500       .addReg(/*IndexReg=*/0)
12501       .addImm(/*Disp=*/Offset)
12502       .addReg(/*Segment=*/0)
12503       .addReg(MI->getOperand(i).getReg())
12504       .addMemOperand(MMO);
12505   }
12506
12507   MI->eraseFromParent();   // The pseudo instruction is gone now.
12508
12509   return EndMBB;
12510 }
12511
12512 // The EFLAGS operand of SelectItr might be missing a kill marker
12513 // because there were multiple uses of EFLAGS, and ISel didn't know
12514 // which to mark. Figure out whether SelectItr should have had a
12515 // kill marker, and set it if it should. Returns the correct kill
12516 // marker value.
12517 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12518                                      MachineBasicBlock* BB,
12519                                      const TargetRegisterInfo* TRI) {
12520   // Scan forward through BB for a use/def of EFLAGS.
12521   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12522   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12523     const MachineInstr& mi = *miI;
12524     if (mi.readsRegister(X86::EFLAGS))
12525       return false;
12526     if (mi.definesRegister(X86::EFLAGS))
12527       break; // Should have kill-flag - update below.
12528   }
12529
12530   // If we hit the end of the block, check whether EFLAGS is live into a
12531   // successor.
12532   if (miI == BB->end()) {
12533     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12534                                           sEnd = BB->succ_end();
12535          sItr != sEnd; ++sItr) {
12536       MachineBasicBlock* succ = *sItr;
12537       if (succ->isLiveIn(X86::EFLAGS))
12538         return false;
12539     }
12540   }
12541
12542   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12543   // out. SelectMI should have a kill flag on EFLAGS.
12544   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12545   return true;
12546 }
12547
12548 MachineBasicBlock *
12549 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12550                                      MachineBasicBlock *BB) const {
12551   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12552   DebugLoc DL = MI->getDebugLoc();
12553
12554   // To "insert" a SELECT_CC instruction, we actually have to insert the
12555   // diamond control-flow pattern.  The incoming instruction knows the
12556   // destination vreg to set, the condition code register to branch on, the
12557   // true/false values to select between, and a branch opcode to use.
12558   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12559   MachineFunction::iterator It = BB;
12560   ++It;
12561
12562   //  thisMBB:
12563   //  ...
12564   //   TrueVal = ...
12565   //   cmpTY ccX, r1, r2
12566   //   bCC copy1MBB
12567   //   fallthrough --> copy0MBB
12568   MachineBasicBlock *thisMBB = BB;
12569   MachineFunction *F = BB->getParent();
12570   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12571   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12572   F->insert(It, copy0MBB);
12573   F->insert(It, sinkMBB);
12574
12575   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12576   // live into the sink and copy blocks.
12577   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12578   if (!MI->killsRegister(X86::EFLAGS) &&
12579       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12580     copy0MBB->addLiveIn(X86::EFLAGS);
12581     sinkMBB->addLiveIn(X86::EFLAGS);
12582   }
12583
12584   // Transfer the remainder of BB and its successor edges to sinkMBB.
12585   sinkMBB->splice(sinkMBB->begin(), BB,
12586                   llvm::next(MachineBasicBlock::iterator(MI)),
12587                   BB->end());
12588   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12589
12590   // Add the true and fallthrough blocks as its successors.
12591   BB->addSuccessor(copy0MBB);
12592   BB->addSuccessor(sinkMBB);
12593
12594   // Create the conditional branch instruction.
12595   unsigned Opc =
12596     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12597   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12598
12599   //  copy0MBB:
12600   //   %FalseValue = ...
12601   //   # fallthrough to sinkMBB
12602   copy0MBB->addSuccessor(sinkMBB);
12603
12604   //  sinkMBB:
12605   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12606   //  ...
12607   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12608           TII->get(X86::PHI), MI->getOperand(0).getReg())
12609     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12610     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12611
12612   MI->eraseFromParent();   // The pseudo instruction is gone now.
12613   return sinkMBB;
12614 }
12615
12616 MachineBasicBlock *
12617 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12618                                         bool Is64Bit) const {
12619   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12620   DebugLoc DL = MI->getDebugLoc();
12621   MachineFunction *MF = BB->getParent();
12622   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12623
12624   assert(getTargetMachine().Options.EnableSegmentedStacks);
12625
12626   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12627   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12628
12629   // BB:
12630   //  ... [Till the alloca]
12631   // If stacklet is not large enough, jump to mallocMBB
12632   //
12633   // bumpMBB:
12634   //  Allocate by subtracting from RSP
12635   //  Jump to continueMBB
12636   //
12637   // mallocMBB:
12638   //  Allocate by call to runtime
12639   //
12640   // continueMBB:
12641   //  ...
12642   //  [rest of original BB]
12643   //
12644
12645   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12646   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12647   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12648
12649   MachineRegisterInfo &MRI = MF->getRegInfo();
12650   const TargetRegisterClass *AddrRegClass =
12651     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12652
12653   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12654     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12655     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12656     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12657     sizeVReg = MI->getOperand(1).getReg(),
12658     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12659
12660   MachineFunction::iterator MBBIter = BB;
12661   ++MBBIter;
12662
12663   MF->insert(MBBIter, bumpMBB);
12664   MF->insert(MBBIter, mallocMBB);
12665   MF->insert(MBBIter, continueMBB);
12666
12667   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12668                       (MachineBasicBlock::iterator(MI)), BB->end());
12669   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12670
12671   // Add code to the main basic block to check if the stack limit has been hit,
12672   // and if so, jump to mallocMBB otherwise to bumpMBB.
12673   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12674   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12675     .addReg(tmpSPVReg).addReg(sizeVReg);
12676   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12677     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12678     .addReg(SPLimitVReg);
12679   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12680
12681   // bumpMBB simply decreases the stack pointer, since we know the current
12682   // stacklet has enough space.
12683   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12684     .addReg(SPLimitVReg);
12685   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12686     .addReg(SPLimitVReg);
12687   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12688
12689   // Calls into a routine in libgcc to allocate more space from the heap.
12690   const uint32_t *RegMask =
12691     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12692   if (Is64Bit) {
12693     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12694       .addReg(sizeVReg);
12695     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12696       .addExternalSymbol("__morestack_allocate_stack_space")
12697       .addRegMask(RegMask)
12698       .addReg(X86::RDI, RegState::Implicit)
12699       .addReg(X86::RAX, RegState::ImplicitDefine);
12700   } else {
12701     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12702       .addImm(12);
12703     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12704     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12705       .addExternalSymbol("__morestack_allocate_stack_space")
12706       .addRegMask(RegMask)
12707       .addReg(X86::EAX, RegState::ImplicitDefine);
12708   }
12709
12710   if (!Is64Bit)
12711     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12712       .addImm(16);
12713
12714   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12715     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12716   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12717
12718   // Set up the CFG correctly.
12719   BB->addSuccessor(bumpMBB);
12720   BB->addSuccessor(mallocMBB);
12721   mallocMBB->addSuccessor(continueMBB);
12722   bumpMBB->addSuccessor(continueMBB);
12723
12724   // Take care of the PHI nodes.
12725   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12726           MI->getOperand(0).getReg())
12727     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12728     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12729
12730   // Delete the original pseudo instruction.
12731   MI->eraseFromParent();
12732
12733   // And we're done.
12734   return continueMBB;
12735 }
12736
12737 MachineBasicBlock *
12738 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12739                                           MachineBasicBlock *BB) const {
12740   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12741   DebugLoc DL = MI->getDebugLoc();
12742
12743   assert(!Subtarget->isTargetEnvMacho());
12744
12745   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12746   // non-trivial part is impdef of ESP.
12747
12748   if (Subtarget->isTargetWin64()) {
12749     if (Subtarget->isTargetCygMing()) {
12750       // ___chkstk(Mingw64):
12751       // Clobbers R10, R11, RAX and EFLAGS.
12752       // Updates RSP.
12753       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12754         .addExternalSymbol("___chkstk")
12755         .addReg(X86::RAX, RegState::Implicit)
12756         .addReg(X86::RSP, RegState::Implicit)
12757         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12758         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12759         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12760     } else {
12761       // __chkstk(MSVCRT): does not update stack pointer.
12762       // Clobbers R10, R11 and EFLAGS.
12763       // FIXME: RAX(allocated size) might be reused and not killed.
12764       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12765         .addExternalSymbol("__chkstk")
12766         .addReg(X86::RAX, RegState::Implicit)
12767         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12768       // RAX has the offset to subtracted from RSP.
12769       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12770         .addReg(X86::RSP)
12771         .addReg(X86::RAX);
12772     }
12773   } else {
12774     const char *StackProbeSymbol =
12775       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12776
12777     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12778       .addExternalSymbol(StackProbeSymbol)
12779       .addReg(X86::EAX, RegState::Implicit)
12780       .addReg(X86::ESP, RegState::Implicit)
12781       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12782       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12783       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12784   }
12785
12786   MI->eraseFromParent();   // The pseudo instruction is gone now.
12787   return BB;
12788 }
12789
12790 MachineBasicBlock *
12791 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12792                                       MachineBasicBlock *BB) const {
12793   // This is pretty easy.  We're taking the value that we received from
12794   // our load from the relocation, sticking it in either RDI (x86-64)
12795   // or EAX and doing an indirect call.  The return value will then
12796   // be in the normal return register.
12797   const X86InstrInfo *TII
12798     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12799   DebugLoc DL = MI->getDebugLoc();
12800   MachineFunction *F = BB->getParent();
12801
12802   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12803   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12804
12805   // Get a register mask for the lowered call.
12806   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12807   // proper register mask.
12808   const uint32_t *RegMask =
12809     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12810   if (Subtarget->is64Bit()) {
12811     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12812                                       TII->get(X86::MOV64rm), X86::RDI)
12813     .addReg(X86::RIP)
12814     .addImm(0).addReg(0)
12815     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12816                       MI->getOperand(3).getTargetFlags())
12817     .addReg(0);
12818     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12819     addDirectMem(MIB, X86::RDI);
12820     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12821   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12822     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12823                                       TII->get(X86::MOV32rm), X86::EAX)
12824     .addReg(0)
12825     .addImm(0).addReg(0)
12826     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12827                       MI->getOperand(3).getTargetFlags())
12828     .addReg(0);
12829     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12830     addDirectMem(MIB, X86::EAX);
12831     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12832   } else {
12833     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12834                                       TII->get(X86::MOV32rm), X86::EAX)
12835     .addReg(TII->getGlobalBaseReg(F))
12836     .addImm(0).addReg(0)
12837     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12838                       MI->getOperand(3).getTargetFlags())
12839     .addReg(0);
12840     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12841     addDirectMem(MIB, X86::EAX);
12842     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12843   }
12844
12845   MI->eraseFromParent(); // The pseudo instruction is gone now.
12846   return BB;
12847 }
12848
12849 MachineBasicBlock *
12850 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12851                                                MachineBasicBlock *BB) const {
12852   switch (MI->getOpcode()) {
12853   default: llvm_unreachable("Unexpected instr type to insert");
12854   case X86::TAILJMPd64:
12855   case X86::TAILJMPr64:
12856   case X86::TAILJMPm64:
12857     llvm_unreachable("TAILJMP64 would not be touched here.");
12858   case X86::TCRETURNdi64:
12859   case X86::TCRETURNri64:
12860   case X86::TCRETURNmi64:
12861     return BB;
12862   case X86::WIN_ALLOCA:
12863     return EmitLoweredWinAlloca(MI, BB);
12864   case X86::SEG_ALLOCA_32:
12865     return EmitLoweredSegAlloca(MI, BB, false);
12866   case X86::SEG_ALLOCA_64:
12867     return EmitLoweredSegAlloca(MI, BB, true);
12868   case X86::TLSCall_32:
12869   case X86::TLSCall_64:
12870     return EmitLoweredTLSCall(MI, BB);
12871   case X86::CMOV_GR8:
12872   case X86::CMOV_FR32:
12873   case X86::CMOV_FR64:
12874   case X86::CMOV_V4F32:
12875   case X86::CMOV_V2F64:
12876   case X86::CMOV_V2I64:
12877   case X86::CMOV_V8F32:
12878   case X86::CMOV_V4F64:
12879   case X86::CMOV_V4I64:
12880   case X86::CMOV_GR16:
12881   case X86::CMOV_GR32:
12882   case X86::CMOV_RFP32:
12883   case X86::CMOV_RFP64:
12884   case X86::CMOV_RFP80:
12885     return EmitLoweredSelect(MI, BB);
12886
12887   case X86::FP32_TO_INT16_IN_MEM:
12888   case X86::FP32_TO_INT32_IN_MEM:
12889   case X86::FP32_TO_INT64_IN_MEM:
12890   case X86::FP64_TO_INT16_IN_MEM:
12891   case X86::FP64_TO_INT32_IN_MEM:
12892   case X86::FP64_TO_INT64_IN_MEM:
12893   case X86::FP80_TO_INT16_IN_MEM:
12894   case X86::FP80_TO_INT32_IN_MEM:
12895   case X86::FP80_TO_INT64_IN_MEM: {
12896     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12897     DebugLoc DL = MI->getDebugLoc();
12898
12899     // Change the floating point control register to use "round towards zero"
12900     // mode when truncating to an integer value.
12901     MachineFunction *F = BB->getParent();
12902     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12903     addFrameReference(BuildMI(*BB, MI, DL,
12904                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12905
12906     // Load the old value of the high byte of the control word...
12907     unsigned OldCW =
12908       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12909     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12910                       CWFrameIdx);
12911
12912     // Set the high part to be round to zero...
12913     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12914       .addImm(0xC7F);
12915
12916     // Reload the modified control word now...
12917     addFrameReference(BuildMI(*BB, MI, DL,
12918                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12919
12920     // Restore the memory image of control word to original value
12921     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12922       .addReg(OldCW);
12923
12924     // Get the X86 opcode to use.
12925     unsigned Opc;
12926     switch (MI->getOpcode()) {
12927     default: llvm_unreachable("illegal opcode!");
12928     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12929     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12930     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12931     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12932     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12933     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12934     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12935     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12936     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12937     }
12938
12939     X86AddressMode AM;
12940     MachineOperand &Op = MI->getOperand(0);
12941     if (Op.isReg()) {
12942       AM.BaseType = X86AddressMode::RegBase;
12943       AM.Base.Reg = Op.getReg();
12944     } else {
12945       AM.BaseType = X86AddressMode::FrameIndexBase;
12946       AM.Base.FrameIndex = Op.getIndex();
12947     }
12948     Op = MI->getOperand(1);
12949     if (Op.isImm())
12950       AM.Scale = Op.getImm();
12951     Op = MI->getOperand(2);
12952     if (Op.isImm())
12953       AM.IndexReg = Op.getImm();
12954     Op = MI->getOperand(3);
12955     if (Op.isGlobal()) {
12956       AM.GV = Op.getGlobal();
12957     } else {
12958       AM.Disp = Op.getImm();
12959     }
12960     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12961                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12962
12963     // Reload the original control word now.
12964     addFrameReference(BuildMI(*BB, MI, DL,
12965                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12966
12967     MI->eraseFromParent();   // The pseudo instruction is gone now.
12968     return BB;
12969   }
12970     // String/text processing lowering.
12971   case X86::PCMPISTRM128REG:
12972   case X86::VPCMPISTRM128REG:
12973   case X86::PCMPISTRM128MEM:
12974   case X86::VPCMPISTRM128MEM:
12975   case X86::PCMPESTRM128REG:
12976   case X86::VPCMPESTRM128REG:
12977   case X86::PCMPESTRM128MEM:
12978   case X86::VPCMPESTRM128MEM: {
12979     unsigned NumArgs;
12980     bool MemArg;
12981     switch (MI->getOpcode()) {
12982     default: llvm_unreachable("illegal opcode!");
12983     case X86::PCMPISTRM128REG:
12984     case X86::VPCMPISTRM128REG:
12985       NumArgs = 3; MemArg = false; break;
12986     case X86::PCMPISTRM128MEM:
12987     case X86::VPCMPISTRM128MEM:
12988       NumArgs = 3; MemArg = true; break;
12989     case X86::PCMPESTRM128REG:
12990     case X86::VPCMPESTRM128REG:
12991       NumArgs = 5; MemArg = false; break;
12992     case X86::PCMPESTRM128MEM:
12993     case X86::VPCMPESTRM128MEM:
12994       NumArgs = 5; MemArg = true; break;
12995     }
12996     return EmitPCMP(MI, BB, NumArgs, MemArg);
12997   }
12998
12999     // Thread synchronization.
13000   case X86::MONITOR:
13001     return EmitMonitor(MI, BB);
13002
13003     // Atomic Lowering.
13004   case X86::ATOMMIN32:
13005   case X86::ATOMMAX32:
13006   case X86::ATOMUMIN32:
13007   case X86::ATOMUMAX32:
13008   case X86::ATOMMIN16:
13009   case X86::ATOMMAX16:
13010   case X86::ATOMUMIN16:
13011   case X86::ATOMUMAX16:
13012   case X86::ATOMMIN64:
13013   case X86::ATOMMAX64:
13014   case X86::ATOMUMIN64:
13015   case X86::ATOMUMAX64: {
13016     unsigned Opc;
13017     switch (MI->getOpcode()) {
13018     default: llvm_unreachable("illegal opcode!");
13019     case X86::ATOMMIN32:  Opc = X86::CMOVL32rr; break;
13020     case X86::ATOMMAX32:  Opc = X86::CMOVG32rr; break;
13021     case X86::ATOMUMIN32: Opc = X86::CMOVB32rr; break;
13022     case X86::ATOMUMAX32: Opc = X86::CMOVA32rr; break;
13023     case X86::ATOMMIN16:  Opc = X86::CMOVL16rr; break;
13024     case X86::ATOMMAX16:  Opc = X86::CMOVG16rr; break;
13025     case X86::ATOMUMIN16: Opc = X86::CMOVB16rr; break;
13026     case X86::ATOMUMAX16: Opc = X86::CMOVA16rr; break;
13027     case X86::ATOMMIN64:  Opc = X86::CMOVL64rr; break;
13028     case X86::ATOMMAX64:  Opc = X86::CMOVG64rr; break;
13029     case X86::ATOMUMIN64: Opc = X86::CMOVB64rr; break;
13030     case X86::ATOMUMAX64: Opc = X86::CMOVA64rr; break;
13031     // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
13032     }
13033     return EmitAtomicMinMaxWithCustomInserter(MI, BB, Opc);
13034   }
13035
13036   case X86::ATOMAND32:
13037   case X86::ATOMOR32:
13038   case X86::ATOMXOR32:
13039   case X86::ATOMNAND32: {
13040     bool Invert = false;
13041     unsigned RegOpc, ImmOpc;
13042     switch (MI->getOpcode()) {
13043     default: llvm_unreachable("illegal opcode!");
13044     case X86::ATOMAND32:
13045       RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; break;
13046     case X86::ATOMOR32:
13047       RegOpc = X86::OR32rr;  ImmOpc = X86::OR32ri; break;
13048     case X86::ATOMXOR32:
13049       RegOpc = X86::XOR32rr; ImmOpc = X86::XOR32ri; break;
13050     case X86::ATOMNAND32:
13051       RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; Invert = true; break;
13052     }
13053     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13054                                                X86::MOV32rm, X86::LCMPXCHG32,
13055                                                X86::NOT32r, X86::EAX,
13056                                                &X86::GR32RegClass, Invert);
13057   }
13058
13059   case X86::ATOMAND16:
13060   case X86::ATOMOR16:
13061   case X86::ATOMXOR16:
13062   case X86::ATOMNAND16: {
13063     bool Invert = false;
13064     unsigned RegOpc, ImmOpc;
13065     switch (MI->getOpcode()) {
13066     default: llvm_unreachable("illegal opcode!");
13067     case X86::ATOMAND16:
13068       RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; break;
13069     case X86::ATOMOR16:
13070       RegOpc = X86::OR16rr;  ImmOpc = X86::OR16ri; break;
13071     case X86::ATOMXOR16:
13072       RegOpc = X86::XOR16rr; ImmOpc = X86::XOR16ri; break;
13073     case X86::ATOMNAND16:
13074       RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; Invert = true; break;
13075     }
13076     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13077                                                X86::MOV16rm, X86::LCMPXCHG16,
13078                                                X86::NOT16r, X86::AX,
13079                                                &X86::GR16RegClass, Invert);
13080   }
13081
13082   case X86::ATOMAND8:
13083   case X86::ATOMOR8:
13084   case X86::ATOMXOR8:
13085   case X86::ATOMNAND8: {
13086     bool Invert = false;
13087     unsigned RegOpc, ImmOpc;
13088     switch (MI->getOpcode()) {
13089     default: llvm_unreachable("illegal opcode!");
13090     case X86::ATOMAND8:
13091       RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; break;
13092     case X86::ATOMOR8:
13093       RegOpc = X86::OR8rr;  ImmOpc = X86::OR8ri; break;
13094     case X86::ATOMXOR8:
13095       RegOpc = X86::XOR8rr; ImmOpc = X86::XOR8ri; break;
13096     case X86::ATOMNAND8:
13097       RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; Invert = true; break;
13098     }
13099     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13100                                                X86::MOV8rm, X86::LCMPXCHG8,
13101                                                X86::NOT8r, X86::AL,
13102                                                &X86::GR8RegClass, Invert);
13103   }
13104
13105   // This group is for 64-bit host.
13106   case X86::ATOMAND64:
13107   case X86::ATOMOR64:
13108   case X86::ATOMXOR64:
13109   case X86::ATOMNAND64: {
13110     bool Invert = false;
13111     unsigned RegOpc, ImmOpc;
13112     switch (MI->getOpcode()) {
13113     default: llvm_unreachable("illegal opcode!");
13114     case X86::ATOMAND64:
13115       RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; break;
13116     case X86::ATOMOR64:
13117       RegOpc = X86::OR64rr;  ImmOpc = X86::OR64ri32; break;
13118     case X86::ATOMXOR64:
13119       RegOpc = X86::XOR64rr; ImmOpc = X86::XOR64ri32; break;
13120     case X86::ATOMNAND64:
13121       RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; Invert = true; break;
13122     }
13123     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13124                                                X86::MOV64rm, X86::LCMPXCHG64,
13125                                                X86::NOT64r, X86::RAX,
13126                                                &X86::GR64RegClass, Invert);
13127   }
13128
13129   // This group does 64-bit operations on a 32-bit host.
13130   case X86::ATOMAND6432:
13131   case X86::ATOMOR6432:
13132   case X86::ATOMXOR6432:
13133   case X86::ATOMNAND6432:
13134   case X86::ATOMADD6432:
13135   case X86::ATOMSUB6432:
13136   case X86::ATOMSWAP6432: {
13137     bool Invert = false;
13138     unsigned RegOpcL, RegOpcH, ImmOpcL, ImmOpcH;
13139     switch (MI->getOpcode()) {
13140     default: llvm_unreachable("illegal opcode!");
13141     case X86::ATOMAND6432:
13142       RegOpcL = RegOpcH = X86::AND32rr;
13143       ImmOpcL = ImmOpcH = X86::AND32ri;
13144       break;
13145     case X86::ATOMOR6432:
13146       RegOpcL = RegOpcH = X86::OR32rr;
13147       ImmOpcL = ImmOpcH = X86::OR32ri;
13148       break;
13149     case X86::ATOMXOR6432:
13150       RegOpcL = RegOpcH = X86::XOR32rr;
13151       ImmOpcL = ImmOpcH = X86::XOR32ri;
13152       break;
13153     case X86::ATOMNAND6432:
13154       RegOpcL = RegOpcH = X86::AND32rr;
13155       ImmOpcL = ImmOpcH = X86::AND32ri;
13156       Invert = true;
13157       break;
13158     case X86::ATOMADD6432:
13159       RegOpcL = X86::ADD32rr; RegOpcH = X86::ADC32rr;
13160       ImmOpcL = X86::ADD32ri; ImmOpcH = X86::ADC32ri;
13161       break;
13162     case X86::ATOMSUB6432:
13163       RegOpcL = X86::SUB32rr; RegOpcH = X86::SBB32rr;
13164       ImmOpcL = X86::SUB32ri; ImmOpcH = X86::SBB32ri;
13165       break;
13166     case X86::ATOMSWAP6432:
13167       RegOpcL = RegOpcH = X86::MOV32rr;
13168       ImmOpcL = ImmOpcH = X86::MOV32ri;
13169       break;
13170     }
13171     return EmitAtomicBit6432WithCustomInserter(MI, BB, RegOpcL, RegOpcH,
13172                                                ImmOpcL, ImmOpcH, Invert);
13173   }
13174
13175   case X86::VASTART_SAVE_XMM_REGS:
13176     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13177
13178   case X86::VAARG_64:
13179     return EmitVAARG64WithCustomInserter(MI, BB);
13180   }
13181 }
13182
13183 //===----------------------------------------------------------------------===//
13184 //                           X86 Optimization Hooks
13185 //===----------------------------------------------------------------------===//
13186
13187 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13188                                                        APInt &KnownZero,
13189                                                        APInt &KnownOne,
13190                                                        const SelectionDAG &DAG,
13191                                                        unsigned Depth) const {
13192   unsigned BitWidth = KnownZero.getBitWidth();
13193   unsigned Opc = Op.getOpcode();
13194   assert((Opc >= ISD::BUILTIN_OP_END ||
13195           Opc == ISD::INTRINSIC_WO_CHAIN ||
13196           Opc == ISD::INTRINSIC_W_CHAIN ||
13197           Opc == ISD::INTRINSIC_VOID) &&
13198          "Should use MaskedValueIsZero if you don't know whether Op"
13199          " is a target node!");
13200
13201   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13202   switch (Opc) {
13203   default: break;
13204   case X86ISD::ADD:
13205   case X86ISD::SUB:
13206   case X86ISD::ADC:
13207   case X86ISD::SBB:
13208   case X86ISD::SMUL:
13209   case X86ISD::UMUL:
13210   case X86ISD::INC:
13211   case X86ISD::DEC:
13212   case X86ISD::OR:
13213   case X86ISD::XOR:
13214   case X86ISD::AND:
13215     // These nodes' second result is a boolean.
13216     if (Op.getResNo() == 0)
13217       break;
13218     // Fallthrough
13219   case X86ISD::SETCC:
13220     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13221     break;
13222   case ISD::INTRINSIC_WO_CHAIN: {
13223     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13224     unsigned NumLoBits = 0;
13225     switch (IntId) {
13226     default: break;
13227     case Intrinsic::x86_sse_movmsk_ps:
13228     case Intrinsic::x86_avx_movmsk_ps_256:
13229     case Intrinsic::x86_sse2_movmsk_pd:
13230     case Intrinsic::x86_avx_movmsk_pd_256:
13231     case Intrinsic::x86_mmx_pmovmskb:
13232     case Intrinsic::x86_sse2_pmovmskb_128:
13233     case Intrinsic::x86_avx2_pmovmskb: {
13234       // High bits of movmskp{s|d}, pmovmskb are known zero.
13235       switch (IntId) {
13236         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13237         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13238         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13239         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13240         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13241         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13242         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13243         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13244       }
13245       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13246       break;
13247     }
13248     }
13249     break;
13250   }
13251   }
13252 }
13253
13254 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13255                                                          unsigned Depth) const {
13256   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13257   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13258     return Op.getValueType().getScalarType().getSizeInBits();
13259
13260   // Fallback case.
13261   return 1;
13262 }
13263
13264 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13265 /// node is a GlobalAddress + offset.
13266 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13267                                        const GlobalValue* &GA,
13268                                        int64_t &Offset) const {
13269   if (N->getOpcode() == X86ISD::Wrapper) {
13270     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13271       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13272       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13273       return true;
13274     }
13275   }
13276   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13277 }
13278
13279 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13280 /// same as extracting the high 128-bit part of 256-bit vector and then
13281 /// inserting the result into the low part of a new 256-bit vector
13282 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13283   EVT VT = SVOp->getValueType(0);
13284   unsigned NumElems = VT.getVectorNumElements();
13285
13286   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13287   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13288     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13289         SVOp->getMaskElt(j) >= 0)
13290       return false;
13291
13292   return true;
13293 }
13294
13295 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13296 /// same as extracting the low 128-bit part of 256-bit vector and then
13297 /// inserting the result into the high part of a new 256-bit vector
13298 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13299   EVT VT = SVOp->getValueType(0);
13300   unsigned NumElems = VT.getVectorNumElements();
13301
13302   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13303   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13304     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13305         SVOp->getMaskElt(j) >= 0)
13306       return false;
13307
13308   return true;
13309 }
13310
13311 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13312 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13313                                         TargetLowering::DAGCombinerInfo &DCI,
13314                                         const X86Subtarget* Subtarget) {
13315   DebugLoc dl = N->getDebugLoc();
13316   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13317   SDValue V1 = SVOp->getOperand(0);
13318   SDValue V2 = SVOp->getOperand(1);
13319   EVT VT = SVOp->getValueType(0);
13320   unsigned NumElems = VT.getVectorNumElements();
13321
13322   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13323       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13324     //
13325     //                   0,0,0,...
13326     //                      |
13327     //    V      UNDEF    BUILD_VECTOR    UNDEF
13328     //     \      /           \           /
13329     //  CONCAT_VECTOR         CONCAT_VECTOR
13330     //         \                  /
13331     //          \                /
13332     //          RESULT: V + zero extended
13333     //
13334     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13335         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13336         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13337       return SDValue();
13338
13339     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13340       return SDValue();
13341
13342     // To match the shuffle mask, the first half of the mask should
13343     // be exactly the first vector, and all the rest a splat with the
13344     // first element of the second one.
13345     for (unsigned i = 0; i != NumElems/2; ++i)
13346       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13347           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13348         return SDValue();
13349
13350     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13351     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13352       if (Ld->hasNUsesOfValue(1, 0)) {
13353         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13354         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13355         SDValue ResNode =
13356           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13357                                   Ld->getMemoryVT(),
13358                                   Ld->getPointerInfo(),
13359                                   Ld->getAlignment(),
13360                                   false/*isVolatile*/, true/*ReadMem*/,
13361                                   false/*WriteMem*/);
13362         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13363       }
13364     }
13365
13366     // Emit a zeroed vector and insert the desired subvector on its
13367     // first half.
13368     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13369     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13370     return DCI.CombineTo(N, InsV);
13371   }
13372
13373   //===--------------------------------------------------------------------===//
13374   // Combine some shuffles into subvector extracts and inserts:
13375   //
13376
13377   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13378   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13379     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13380     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13381     return DCI.CombineTo(N, InsV);
13382   }
13383
13384   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13385   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13386     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13387     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13388     return DCI.CombineTo(N, InsV);
13389   }
13390
13391   return SDValue();
13392 }
13393
13394 /// PerformShuffleCombine - Performs several different shuffle combines.
13395 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13396                                      TargetLowering::DAGCombinerInfo &DCI,
13397                                      const X86Subtarget *Subtarget) {
13398   DebugLoc dl = N->getDebugLoc();
13399   EVT VT = N->getValueType(0);
13400
13401   // Don't create instructions with illegal types after legalize types has run.
13402   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13403   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13404     return SDValue();
13405
13406   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13407   if (Subtarget->hasAVX() && VT.is256BitVector() &&
13408       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13409     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13410
13411   // Only handle 128 wide vector from here on.
13412   if (!VT.is128BitVector())
13413     return SDValue();
13414
13415   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13416   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13417   // consecutive, non-overlapping, and in the right order.
13418   SmallVector<SDValue, 16> Elts;
13419   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13420     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13421
13422   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13423 }
13424
13425
13426 /// DCI, PerformTruncateCombine - Converts truncate operation to
13427 /// a sequence of vector shuffle operations.
13428 /// It is possible when we truncate 256-bit vector to 128-bit vector
13429
13430 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13431                                                   DAGCombinerInfo &DCI) const {
13432   if (!DCI.isBeforeLegalizeOps())
13433     return SDValue();
13434
13435   if (!Subtarget->hasAVX())
13436     return SDValue();
13437
13438   EVT VT = N->getValueType(0);
13439   SDValue Op = N->getOperand(0);
13440   EVT OpVT = Op.getValueType();
13441   DebugLoc dl = N->getDebugLoc();
13442
13443   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13444
13445     if (Subtarget->hasAVX2()) {
13446       // AVX2: v4i64 -> v4i32
13447
13448       // VPERMD
13449       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13450
13451       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13452       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13453                                 ShufMask);
13454
13455       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13456                          DAG.getIntPtrConstant(0));
13457     }
13458
13459     // AVX: v4i64 -> v4i32
13460     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13461                                DAG.getIntPtrConstant(0));
13462
13463     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13464                                DAG.getIntPtrConstant(2));
13465
13466     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13467     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13468
13469     // PSHUFD
13470     static const int ShufMask1[] = {0, 2, 0, 0};
13471
13472     SDValue Undef = DAG.getUNDEF(VT);
13473     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13474     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13475
13476     // MOVLHPS
13477     static const int ShufMask2[] = {0, 1, 4, 5};
13478
13479     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13480   }
13481
13482   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13483
13484     if (Subtarget->hasAVX2()) {
13485       // AVX2: v8i32 -> v8i16
13486
13487       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13488
13489       // PSHUFB
13490       SmallVector<SDValue,32> pshufbMask;
13491       for (unsigned i = 0; i < 2; ++i) {
13492         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13493         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13494         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13495         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13496         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13497         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13498         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13499         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13500         for (unsigned j = 0; j < 8; ++j)
13501           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13502       }
13503       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13504                                &pshufbMask[0], 32);
13505       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13506
13507       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13508
13509       static const int ShufMask[] = {0,  2,  -1,  -1};
13510       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13511                                 &ShufMask[0]);
13512
13513       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13514                        DAG.getIntPtrConstant(0));
13515
13516       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13517     }
13518
13519     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13520                                DAG.getIntPtrConstant(0));
13521
13522     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13523                                DAG.getIntPtrConstant(4));
13524
13525     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13526     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13527
13528     // PSHUFB
13529     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13530                                    -1, -1, -1, -1, -1, -1, -1, -1};
13531
13532     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13533     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13534     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13535
13536     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13537     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13538
13539     // MOVLHPS
13540     static const int ShufMask2[] = {0, 1, 4, 5};
13541
13542     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13543     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13544   }
13545
13546   return SDValue();
13547 }
13548
13549 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13550 /// specific shuffle of a load can be folded into a single element load.
13551 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13552 /// shuffles have been customed lowered so we need to handle those here.
13553 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13554                                          TargetLowering::DAGCombinerInfo &DCI) {
13555   if (DCI.isBeforeLegalizeOps())
13556     return SDValue();
13557
13558   SDValue InVec = N->getOperand(0);
13559   SDValue EltNo = N->getOperand(1);
13560
13561   if (!isa<ConstantSDNode>(EltNo))
13562     return SDValue();
13563
13564   EVT VT = InVec.getValueType();
13565
13566   bool HasShuffleIntoBitcast = false;
13567   if (InVec.getOpcode() == ISD::BITCAST) {
13568     // Don't duplicate a load with other uses.
13569     if (!InVec.hasOneUse())
13570       return SDValue();
13571     EVT BCVT = InVec.getOperand(0).getValueType();
13572     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13573       return SDValue();
13574     InVec = InVec.getOperand(0);
13575     HasShuffleIntoBitcast = true;
13576   }
13577
13578   if (!isTargetShuffle(InVec.getOpcode()))
13579     return SDValue();
13580
13581   // Don't duplicate a load with other uses.
13582   if (!InVec.hasOneUse())
13583     return SDValue();
13584
13585   SmallVector<int, 16> ShuffleMask;
13586   bool UnaryShuffle;
13587   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13588                             UnaryShuffle))
13589     return SDValue();
13590
13591   // Select the input vector, guarding against out of range extract vector.
13592   unsigned NumElems = VT.getVectorNumElements();
13593   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13594   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13595   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13596                                          : InVec.getOperand(1);
13597
13598   // If inputs to shuffle are the same for both ops, then allow 2 uses
13599   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13600
13601   if (LdNode.getOpcode() == ISD::BITCAST) {
13602     // Don't duplicate a load with other uses.
13603     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13604       return SDValue();
13605
13606     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13607     LdNode = LdNode.getOperand(0);
13608   }
13609
13610   if (!ISD::isNormalLoad(LdNode.getNode()))
13611     return SDValue();
13612
13613   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13614
13615   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13616     return SDValue();
13617
13618   if (HasShuffleIntoBitcast) {
13619     // If there's a bitcast before the shuffle, check if the load type and
13620     // alignment is valid.
13621     unsigned Align = LN0->getAlignment();
13622     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13623     unsigned NewAlign = TLI.getTargetData()->
13624       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13625
13626     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13627       return SDValue();
13628   }
13629
13630   // All checks match so transform back to vector_shuffle so that DAG combiner
13631   // can finish the job
13632   DebugLoc dl = N->getDebugLoc();
13633
13634   // Create shuffle node taking into account the case that its a unary shuffle
13635   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13636   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13637                                  InVec.getOperand(0), Shuffle,
13638                                  &ShuffleMask[0]);
13639   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13640   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13641                      EltNo);
13642 }
13643
13644 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13645 /// generation and convert it from being a bunch of shuffles and extracts
13646 /// to a simple store and scalar loads to extract the elements.
13647 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13648                                          TargetLowering::DAGCombinerInfo &DCI) {
13649   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13650   if (NewOp.getNode())
13651     return NewOp;
13652
13653   SDValue InputVector = N->getOperand(0);
13654
13655   // Only operate on vectors of 4 elements, where the alternative shuffling
13656   // gets to be more expensive.
13657   if (InputVector.getValueType() != MVT::v4i32)
13658     return SDValue();
13659
13660   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13661   // single use which is a sign-extend or zero-extend, and all elements are
13662   // used.
13663   SmallVector<SDNode *, 4> Uses;
13664   unsigned ExtractedElements = 0;
13665   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13666        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13667     if (UI.getUse().getResNo() != InputVector.getResNo())
13668       return SDValue();
13669
13670     SDNode *Extract = *UI;
13671     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13672       return SDValue();
13673
13674     if (Extract->getValueType(0) != MVT::i32)
13675       return SDValue();
13676     if (!Extract->hasOneUse())
13677       return SDValue();
13678     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13679         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13680       return SDValue();
13681     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13682       return SDValue();
13683
13684     // Record which element was extracted.
13685     ExtractedElements |=
13686       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13687
13688     Uses.push_back(Extract);
13689   }
13690
13691   // If not all the elements were used, this may not be worthwhile.
13692   if (ExtractedElements != 15)
13693     return SDValue();
13694
13695   // Ok, we've now decided to do the transformation.
13696   DebugLoc dl = InputVector.getDebugLoc();
13697
13698   // Store the value to a temporary stack slot.
13699   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13700   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13701                             MachinePointerInfo(), false, false, 0);
13702
13703   // Replace each use (extract) with a load of the appropriate element.
13704   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13705        UE = Uses.end(); UI != UE; ++UI) {
13706     SDNode *Extract = *UI;
13707
13708     // cOMpute the element's address.
13709     SDValue Idx = Extract->getOperand(1);
13710     unsigned EltSize =
13711         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13712     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13713     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13714     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13715
13716     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13717                                      StackPtr, OffsetVal);
13718
13719     // Load the scalar.
13720     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13721                                      ScalarAddr, MachinePointerInfo(),
13722                                      false, false, false, 0);
13723
13724     // Replace the exact with the load.
13725     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13726   }
13727
13728   // The replacement was made in place; don't return anything.
13729   return SDValue();
13730 }
13731
13732 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13733 /// nodes.
13734 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13735                                     TargetLowering::DAGCombinerInfo &DCI,
13736                                     const X86Subtarget *Subtarget) {
13737   DebugLoc DL = N->getDebugLoc();
13738   SDValue Cond = N->getOperand(0);
13739   // Get the LHS/RHS of the select.
13740   SDValue LHS = N->getOperand(1);
13741   SDValue RHS = N->getOperand(2);
13742   EVT VT = LHS.getValueType();
13743
13744   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13745   // instructions match the semantics of the common C idiom x<y?x:y but not
13746   // x<=y?x:y, because of how they handle negative zero (which can be
13747   // ignored in unsafe-math mode).
13748   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13749       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13750       (Subtarget->hasSSE2() ||
13751        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13752     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13753
13754     unsigned Opcode = 0;
13755     // Check for x CC y ? x : y.
13756     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13757         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13758       switch (CC) {
13759       default: break;
13760       case ISD::SETULT:
13761         // Converting this to a min would handle NaNs incorrectly, and swapping
13762         // the operands would cause it to handle comparisons between positive
13763         // and negative zero incorrectly.
13764         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13765           if (!DAG.getTarget().Options.UnsafeFPMath &&
13766               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13767             break;
13768           std::swap(LHS, RHS);
13769         }
13770         Opcode = X86ISD::FMIN;
13771         break;
13772       case ISD::SETOLE:
13773         // Converting this to a min would handle comparisons between positive
13774         // and negative zero incorrectly.
13775         if (!DAG.getTarget().Options.UnsafeFPMath &&
13776             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13777           break;
13778         Opcode = X86ISD::FMIN;
13779         break;
13780       case ISD::SETULE:
13781         // Converting this to a min would handle both negative zeros and NaNs
13782         // incorrectly, but we can swap the operands to fix both.
13783         std::swap(LHS, RHS);
13784       case ISD::SETOLT:
13785       case ISD::SETLT:
13786       case ISD::SETLE:
13787         Opcode = X86ISD::FMIN;
13788         break;
13789
13790       case ISD::SETOGE:
13791         // Converting this to a max would handle comparisons between positive
13792         // and negative zero incorrectly.
13793         if (!DAG.getTarget().Options.UnsafeFPMath &&
13794             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13795           break;
13796         Opcode = X86ISD::FMAX;
13797         break;
13798       case ISD::SETUGT:
13799         // Converting this to a max would handle NaNs incorrectly, and swapping
13800         // the operands would cause it to handle comparisons between positive
13801         // and negative zero incorrectly.
13802         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13803           if (!DAG.getTarget().Options.UnsafeFPMath &&
13804               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13805             break;
13806           std::swap(LHS, RHS);
13807         }
13808         Opcode = X86ISD::FMAX;
13809         break;
13810       case ISD::SETUGE:
13811         // Converting this to a max would handle both negative zeros and NaNs
13812         // incorrectly, but we can swap the operands to fix both.
13813         std::swap(LHS, RHS);
13814       case ISD::SETOGT:
13815       case ISD::SETGT:
13816       case ISD::SETGE:
13817         Opcode = X86ISD::FMAX;
13818         break;
13819       }
13820     // Check for x CC y ? y : x -- a min/max with reversed arms.
13821     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13822                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13823       switch (CC) {
13824       default: break;
13825       case ISD::SETOGE:
13826         // Converting this to a min would handle comparisons between positive
13827         // and negative zero incorrectly, and swapping the operands would
13828         // cause it to handle NaNs incorrectly.
13829         if (!DAG.getTarget().Options.UnsafeFPMath &&
13830             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13831           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13832             break;
13833           std::swap(LHS, RHS);
13834         }
13835         Opcode = X86ISD::FMIN;
13836         break;
13837       case ISD::SETUGT:
13838         // Converting this to a min would handle NaNs incorrectly.
13839         if (!DAG.getTarget().Options.UnsafeFPMath &&
13840             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13841           break;
13842         Opcode = X86ISD::FMIN;
13843         break;
13844       case ISD::SETUGE:
13845         // Converting this to a min would handle both negative zeros and NaNs
13846         // incorrectly, but we can swap the operands to fix both.
13847         std::swap(LHS, RHS);
13848       case ISD::SETOGT:
13849       case ISD::SETGT:
13850       case ISD::SETGE:
13851         Opcode = X86ISD::FMIN;
13852         break;
13853
13854       case ISD::SETULT:
13855         // Converting this to a max would handle NaNs incorrectly.
13856         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13857           break;
13858         Opcode = X86ISD::FMAX;
13859         break;
13860       case ISD::SETOLE:
13861         // Converting this to a max would handle comparisons between positive
13862         // and negative zero incorrectly, and swapping the operands would
13863         // cause it to handle NaNs incorrectly.
13864         if (!DAG.getTarget().Options.UnsafeFPMath &&
13865             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13866           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13867             break;
13868           std::swap(LHS, RHS);
13869         }
13870         Opcode = X86ISD::FMAX;
13871         break;
13872       case ISD::SETULE:
13873         // Converting this to a max would handle both negative zeros and NaNs
13874         // incorrectly, but we can swap the operands to fix both.
13875         std::swap(LHS, RHS);
13876       case ISD::SETOLT:
13877       case ISD::SETLT:
13878       case ISD::SETLE:
13879         Opcode = X86ISD::FMAX;
13880         break;
13881       }
13882     }
13883
13884     if (Opcode)
13885       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13886   }
13887
13888   // If this is a select between two integer constants, try to do some
13889   // optimizations.
13890   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13891     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13892       // Don't do this for crazy integer types.
13893       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13894         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13895         // so that TrueC (the true value) is larger than FalseC.
13896         bool NeedsCondInvert = false;
13897
13898         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13899             // Efficiently invertible.
13900             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13901              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13902               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13903           NeedsCondInvert = true;
13904           std::swap(TrueC, FalseC);
13905         }
13906
13907         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13908         if (FalseC->getAPIntValue() == 0 &&
13909             TrueC->getAPIntValue().isPowerOf2()) {
13910           if (NeedsCondInvert) // Invert the condition if needed.
13911             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13912                                DAG.getConstant(1, Cond.getValueType()));
13913
13914           // Zero extend the condition if needed.
13915           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13916
13917           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13918           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13919                              DAG.getConstant(ShAmt, MVT::i8));
13920         }
13921
13922         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13923         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13924           if (NeedsCondInvert) // Invert the condition if needed.
13925             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13926                                DAG.getConstant(1, Cond.getValueType()));
13927
13928           // Zero extend the condition if needed.
13929           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13930                              FalseC->getValueType(0), Cond);
13931           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13932                              SDValue(FalseC, 0));
13933         }
13934
13935         // Optimize cases that will turn into an LEA instruction.  This requires
13936         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13937         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13938           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13939           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13940
13941           bool isFastMultiplier = false;
13942           if (Diff < 10) {
13943             switch ((unsigned char)Diff) {
13944               default: break;
13945               case 1:  // result = add base, cond
13946               case 2:  // result = lea base(    , cond*2)
13947               case 3:  // result = lea base(cond, cond*2)
13948               case 4:  // result = lea base(    , cond*4)
13949               case 5:  // result = lea base(cond, cond*4)
13950               case 8:  // result = lea base(    , cond*8)
13951               case 9:  // result = lea base(cond, cond*8)
13952                 isFastMultiplier = true;
13953                 break;
13954             }
13955           }
13956
13957           if (isFastMultiplier) {
13958             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13959             if (NeedsCondInvert) // Invert the condition if needed.
13960               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13961                                  DAG.getConstant(1, Cond.getValueType()));
13962
13963             // Zero extend the condition if needed.
13964             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13965                                Cond);
13966             // Scale the condition by the difference.
13967             if (Diff != 1)
13968               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13969                                  DAG.getConstant(Diff, Cond.getValueType()));
13970
13971             // Add the base if non-zero.
13972             if (FalseC->getAPIntValue() != 0)
13973               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13974                                  SDValue(FalseC, 0));
13975             return Cond;
13976           }
13977         }
13978       }
13979   }
13980
13981   // Canonicalize max and min:
13982   // (x > y) ? x : y -> (x >= y) ? x : y
13983   // (x < y) ? x : y -> (x <= y) ? x : y
13984   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13985   // the need for an extra compare
13986   // against zero. e.g.
13987   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13988   // subl   %esi, %edi
13989   // testl  %edi, %edi
13990   // movl   $0, %eax
13991   // cmovgl %edi, %eax
13992   // =>
13993   // xorl   %eax, %eax
13994   // subl   %esi, $edi
13995   // cmovsl %eax, %edi
13996   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13997       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13998       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13999     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14000     switch (CC) {
14001     default: break;
14002     case ISD::SETLT:
14003     case ISD::SETGT: {
14004       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14005       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14006                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14007       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14008     }
14009     }
14010   }
14011
14012   // If we know that this node is legal then we know that it is going to be
14013   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14014   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14015   // to simplify previous instructions.
14016   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14017   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14018       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14019     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14020
14021     // Don't optimize vector selects that map to mask-registers.
14022     if (BitWidth == 1)
14023       return SDValue();
14024
14025     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14026     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14027
14028     APInt KnownZero, KnownOne;
14029     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14030                                           DCI.isBeforeLegalizeOps());
14031     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14032         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14033       DCI.CommitTargetLoweringOpt(TLO);
14034   }
14035
14036   return SDValue();
14037 }
14038
14039 // Check whether a boolean test is testing a boolean value generated by
14040 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14041 // code.
14042 //
14043 // Simplify the following patterns:
14044 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14045 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14046 // to (Op EFLAGS Cond)
14047 //
14048 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14049 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14050 // to (Op EFLAGS !Cond)
14051 //
14052 // where Op could be BRCOND or CMOV.
14053 //
14054 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14055   // Quit if not CMP and SUB with its value result used.
14056   if (Cmp.getOpcode() != X86ISD::CMP &&
14057       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14058       return SDValue();
14059
14060   // Quit if not used as a boolean value.
14061   if (CC != X86::COND_E && CC != X86::COND_NE)
14062     return SDValue();
14063
14064   // Check CMP operands. One of them should be 0 or 1 and the other should be
14065   // an SetCC or extended from it.
14066   SDValue Op1 = Cmp.getOperand(0);
14067   SDValue Op2 = Cmp.getOperand(1);
14068
14069   SDValue SetCC;
14070   const ConstantSDNode* C = 0;
14071   bool needOppositeCond = (CC == X86::COND_E);
14072
14073   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14074     SetCC = Op2;
14075   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14076     SetCC = Op1;
14077   else // Quit if all operands are not constants.
14078     return SDValue();
14079
14080   if (C->getZExtValue() == 1)
14081     needOppositeCond = !needOppositeCond;
14082   else if (C->getZExtValue() != 0)
14083     // Quit if the constant is neither 0 or 1.
14084     return SDValue();
14085
14086   // Skip 'zext' node.
14087   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14088     SetCC = SetCC.getOperand(0);
14089
14090   // Quit if not SETCC.
14091   // FIXME: So far we only handle the boolean value generated from SETCC. If
14092   // there is other ways to generate boolean values, we need handle them here
14093   // as well.
14094   if (SetCC.getOpcode() != X86ISD::SETCC)
14095     return SDValue();
14096
14097   // Set the condition code or opposite one if necessary.
14098   CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14099   if (needOppositeCond)
14100     CC = X86::GetOppositeBranchCondition(CC);
14101
14102   return SetCC.getOperand(1);
14103 }
14104
14105 /// checkFlaggedOrCombine - DAG combination on X86ISD::OR, i.e. with EFLAGS
14106 /// updated. If only flag result is used and the result is evaluated from a
14107 /// series of element extraction, try to combine it into a PTEST.
14108 static SDValue checkFlaggedOrCombine(SDValue Or, X86::CondCode &CC,
14109                                      SelectionDAG &DAG,
14110                                      const X86Subtarget *Subtarget) {
14111   SDNode *N = Or.getNode();
14112   DebugLoc DL = N->getDebugLoc();
14113
14114   // Only SSE4.1 and beyond supports PTEST or like.
14115   if (!Subtarget->hasSSE41())
14116     return SDValue();
14117
14118   if (N->getOpcode() != X86ISD::OR)
14119     return SDValue();
14120
14121   // Quit if the value result of OR is used.
14122   if (N->hasAnyUseOfValue(0))
14123     return SDValue();
14124
14125   // Quit if not used as a boolean value.
14126   if (CC != X86::COND_E && CC != X86::COND_NE)
14127     return SDValue();
14128
14129   SmallVector<SDValue, 8> Opnds;
14130   SDValue VecIn;
14131   EVT VT = MVT::Other;
14132   unsigned Mask = 0;
14133
14134   // Recognize a special case where a vector is casted into wide integer to
14135   // test all 0s.
14136   Opnds.push_back(N->getOperand(0));
14137   Opnds.push_back(N->getOperand(1));
14138
14139   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14140     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
14141     // BFS traverse all OR'd operands.
14142     if (I->getOpcode() == ISD::OR) {
14143       Opnds.push_back(I->getOperand(0));
14144       Opnds.push_back(I->getOperand(1));
14145       // Re-evaluate the number of nodes to be traversed.
14146       e += 2; // 2 more nodes (LHS and RHS) are pushed.
14147       continue;
14148     }
14149
14150     // Quit if a non-EXTRACT_VECTOR_ELT
14151     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14152       return SDValue();
14153
14154     // Quit if without a constant index.
14155     SDValue Idx = I->getOperand(1);
14156     if (!isa<ConstantSDNode>(Idx))
14157       return SDValue();
14158
14159     // Check if all elements are extracted from the same vector.
14160     SDValue ExtractedFromVec = I->getOperand(0);
14161     if (VecIn.getNode() == 0) {
14162       VT = ExtractedFromVec.getValueType();
14163       // FIXME: only 128-bit vector is supported so far.
14164       if (!VT.is128BitVector())
14165         return SDValue();
14166       VecIn = ExtractedFromVec;
14167     } else if (VecIn != ExtractedFromVec)
14168       return SDValue();
14169
14170     // Record the constant index.
14171     Mask |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14172   }
14173
14174   assert(VT.is128BitVector() && "Only 128-bit vector PTEST is supported so far.");
14175
14176   // Quit if not all elements are used.
14177   if (Mask != (1U << VT.getVectorNumElements()) - 1U)
14178     return SDValue();
14179
14180   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIn, VecIn);
14181 }
14182
14183 static bool isValidFCMOVCondition(X86::CondCode CC) {
14184   switch (CC) {
14185   default:
14186     return false;
14187   case X86::COND_B:
14188   case X86::COND_BE:
14189   case X86::COND_E:
14190   case X86::COND_P:
14191   case X86::COND_AE:
14192   case X86::COND_A:
14193   case X86::COND_NE:
14194   case X86::COND_NP:
14195     return true;
14196   }
14197 }
14198
14199 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14200 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14201                                   TargetLowering::DAGCombinerInfo &DCI,
14202                                   const X86Subtarget *Subtarget) {
14203   DebugLoc DL = N->getDebugLoc();
14204
14205   // If the flag operand isn't dead, don't touch this CMOV.
14206   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14207     return SDValue();
14208
14209   SDValue FalseOp = N->getOperand(0);
14210   SDValue TrueOp = N->getOperand(1);
14211   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14212   SDValue Cond = N->getOperand(3);
14213
14214   if (CC == X86::COND_E || CC == X86::COND_NE) {
14215     switch (Cond.getOpcode()) {
14216     default: break;
14217     case X86ISD::BSR:
14218     case X86ISD::BSF:
14219       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14220       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14221         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14222     }
14223   }
14224
14225   SDValue Flags;
14226
14227   Flags = checkBoolTestSetCCCombine(Cond, CC);
14228   if (Flags.getNode() &&
14229       // Extra check as FCMOV only supports a subset of X86 cond.
14230       (FalseOp.getValueType() != MVT::f80 || isValidFCMOVCondition(CC))) {
14231     SDValue Ops[] = { FalseOp, TrueOp,
14232                       DAG.getConstant(CC, MVT::i8), Flags };
14233     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14234                        Ops, array_lengthof(Ops));
14235   }
14236
14237   Flags = checkFlaggedOrCombine(Cond, CC, DAG, Subtarget);
14238   if (Flags.getNode()) {
14239     SDValue Ops[] = { FalseOp, TrueOp,
14240                       DAG.getConstant(CC, MVT::i8), Flags };
14241     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14242                        Ops, array_lengthof(Ops));
14243   }
14244
14245   // If this is a select between two integer constants, try to do some
14246   // optimizations.  Note that the operands are ordered the opposite of SELECT
14247   // operands.
14248   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14249     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14250       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14251       // larger than FalseC (the false value).
14252       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14253         CC = X86::GetOppositeBranchCondition(CC);
14254         std::swap(TrueC, FalseC);
14255       }
14256
14257       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14258       // This is efficient for any integer data type (including i8/i16) and
14259       // shift amount.
14260       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14261         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14262                            DAG.getConstant(CC, MVT::i8), Cond);
14263
14264         // Zero extend the condition if needed.
14265         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14266
14267         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14268         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14269                            DAG.getConstant(ShAmt, MVT::i8));
14270         if (N->getNumValues() == 2)  // Dead flag value?
14271           return DCI.CombineTo(N, Cond, SDValue());
14272         return Cond;
14273       }
14274
14275       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14276       // for any integer data type, including i8/i16.
14277       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14278         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14279                            DAG.getConstant(CC, MVT::i8), Cond);
14280
14281         // Zero extend the condition if needed.
14282         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14283                            FalseC->getValueType(0), Cond);
14284         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14285                            SDValue(FalseC, 0));
14286
14287         if (N->getNumValues() == 2)  // Dead flag value?
14288           return DCI.CombineTo(N, Cond, SDValue());
14289         return Cond;
14290       }
14291
14292       // Optimize cases that will turn into an LEA instruction.  This requires
14293       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14294       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14295         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14296         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14297
14298         bool isFastMultiplier = false;
14299         if (Diff < 10) {
14300           switch ((unsigned char)Diff) {
14301           default: break;
14302           case 1:  // result = add base, cond
14303           case 2:  // result = lea base(    , cond*2)
14304           case 3:  // result = lea base(cond, cond*2)
14305           case 4:  // result = lea base(    , cond*4)
14306           case 5:  // result = lea base(cond, cond*4)
14307           case 8:  // result = lea base(    , cond*8)
14308           case 9:  // result = lea base(cond, cond*8)
14309             isFastMultiplier = true;
14310             break;
14311           }
14312         }
14313
14314         if (isFastMultiplier) {
14315           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14316           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14317                              DAG.getConstant(CC, MVT::i8), Cond);
14318           // Zero extend the condition if needed.
14319           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14320                              Cond);
14321           // Scale the condition by the difference.
14322           if (Diff != 1)
14323             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14324                                DAG.getConstant(Diff, Cond.getValueType()));
14325
14326           // Add the base if non-zero.
14327           if (FalseC->getAPIntValue() != 0)
14328             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14329                                SDValue(FalseC, 0));
14330           if (N->getNumValues() == 2)  // Dead flag value?
14331             return DCI.CombineTo(N, Cond, SDValue());
14332           return Cond;
14333         }
14334       }
14335     }
14336   }
14337   return SDValue();
14338 }
14339
14340
14341 /// PerformMulCombine - Optimize a single multiply with constant into two
14342 /// in order to implement it with two cheaper instructions, e.g.
14343 /// LEA + SHL, LEA + LEA.
14344 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14345                                  TargetLowering::DAGCombinerInfo &DCI) {
14346   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14347     return SDValue();
14348
14349   EVT VT = N->getValueType(0);
14350   if (VT != MVT::i64)
14351     return SDValue();
14352
14353   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14354   if (!C)
14355     return SDValue();
14356   uint64_t MulAmt = C->getZExtValue();
14357   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14358     return SDValue();
14359
14360   uint64_t MulAmt1 = 0;
14361   uint64_t MulAmt2 = 0;
14362   if ((MulAmt % 9) == 0) {
14363     MulAmt1 = 9;
14364     MulAmt2 = MulAmt / 9;
14365   } else if ((MulAmt % 5) == 0) {
14366     MulAmt1 = 5;
14367     MulAmt2 = MulAmt / 5;
14368   } else if ((MulAmt % 3) == 0) {
14369     MulAmt1 = 3;
14370     MulAmt2 = MulAmt / 3;
14371   }
14372   if (MulAmt2 &&
14373       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14374     DebugLoc DL = N->getDebugLoc();
14375
14376     if (isPowerOf2_64(MulAmt2) &&
14377         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14378       // If second multiplifer is pow2, issue it first. We want the multiply by
14379       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14380       // is an add.
14381       std::swap(MulAmt1, MulAmt2);
14382
14383     SDValue NewMul;
14384     if (isPowerOf2_64(MulAmt1))
14385       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14386                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14387     else
14388       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14389                            DAG.getConstant(MulAmt1, VT));
14390
14391     if (isPowerOf2_64(MulAmt2))
14392       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14393                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14394     else
14395       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14396                            DAG.getConstant(MulAmt2, VT));
14397
14398     // Do not add new nodes to DAG combiner worklist.
14399     DCI.CombineTo(N, NewMul, false);
14400   }
14401   return SDValue();
14402 }
14403
14404 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14405   SDValue N0 = N->getOperand(0);
14406   SDValue N1 = N->getOperand(1);
14407   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14408   EVT VT = N0.getValueType();
14409
14410   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14411   // since the result of setcc_c is all zero's or all ones.
14412   if (VT.isInteger() && !VT.isVector() &&
14413       N1C && N0.getOpcode() == ISD::AND &&
14414       N0.getOperand(1).getOpcode() == ISD::Constant) {
14415     SDValue N00 = N0.getOperand(0);
14416     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14417         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14418           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14419          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14420       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14421       APInt ShAmt = N1C->getAPIntValue();
14422       Mask = Mask.shl(ShAmt);
14423       if (Mask != 0)
14424         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14425                            N00, DAG.getConstant(Mask, VT));
14426     }
14427   }
14428
14429
14430   // Hardware support for vector shifts is sparse which makes us scalarize the
14431   // vector operations in many cases. Also, on sandybridge ADD is faster than
14432   // shl.
14433   // (shl V, 1) -> add V,V
14434   if (isSplatVector(N1.getNode())) {
14435     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14436     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14437     // We shift all of the values by one. In many cases we do not have
14438     // hardware support for this operation. This is better expressed as an ADD
14439     // of two values.
14440     if (N1C && (1 == N1C->getZExtValue())) {
14441       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14442     }
14443   }
14444
14445   return SDValue();
14446 }
14447
14448 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14449 ///                       when possible.
14450 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14451                                    TargetLowering::DAGCombinerInfo &DCI,
14452                                    const X86Subtarget *Subtarget) {
14453   EVT VT = N->getValueType(0);
14454   if (N->getOpcode() == ISD::SHL) {
14455     SDValue V = PerformSHLCombine(N, DAG);
14456     if (V.getNode()) return V;
14457   }
14458
14459   // On X86 with SSE2 support, we can transform this to a vector shift if
14460   // all elements are shifted by the same amount.  We can't do this in legalize
14461   // because the a constant vector is typically transformed to a constant pool
14462   // so we have no knowledge of the shift amount.
14463   if (!Subtarget->hasSSE2())
14464     return SDValue();
14465
14466   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14467       (!Subtarget->hasAVX2() ||
14468        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14469     return SDValue();
14470
14471   SDValue ShAmtOp = N->getOperand(1);
14472   EVT EltVT = VT.getVectorElementType();
14473   DebugLoc DL = N->getDebugLoc();
14474   SDValue BaseShAmt = SDValue();
14475   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14476     unsigned NumElts = VT.getVectorNumElements();
14477     unsigned i = 0;
14478     for (; i != NumElts; ++i) {
14479       SDValue Arg = ShAmtOp.getOperand(i);
14480       if (Arg.getOpcode() == ISD::UNDEF) continue;
14481       BaseShAmt = Arg;
14482       break;
14483     }
14484     // Handle the case where the build_vector is all undef
14485     // FIXME: Should DAG allow this?
14486     if (i == NumElts)
14487       return SDValue();
14488
14489     for (; i != NumElts; ++i) {
14490       SDValue Arg = ShAmtOp.getOperand(i);
14491       if (Arg.getOpcode() == ISD::UNDEF) continue;
14492       if (Arg != BaseShAmt) {
14493         return SDValue();
14494       }
14495     }
14496   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14497              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14498     SDValue InVec = ShAmtOp.getOperand(0);
14499     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14500       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14501       unsigned i = 0;
14502       for (; i != NumElts; ++i) {
14503         SDValue Arg = InVec.getOperand(i);
14504         if (Arg.getOpcode() == ISD::UNDEF) continue;
14505         BaseShAmt = Arg;
14506         break;
14507       }
14508     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14509        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14510          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14511          if (C->getZExtValue() == SplatIdx)
14512            BaseShAmt = InVec.getOperand(1);
14513        }
14514     }
14515     if (BaseShAmt.getNode() == 0) {
14516       // Don't create instructions with illegal types after legalize
14517       // types has run.
14518       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14519           !DCI.isBeforeLegalize())
14520         return SDValue();
14521
14522       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14523                               DAG.getIntPtrConstant(0));
14524     }
14525   } else
14526     return SDValue();
14527
14528   // The shift amount is an i32.
14529   if (EltVT.bitsGT(MVT::i32))
14530     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14531   else if (EltVT.bitsLT(MVT::i32))
14532     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14533
14534   // The shift amount is identical so we can do a vector shift.
14535   SDValue  ValOp = N->getOperand(0);
14536   switch (N->getOpcode()) {
14537   default:
14538     llvm_unreachable("Unknown shift opcode!");
14539   case ISD::SHL:
14540     switch (VT.getSimpleVT().SimpleTy) {
14541     default: return SDValue();
14542     case MVT::v2i64:
14543     case MVT::v4i32:
14544     case MVT::v8i16:
14545     case MVT::v4i64:
14546     case MVT::v8i32:
14547     case MVT::v16i16:
14548       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14549     }
14550   case ISD::SRA:
14551     switch (VT.getSimpleVT().SimpleTy) {
14552     default: return SDValue();
14553     case MVT::v4i32:
14554     case MVT::v8i16:
14555     case MVT::v8i32:
14556     case MVT::v16i16:
14557       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14558     }
14559   case ISD::SRL:
14560     switch (VT.getSimpleVT().SimpleTy) {
14561     default: return SDValue();
14562     case MVT::v2i64:
14563     case MVT::v4i32:
14564     case MVT::v8i16:
14565     case MVT::v4i64:
14566     case MVT::v8i32:
14567     case MVT::v16i16:
14568       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14569     }
14570   }
14571 }
14572
14573
14574 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14575 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14576 // and friends.  Likewise for OR -> CMPNEQSS.
14577 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14578                             TargetLowering::DAGCombinerInfo &DCI,
14579                             const X86Subtarget *Subtarget) {
14580   unsigned opcode;
14581
14582   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14583   // we're requiring SSE2 for both.
14584   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14585     SDValue N0 = N->getOperand(0);
14586     SDValue N1 = N->getOperand(1);
14587     SDValue CMP0 = N0->getOperand(1);
14588     SDValue CMP1 = N1->getOperand(1);
14589     DebugLoc DL = N->getDebugLoc();
14590
14591     // The SETCCs should both refer to the same CMP.
14592     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14593       return SDValue();
14594
14595     SDValue CMP00 = CMP0->getOperand(0);
14596     SDValue CMP01 = CMP0->getOperand(1);
14597     EVT     VT    = CMP00.getValueType();
14598
14599     if (VT == MVT::f32 || VT == MVT::f64) {
14600       bool ExpectingFlags = false;
14601       // Check for any users that want flags:
14602       for (SDNode::use_iterator UI = N->use_begin(),
14603              UE = N->use_end();
14604            !ExpectingFlags && UI != UE; ++UI)
14605         switch (UI->getOpcode()) {
14606         default:
14607         case ISD::BR_CC:
14608         case ISD::BRCOND:
14609         case ISD::SELECT:
14610           ExpectingFlags = true;
14611           break;
14612         case ISD::CopyToReg:
14613         case ISD::SIGN_EXTEND:
14614         case ISD::ZERO_EXTEND:
14615         case ISD::ANY_EXTEND:
14616           break;
14617         }
14618
14619       if (!ExpectingFlags) {
14620         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14621         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14622
14623         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14624           X86::CondCode tmp = cc0;
14625           cc0 = cc1;
14626           cc1 = tmp;
14627         }
14628
14629         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14630             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14631           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14632           X86ISD::NodeType NTOperator = is64BitFP ?
14633             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14634           // FIXME: need symbolic constants for these magic numbers.
14635           // See X86ATTInstPrinter.cpp:printSSECC().
14636           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14637           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14638                                               DAG.getConstant(x86cc, MVT::i8));
14639           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14640                                               OnesOrZeroesF);
14641           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14642                                       DAG.getConstant(1, MVT::i32));
14643           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14644           return OneBitOfTruth;
14645         }
14646       }
14647     }
14648   }
14649   return SDValue();
14650 }
14651
14652 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14653 /// so it can be folded inside ANDNP.
14654 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14655   EVT VT = N->getValueType(0);
14656
14657   // Match direct AllOnes for 128 and 256-bit vectors
14658   if (ISD::isBuildVectorAllOnes(N))
14659     return true;
14660
14661   // Look through a bit convert.
14662   if (N->getOpcode() == ISD::BITCAST)
14663     N = N->getOperand(0).getNode();
14664
14665   // Sometimes the operand may come from a insert_subvector building a 256-bit
14666   // allones vector
14667   if (VT.is256BitVector() &&
14668       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14669     SDValue V1 = N->getOperand(0);
14670     SDValue V2 = N->getOperand(1);
14671
14672     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14673         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14674         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14675         ISD::isBuildVectorAllOnes(V2.getNode()))
14676       return true;
14677   }
14678
14679   return false;
14680 }
14681
14682 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14683                                  TargetLowering::DAGCombinerInfo &DCI,
14684                                  const X86Subtarget *Subtarget) {
14685   if (DCI.isBeforeLegalizeOps())
14686     return SDValue();
14687
14688   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14689   if (R.getNode())
14690     return R;
14691
14692   EVT VT = N->getValueType(0);
14693
14694   // Create ANDN, BLSI, and BLSR instructions
14695   // BLSI is X & (-X)
14696   // BLSR is X & (X-1)
14697   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14698     SDValue N0 = N->getOperand(0);
14699     SDValue N1 = N->getOperand(1);
14700     DebugLoc DL = N->getDebugLoc();
14701
14702     // Check LHS for not
14703     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14704       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14705     // Check RHS for not
14706     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14707       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14708
14709     // Check LHS for neg
14710     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14711         isZero(N0.getOperand(0)))
14712       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14713
14714     // Check RHS for neg
14715     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14716         isZero(N1.getOperand(0)))
14717       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14718
14719     // Check LHS for X-1
14720     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14721         isAllOnes(N0.getOperand(1)))
14722       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14723
14724     // Check RHS for X-1
14725     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14726         isAllOnes(N1.getOperand(1)))
14727       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14728
14729     return SDValue();
14730   }
14731
14732   // Want to form ANDNP nodes:
14733   // 1) In the hopes of then easily combining them with OR and AND nodes
14734   //    to form PBLEND/PSIGN.
14735   // 2) To match ANDN packed intrinsics
14736   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14737     return SDValue();
14738
14739   SDValue N0 = N->getOperand(0);
14740   SDValue N1 = N->getOperand(1);
14741   DebugLoc DL = N->getDebugLoc();
14742
14743   // Check LHS for vnot
14744   if (N0.getOpcode() == ISD::XOR &&
14745       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14746       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14747     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14748
14749   // Check RHS for vnot
14750   if (N1.getOpcode() == ISD::XOR &&
14751       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14752       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14753     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14754
14755   return SDValue();
14756 }
14757
14758 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14759                                 TargetLowering::DAGCombinerInfo &DCI,
14760                                 const X86Subtarget *Subtarget) {
14761   if (DCI.isBeforeLegalizeOps())
14762     return SDValue();
14763
14764   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14765   if (R.getNode())
14766     return R;
14767
14768   EVT VT = N->getValueType(0);
14769
14770   SDValue N0 = N->getOperand(0);
14771   SDValue N1 = N->getOperand(1);
14772
14773   // look for psign/blend
14774   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14775     if (!Subtarget->hasSSSE3() ||
14776         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14777       return SDValue();
14778
14779     // Canonicalize pandn to RHS
14780     if (N0.getOpcode() == X86ISD::ANDNP)
14781       std::swap(N0, N1);
14782     // or (and (m, y), (pandn m, x))
14783     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14784       SDValue Mask = N1.getOperand(0);
14785       SDValue X    = N1.getOperand(1);
14786       SDValue Y;
14787       if (N0.getOperand(0) == Mask)
14788         Y = N0.getOperand(1);
14789       if (N0.getOperand(1) == Mask)
14790         Y = N0.getOperand(0);
14791
14792       // Check to see if the mask appeared in both the AND and ANDNP and
14793       if (!Y.getNode())
14794         return SDValue();
14795
14796       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14797       // Look through mask bitcast.
14798       if (Mask.getOpcode() == ISD::BITCAST)
14799         Mask = Mask.getOperand(0);
14800       if (X.getOpcode() == ISD::BITCAST)
14801         X = X.getOperand(0);
14802       if (Y.getOpcode() == ISD::BITCAST)
14803         Y = Y.getOperand(0);
14804
14805       EVT MaskVT = Mask.getValueType();
14806
14807       // Validate that the Mask operand is a vector sra node.
14808       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14809       // there is no psrai.b
14810       if (Mask.getOpcode() != X86ISD::VSRAI)
14811         return SDValue();
14812
14813       // Check that the SRA is all signbits.
14814       SDValue SraC = Mask.getOperand(1);
14815       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14816       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14817       if ((SraAmt + 1) != EltBits)
14818         return SDValue();
14819
14820       DebugLoc DL = N->getDebugLoc();
14821
14822       // Now we know we at least have a plendvb with the mask val.  See if
14823       // we can form a psignb/w/d.
14824       // psign = x.type == y.type == mask.type && y = sub(0, x);
14825       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14826           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14827           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14828         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14829                "Unsupported VT for PSIGN");
14830         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14831         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14832       }
14833       // PBLENDVB only available on SSE 4.1
14834       if (!Subtarget->hasSSE41())
14835         return SDValue();
14836
14837       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14838
14839       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14840       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14841       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14842       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14843       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14844     }
14845   }
14846
14847   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14848     return SDValue();
14849
14850   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14851   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14852     std::swap(N0, N1);
14853   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14854     return SDValue();
14855   if (!N0.hasOneUse() || !N1.hasOneUse())
14856     return SDValue();
14857
14858   SDValue ShAmt0 = N0.getOperand(1);
14859   if (ShAmt0.getValueType() != MVT::i8)
14860     return SDValue();
14861   SDValue ShAmt1 = N1.getOperand(1);
14862   if (ShAmt1.getValueType() != MVT::i8)
14863     return SDValue();
14864   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14865     ShAmt0 = ShAmt0.getOperand(0);
14866   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14867     ShAmt1 = ShAmt1.getOperand(0);
14868
14869   DebugLoc DL = N->getDebugLoc();
14870   unsigned Opc = X86ISD::SHLD;
14871   SDValue Op0 = N0.getOperand(0);
14872   SDValue Op1 = N1.getOperand(0);
14873   if (ShAmt0.getOpcode() == ISD::SUB) {
14874     Opc = X86ISD::SHRD;
14875     std::swap(Op0, Op1);
14876     std::swap(ShAmt0, ShAmt1);
14877   }
14878
14879   unsigned Bits = VT.getSizeInBits();
14880   if (ShAmt1.getOpcode() == ISD::SUB) {
14881     SDValue Sum = ShAmt1.getOperand(0);
14882     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14883       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14884       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14885         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14886       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14887         return DAG.getNode(Opc, DL, VT,
14888                            Op0, Op1,
14889                            DAG.getNode(ISD::TRUNCATE, DL,
14890                                        MVT::i8, ShAmt0));
14891     }
14892   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14893     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14894     if (ShAmt0C &&
14895         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14896       return DAG.getNode(Opc, DL, VT,
14897                          N0.getOperand(0), N1.getOperand(0),
14898                          DAG.getNode(ISD::TRUNCATE, DL,
14899                                        MVT::i8, ShAmt0));
14900   }
14901
14902   return SDValue();
14903 }
14904
14905 // Generate NEG and CMOV for integer abs.
14906 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14907   EVT VT = N->getValueType(0);
14908
14909   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14910   // 8-bit integer abs to NEG and CMOV.
14911   if (VT.isInteger() && VT.getSizeInBits() == 8)
14912     return SDValue();
14913
14914   SDValue N0 = N->getOperand(0);
14915   SDValue N1 = N->getOperand(1);
14916   DebugLoc DL = N->getDebugLoc();
14917
14918   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
14919   // and change it to SUB and CMOV.
14920   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
14921       N0.getOpcode() == ISD::ADD &&
14922       N0.getOperand(1) == N1 &&
14923       N1.getOpcode() == ISD::SRA &&
14924       N1.getOperand(0) == N0.getOperand(0))
14925     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
14926       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
14927         // Generate SUB & CMOV.
14928         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
14929                                   DAG.getConstant(0, VT), N0.getOperand(0));
14930
14931         SDValue Ops[] = { N0.getOperand(0), Neg,
14932                           DAG.getConstant(X86::COND_GE, MVT::i8),
14933                           SDValue(Neg.getNode(), 1) };
14934         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
14935                            Ops, array_lengthof(Ops));
14936       }
14937   return SDValue();
14938 }
14939
14940 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14941 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14942                                  TargetLowering::DAGCombinerInfo &DCI,
14943                                  const X86Subtarget *Subtarget) {
14944   if (DCI.isBeforeLegalizeOps())
14945     return SDValue();
14946
14947   if (Subtarget->hasCMov()) {
14948     SDValue RV = performIntegerAbsCombine(N, DAG);
14949     if (RV.getNode())
14950       return RV;
14951   }
14952
14953   // Try forming BMI if it is available.
14954   if (!Subtarget->hasBMI())
14955     return SDValue();
14956
14957   EVT VT = N->getValueType(0);
14958
14959   if (VT != MVT::i32 && VT != MVT::i64)
14960     return SDValue();
14961
14962   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14963
14964   // Create BLSMSK instructions by finding X ^ (X-1)
14965   SDValue N0 = N->getOperand(0);
14966   SDValue N1 = N->getOperand(1);
14967   DebugLoc DL = N->getDebugLoc();
14968
14969   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14970       isAllOnes(N0.getOperand(1)))
14971     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14972
14973   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14974       isAllOnes(N1.getOperand(1)))
14975     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14976
14977   return SDValue();
14978 }
14979
14980 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14981 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14982                                   TargetLowering::DAGCombinerInfo &DCI,
14983                                   const X86Subtarget *Subtarget) {
14984   LoadSDNode *Ld = cast<LoadSDNode>(N);
14985   EVT RegVT = Ld->getValueType(0);
14986   EVT MemVT = Ld->getMemoryVT();
14987   DebugLoc dl = Ld->getDebugLoc();
14988   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14989
14990   ISD::LoadExtType Ext = Ld->getExtensionType();
14991
14992   // If this is a vector EXT Load then attempt to optimize it using a
14993   // shuffle. We need SSE4 for the shuffles.
14994   // TODO: It is possible to support ZExt by zeroing the undef values
14995   // during the shuffle phase or after the shuffle.
14996   if (RegVT.isVector() && RegVT.isInteger() &&
14997       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14998     assert(MemVT != RegVT && "Cannot extend to the same type");
14999     assert(MemVT.isVector() && "Must load a vector from memory");
15000
15001     unsigned NumElems = RegVT.getVectorNumElements();
15002     unsigned RegSz = RegVT.getSizeInBits();
15003     unsigned MemSz = MemVT.getSizeInBits();
15004     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15005
15006     // All sizes must be a power of two.
15007     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15008       return SDValue();
15009
15010     // Attempt to load the original value using scalar loads.
15011     // Find the largest scalar type that divides the total loaded size.
15012     MVT SclrLoadTy = MVT::i8;
15013     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15014          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15015       MVT Tp = (MVT::SimpleValueType)tp;
15016       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15017         SclrLoadTy = Tp;
15018       }
15019     }
15020
15021     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15022     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15023         (64 <= MemSz))
15024       SclrLoadTy = MVT::f64;
15025
15026     // Calculate the number of scalar loads that we need to perform
15027     // in order to load our vector from memory.
15028     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15029
15030     // Represent our vector as a sequence of elements which are the
15031     // largest scalar that we can load.
15032     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15033       RegSz/SclrLoadTy.getSizeInBits());
15034
15035     // Represent the data using the same element type that is stored in
15036     // memory. In practice, we ''widen'' MemVT.
15037     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15038                                   RegSz/MemVT.getScalarType().getSizeInBits());
15039
15040     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15041       "Invalid vector type");
15042
15043     // We can't shuffle using an illegal type.
15044     if (!TLI.isTypeLegal(WideVecVT))
15045       return SDValue();
15046
15047     SmallVector<SDValue, 8> Chains;
15048     SDValue Ptr = Ld->getBasePtr();
15049     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15050                                         TLI.getPointerTy());
15051     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15052
15053     for (unsigned i = 0; i < NumLoads; ++i) {
15054       // Perform a single load.
15055       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15056                                        Ptr, Ld->getPointerInfo(),
15057                                        Ld->isVolatile(), Ld->isNonTemporal(),
15058                                        Ld->isInvariant(), Ld->getAlignment());
15059       Chains.push_back(ScalarLoad.getValue(1));
15060       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15061       // another round of DAGCombining.
15062       if (i == 0)
15063         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15064       else
15065         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15066                           ScalarLoad, DAG.getIntPtrConstant(i));
15067
15068       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15069     }
15070
15071     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15072                                Chains.size());
15073
15074     // Bitcast the loaded value to a vector of the original element type, in
15075     // the size of the target vector type.
15076     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15077     unsigned SizeRatio = RegSz/MemSz;
15078
15079     // Redistribute the loaded elements into the different locations.
15080     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15081     for (unsigned i = 0; i != NumElems; ++i)
15082       ShuffleVec[i*SizeRatio] = i;
15083
15084     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15085                                          DAG.getUNDEF(WideVecVT),
15086                                          &ShuffleVec[0]);
15087
15088     // Bitcast to the requested type.
15089     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15090     // Replace the original load with the new sequence
15091     // and return the new chain.
15092     return DCI.CombineTo(N, Shuff, TF, true);
15093   }
15094
15095   return SDValue();
15096 }
15097
15098 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15099 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15100                                    const X86Subtarget *Subtarget) {
15101   StoreSDNode *St = cast<StoreSDNode>(N);
15102   EVT VT = St->getValue().getValueType();
15103   EVT StVT = St->getMemoryVT();
15104   DebugLoc dl = St->getDebugLoc();
15105   SDValue StoredVal = St->getOperand(1);
15106   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15107
15108   // If we are saving a concatenation of two XMM registers, perform two stores.
15109   // On Sandy Bridge, 256-bit memory operations are executed by two
15110   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15111   // memory  operation.
15112   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15113       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15114       StoredVal.getNumOperands() == 2) {
15115     SDValue Value0 = StoredVal.getOperand(0);
15116     SDValue Value1 = StoredVal.getOperand(1);
15117
15118     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15119     SDValue Ptr0 = St->getBasePtr();
15120     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15121
15122     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15123                                 St->getPointerInfo(), St->isVolatile(),
15124                                 St->isNonTemporal(), St->getAlignment());
15125     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15126                                 St->getPointerInfo(), St->isVolatile(),
15127                                 St->isNonTemporal(), St->getAlignment());
15128     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15129   }
15130
15131   // Optimize trunc store (of multiple scalars) to shuffle and store.
15132   // First, pack all of the elements in one place. Next, store to memory
15133   // in fewer chunks.
15134   if (St->isTruncatingStore() && VT.isVector()) {
15135     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15136     unsigned NumElems = VT.getVectorNumElements();
15137     assert(StVT != VT && "Cannot truncate to the same type");
15138     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15139     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15140
15141     // From, To sizes and ElemCount must be pow of two
15142     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15143     // We are going to use the original vector elt for storing.
15144     // Accumulated smaller vector elements must be a multiple of the store size.
15145     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15146
15147     unsigned SizeRatio  = FromSz / ToSz;
15148
15149     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15150
15151     // Create a type on which we perform the shuffle
15152     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15153             StVT.getScalarType(), NumElems*SizeRatio);
15154
15155     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15156
15157     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15158     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15159     for (unsigned i = 0; i != NumElems; ++i)
15160       ShuffleVec[i] = i * SizeRatio;
15161
15162     // Can't shuffle using an illegal type.
15163     if (!TLI.isTypeLegal(WideVecVT))
15164       return SDValue();
15165
15166     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15167                                          DAG.getUNDEF(WideVecVT),
15168                                          &ShuffleVec[0]);
15169     // At this point all of the data is stored at the bottom of the
15170     // register. We now need to save it to mem.
15171
15172     // Find the largest store unit
15173     MVT StoreType = MVT::i8;
15174     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15175          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15176       MVT Tp = (MVT::SimpleValueType)tp;
15177       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15178         StoreType = Tp;
15179     }
15180
15181     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15182     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15183         (64 <= NumElems * ToSz))
15184       StoreType = MVT::f64;
15185
15186     // Bitcast the original vector into a vector of store-size units
15187     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15188             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15189     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15190     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15191     SmallVector<SDValue, 8> Chains;
15192     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15193                                         TLI.getPointerTy());
15194     SDValue Ptr = St->getBasePtr();
15195
15196     // Perform one or more big stores into memory.
15197     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15198       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15199                                    StoreType, ShuffWide,
15200                                    DAG.getIntPtrConstant(i));
15201       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15202                                 St->getPointerInfo(), St->isVolatile(),
15203                                 St->isNonTemporal(), St->getAlignment());
15204       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15205       Chains.push_back(Ch);
15206     }
15207
15208     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15209                                Chains.size());
15210   }
15211
15212
15213   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15214   // the FP state in cases where an emms may be missing.
15215   // A preferable solution to the general problem is to figure out the right
15216   // places to insert EMMS.  This qualifies as a quick hack.
15217
15218   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15219   if (VT.getSizeInBits() != 64)
15220     return SDValue();
15221
15222   const Function *F = DAG.getMachineFunction().getFunction();
15223   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15224   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15225                      && Subtarget->hasSSE2();
15226   if ((VT.isVector() ||
15227        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15228       isa<LoadSDNode>(St->getValue()) &&
15229       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15230       St->getChain().hasOneUse() && !St->isVolatile()) {
15231     SDNode* LdVal = St->getValue().getNode();
15232     LoadSDNode *Ld = 0;
15233     int TokenFactorIndex = -1;
15234     SmallVector<SDValue, 8> Ops;
15235     SDNode* ChainVal = St->getChain().getNode();
15236     // Must be a store of a load.  We currently handle two cases:  the load
15237     // is a direct child, and it's under an intervening TokenFactor.  It is
15238     // possible to dig deeper under nested TokenFactors.
15239     if (ChainVal == LdVal)
15240       Ld = cast<LoadSDNode>(St->getChain());
15241     else if (St->getValue().hasOneUse() &&
15242              ChainVal->getOpcode() == ISD::TokenFactor) {
15243       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15244         if (ChainVal->getOperand(i).getNode() == LdVal) {
15245           TokenFactorIndex = i;
15246           Ld = cast<LoadSDNode>(St->getValue());
15247         } else
15248           Ops.push_back(ChainVal->getOperand(i));
15249       }
15250     }
15251
15252     if (!Ld || !ISD::isNormalLoad(Ld))
15253       return SDValue();
15254
15255     // If this is not the MMX case, i.e. we are just turning i64 load/store
15256     // into f64 load/store, avoid the transformation if there are multiple
15257     // uses of the loaded value.
15258     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15259       return SDValue();
15260
15261     DebugLoc LdDL = Ld->getDebugLoc();
15262     DebugLoc StDL = N->getDebugLoc();
15263     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15264     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15265     // pair instead.
15266     if (Subtarget->is64Bit() || F64IsLegal) {
15267       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15268       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15269                                   Ld->getPointerInfo(), Ld->isVolatile(),
15270                                   Ld->isNonTemporal(), Ld->isInvariant(),
15271                                   Ld->getAlignment());
15272       SDValue NewChain = NewLd.getValue(1);
15273       if (TokenFactorIndex != -1) {
15274         Ops.push_back(NewChain);
15275         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15276                                Ops.size());
15277       }
15278       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15279                           St->getPointerInfo(),
15280                           St->isVolatile(), St->isNonTemporal(),
15281                           St->getAlignment());
15282     }
15283
15284     // Otherwise, lower to two pairs of 32-bit loads / stores.
15285     SDValue LoAddr = Ld->getBasePtr();
15286     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15287                                  DAG.getConstant(4, MVT::i32));
15288
15289     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15290                                Ld->getPointerInfo(),
15291                                Ld->isVolatile(), Ld->isNonTemporal(),
15292                                Ld->isInvariant(), Ld->getAlignment());
15293     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15294                                Ld->getPointerInfo().getWithOffset(4),
15295                                Ld->isVolatile(), Ld->isNonTemporal(),
15296                                Ld->isInvariant(),
15297                                MinAlign(Ld->getAlignment(), 4));
15298
15299     SDValue NewChain = LoLd.getValue(1);
15300     if (TokenFactorIndex != -1) {
15301       Ops.push_back(LoLd);
15302       Ops.push_back(HiLd);
15303       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15304                              Ops.size());
15305     }
15306
15307     LoAddr = St->getBasePtr();
15308     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15309                          DAG.getConstant(4, MVT::i32));
15310
15311     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15312                                 St->getPointerInfo(),
15313                                 St->isVolatile(), St->isNonTemporal(),
15314                                 St->getAlignment());
15315     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15316                                 St->getPointerInfo().getWithOffset(4),
15317                                 St->isVolatile(),
15318                                 St->isNonTemporal(),
15319                                 MinAlign(St->getAlignment(), 4));
15320     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15321   }
15322   return SDValue();
15323 }
15324
15325 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15326 /// and return the operands for the horizontal operation in LHS and RHS.  A
15327 /// horizontal operation performs the binary operation on successive elements
15328 /// of its first operand, then on successive elements of its second operand,
15329 /// returning the resulting values in a vector.  For example, if
15330 ///   A = < float a0, float a1, float a2, float a3 >
15331 /// and
15332 ///   B = < float b0, float b1, float b2, float b3 >
15333 /// then the result of doing a horizontal operation on A and B is
15334 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15335 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15336 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15337 /// set to A, RHS to B, and the routine returns 'true'.
15338 /// Note that the binary operation should have the property that if one of the
15339 /// operands is UNDEF then the result is UNDEF.
15340 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15341   // Look for the following pattern: if
15342   //   A = < float a0, float a1, float a2, float a3 >
15343   //   B = < float b0, float b1, float b2, float b3 >
15344   // and
15345   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15346   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15347   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15348   // which is A horizontal-op B.
15349
15350   // At least one of the operands should be a vector shuffle.
15351   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15352       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15353     return false;
15354
15355   EVT VT = LHS.getValueType();
15356
15357   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15358          "Unsupported vector type for horizontal add/sub");
15359
15360   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15361   // operate independently on 128-bit lanes.
15362   unsigned NumElts = VT.getVectorNumElements();
15363   unsigned NumLanes = VT.getSizeInBits()/128;
15364   unsigned NumLaneElts = NumElts / NumLanes;
15365   assert((NumLaneElts % 2 == 0) &&
15366          "Vector type should have an even number of elements in each lane");
15367   unsigned HalfLaneElts = NumLaneElts/2;
15368
15369   // View LHS in the form
15370   //   LHS = VECTOR_SHUFFLE A, B, LMask
15371   // If LHS is not a shuffle then pretend it is the shuffle
15372   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15373   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15374   // type VT.
15375   SDValue A, B;
15376   SmallVector<int, 16> LMask(NumElts);
15377   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15378     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15379       A = LHS.getOperand(0);
15380     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15381       B = LHS.getOperand(1);
15382     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15383     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15384   } else {
15385     if (LHS.getOpcode() != ISD::UNDEF)
15386       A = LHS;
15387     for (unsigned i = 0; i != NumElts; ++i)
15388       LMask[i] = i;
15389   }
15390
15391   // Likewise, view RHS in the form
15392   //   RHS = VECTOR_SHUFFLE C, D, RMask
15393   SDValue C, D;
15394   SmallVector<int, 16> RMask(NumElts);
15395   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15396     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15397       C = RHS.getOperand(0);
15398     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15399       D = RHS.getOperand(1);
15400     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15401     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15402   } else {
15403     if (RHS.getOpcode() != ISD::UNDEF)
15404       C = RHS;
15405     for (unsigned i = 0; i != NumElts; ++i)
15406       RMask[i] = i;
15407   }
15408
15409   // Check that the shuffles are both shuffling the same vectors.
15410   if (!(A == C && B == D) && !(A == D && B == C))
15411     return false;
15412
15413   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15414   if (!A.getNode() && !B.getNode())
15415     return false;
15416
15417   // If A and B occur in reverse order in RHS, then "swap" them (which means
15418   // rewriting the mask).
15419   if (A != C)
15420     CommuteVectorShuffleMask(RMask, NumElts);
15421
15422   // At this point LHS and RHS are equivalent to
15423   //   LHS = VECTOR_SHUFFLE A, B, LMask
15424   //   RHS = VECTOR_SHUFFLE A, B, RMask
15425   // Check that the masks correspond to performing a horizontal operation.
15426   for (unsigned i = 0; i != NumElts; ++i) {
15427     int LIdx = LMask[i], RIdx = RMask[i];
15428
15429     // Ignore any UNDEF components.
15430     if (LIdx < 0 || RIdx < 0 ||
15431         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15432         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15433       continue;
15434
15435     // Check that successive elements are being operated on.  If not, this is
15436     // not a horizontal operation.
15437     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15438     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15439     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15440     if (!(LIdx == Index && RIdx == Index + 1) &&
15441         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15442       return false;
15443   }
15444
15445   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15446   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15447   return true;
15448 }
15449
15450 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15451 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15452                                   const X86Subtarget *Subtarget) {
15453   EVT VT = N->getValueType(0);
15454   SDValue LHS = N->getOperand(0);
15455   SDValue RHS = N->getOperand(1);
15456
15457   // Try to synthesize horizontal adds from adds of shuffles.
15458   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15459        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15460       isHorizontalBinOp(LHS, RHS, true))
15461     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15462   return SDValue();
15463 }
15464
15465 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15466 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15467                                   const X86Subtarget *Subtarget) {
15468   EVT VT = N->getValueType(0);
15469   SDValue LHS = N->getOperand(0);
15470   SDValue RHS = N->getOperand(1);
15471
15472   // Try to synthesize horizontal subs from subs of shuffles.
15473   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15474        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15475       isHorizontalBinOp(LHS, RHS, false))
15476     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15477   return SDValue();
15478 }
15479
15480 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15481 /// X86ISD::FXOR nodes.
15482 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15483   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15484   // F[X]OR(0.0, x) -> x
15485   // F[X]OR(x, 0.0) -> x
15486   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15487     if (C->getValueAPF().isPosZero())
15488       return N->getOperand(1);
15489   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15490     if (C->getValueAPF().isPosZero())
15491       return N->getOperand(0);
15492   return SDValue();
15493 }
15494
15495 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15496 /// X86ISD::FMAX nodes.
15497 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15498   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15499
15500   // Only perform optimizations if UnsafeMath is used.
15501   if (!DAG.getTarget().Options.UnsafeFPMath)
15502     return SDValue();
15503
15504   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15505   // into FMINC and FMAXC, which are Commutative operations.
15506   unsigned NewOp = 0;
15507   switch (N->getOpcode()) {
15508     default: llvm_unreachable("unknown opcode");
15509     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15510     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15511   }
15512
15513   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15514                      N->getOperand(0), N->getOperand(1));
15515 }
15516
15517
15518 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15519 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15520   // FAND(0.0, x) -> 0.0
15521   // FAND(x, 0.0) -> 0.0
15522   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15523     if (C->getValueAPF().isPosZero())
15524       return N->getOperand(0);
15525   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15526     if (C->getValueAPF().isPosZero())
15527       return N->getOperand(1);
15528   return SDValue();
15529 }
15530
15531 static SDValue PerformBTCombine(SDNode *N,
15532                                 SelectionDAG &DAG,
15533                                 TargetLowering::DAGCombinerInfo &DCI) {
15534   // BT ignores high bits in the bit index operand.
15535   SDValue Op1 = N->getOperand(1);
15536   if (Op1.hasOneUse()) {
15537     unsigned BitWidth = Op1.getValueSizeInBits();
15538     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15539     APInt KnownZero, KnownOne;
15540     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15541                                           !DCI.isBeforeLegalizeOps());
15542     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15543     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15544         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15545       DCI.CommitTargetLoweringOpt(TLO);
15546   }
15547   return SDValue();
15548 }
15549
15550 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15551   SDValue Op = N->getOperand(0);
15552   if (Op.getOpcode() == ISD::BITCAST)
15553     Op = Op.getOperand(0);
15554   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15555   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15556       VT.getVectorElementType().getSizeInBits() ==
15557       OpVT.getVectorElementType().getSizeInBits()) {
15558     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15559   }
15560   return SDValue();
15561 }
15562
15563 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15564                                   TargetLowering::DAGCombinerInfo &DCI,
15565                                   const X86Subtarget *Subtarget) {
15566   if (!DCI.isBeforeLegalizeOps())
15567     return SDValue();
15568
15569   if (!Subtarget->hasAVX())
15570     return SDValue();
15571
15572   EVT VT = N->getValueType(0);
15573   SDValue Op = N->getOperand(0);
15574   EVT OpVT = Op.getValueType();
15575   DebugLoc dl = N->getDebugLoc();
15576
15577   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15578       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15579
15580     if (Subtarget->hasAVX2())
15581       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15582
15583     // Optimize vectors in AVX mode
15584     // Sign extend  v8i16 to v8i32 and
15585     //              v4i32 to v4i64
15586     //
15587     // Divide input vector into two parts
15588     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15589     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15590     // concat the vectors to original VT
15591
15592     unsigned NumElems = OpVT.getVectorNumElements();
15593     SDValue Undef = DAG.getUNDEF(OpVT);
15594
15595     SmallVector<int,8> ShufMask1(NumElems, -1);
15596     for (unsigned i = 0; i != NumElems/2; ++i)
15597       ShufMask1[i] = i;
15598
15599     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15600
15601     SmallVector<int,8> ShufMask2(NumElems, -1);
15602     for (unsigned i = 0; i != NumElems/2; ++i)
15603       ShufMask2[i] = i + NumElems/2;
15604
15605     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15606
15607     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15608                                   VT.getVectorNumElements()/2);
15609
15610     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15611     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15612
15613     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15614   }
15615   return SDValue();
15616 }
15617
15618 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15619                                  const X86Subtarget* Subtarget) {
15620   DebugLoc dl = N->getDebugLoc();
15621   EVT VT = N->getValueType(0);
15622
15623   // Let legalize expand this if it isn't a legal type yet.
15624   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15625     return SDValue();
15626
15627   EVT ScalarVT = VT.getScalarType();
15628   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15629       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15630     return SDValue();
15631
15632   SDValue A = N->getOperand(0);
15633   SDValue B = N->getOperand(1);
15634   SDValue C = N->getOperand(2);
15635
15636   bool NegA = (A.getOpcode() == ISD::FNEG);
15637   bool NegB = (B.getOpcode() == ISD::FNEG);
15638   bool NegC = (C.getOpcode() == ISD::FNEG);
15639
15640   // Negative multiplication when NegA xor NegB
15641   bool NegMul = (NegA != NegB);
15642   if (NegA)
15643     A = A.getOperand(0);
15644   if (NegB)
15645     B = B.getOperand(0);
15646   if (NegC)
15647     C = C.getOperand(0);
15648
15649   unsigned Opcode;
15650   if (!NegMul)
15651     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15652   else
15653     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15654
15655   return DAG.getNode(Opcode, dl, VT, A, B, C);
15656 }
15657
15658 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15659                                   TargetLowering::DAGCombinerInfo &DCI,
15660                                   const X86Subtarget *Subtarget) {
15661   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15662   //           (and (i32 x86isd::setcc_carry), 1)
15663   // This eliminates the zext. This transformation is necessary because
15664   // ISD::SETCC is always legalized to i8.
15665   DebugLoc dl = N->getDebugLoc();
15666   SDValue N0 = N->getOperand(0);
15667   EVT VT = N->getValueType(0);
15668   EVT OpVT = N0.getValueType();
15669
15670   if (N0.getOpcode() == ISD::AND &&
15671       N0.hasOneUse() &&
15672       N0.getOperand(0).hasOneUse()) {
15673     SDValue N00 = N0.getOperand(0);
15674     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15675       return SDValue();
15676     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15677     if (!C || C->getZExtValue() != 1)
15678       return SDValue();
15679     return DAG.getNode(ISD::AND, dl, VT,
15680                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15681                                    N00.getOperand(0), N00.getOperand(1)),
15682                        DAG.getConstant(1, VT));
15683   }
15684
15685   // Optimize vectors in AVX mode:
15686   //
15687   //   v8i16 -> v8i32
15688   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15689   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15690   //   Concat upper and lower parts.
15691   //
15692   //   v4i32 -> v4i64
15693   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15694   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15695   //   Concat upper and lower parts.
15696   //
15697   if (!DCI.isBeforeLegalizeOps())
15698     return SDValue();
15699
15700   if (!Subtarget->hasAVX())
15701     return SDValue();
15702
15703   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15704       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15705
15706     if (Subtarget->hasAVX2())
15707       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15708
15709     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15710     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15711     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15712
15713     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15714                                VT.getVectorNumElements()/2);
15715
15716     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15717     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15718
15719     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15720   }
15721
15722   return SDValue();
15723 }
15724
15725 // Optimize x == -y --> x+y == 0
15726 //          x != -y --> x+y != 0
15727 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15728   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15729   SDValue LHS = N->getOperand(0);
15730   SDValue RHS = N->getOperand(1);
15731
15732   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15733     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15734       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15735         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15736                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15737         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15738                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15739       }
15740   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15741     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15742       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15743         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15744                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15745         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15746                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15747       }
15748   return SDValue();
15749 }
15750
15751 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15752 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15753                                    TargetLowering::DAGCombinerInfo &DCI,
15754                                    const X86Subtarget *Subtarget) {
15755   DebugLoc DL = N->getDebugLoc();
15756   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15757   SDValue EFLAGS = N->getOperand(1);
15758
15759   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15760   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15761   // cases.
15762   if (CC == X86::COND_B)
15763     return DAG.getNode(ISD::AND, DL, MVT::i8,
15764                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15765                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
15766                        DAG.getConstant(1, MVT::i8));
15767
15768   SDValue Flags;
15769
15770   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15771   if (Flags.getNode()) {
15772     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15773     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15774   }
15775
15776   Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15777   if (Flags.getNode()) {
15778     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15779     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15780   }
15781
15782   return SDValue();
15783 }
15784
15785 // Optimize branch condition evaluation.
15786 //
15787 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15788                                     TargetLowering::DAGCombinerInfo &DCI,
15789                                     const X86Subtarget *Subtarget) {
15790   DebugLoc DL = N->getDebugLoc();
15791   SDValue Chain = N->getOperand(0);
15792   SDValue Dest = N->getOperand(1);
15793   SDValue EFLAGS = N->getOperand(3);
15794   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15795
15796   SDValue Flags;
15797
15798   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15799   if (Flags.getNode()) {
15800     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15801     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15802                        Flags);
15803   }
15804
15805   Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15806   if (Flags.getNode()) {
15807     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15808     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15809                        Flags);
15810   }
15811
15812   return SDValue();
15813 }
15814
15815 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15816   SDValue Op0 = N->getOperand(0);
15817   EVT InVT = Op0->getValueType(0);
15818
15819   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15820   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15821     DebugLoc dl = N->getDebugLoc();
15822     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15823     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15824     // Notice that we use SINT_TO_FP because we know that the high bits
15825     // are zero and SINT_TO_FP is better supported by the hardware.
15826     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15827   }
15828
15829   return SDValue();
15830 }
15831
15832 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15833                                         const X86TargetLowering *XTLI) {
15834   SDValue Op0 = N->getOperand(0);
15835   EVT InVT = Op0->getValueType(0);
15836
15837   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15838   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15839     DebugLoc dl = N->getDebugLoc();
15840     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15841     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15842     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15843   }
15844
15845   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15846   // a 32-bit target where SSE doesn't support i64->FP operations.
15847   if (Op0.getOpcode() == ISD::LOAD) {
15848     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15849     EVT VT = Ld->getValueType(0);
15850     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15851         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15852         !XTLI->getSubtarget()->is64Bit() &&
15853         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15854       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15855                                           Ld->getChain(), Op0, DAG);
15856       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15857       return FILDChain;
15858     }
15859   }
15860   return SDValue();
15861 }
15862
15863 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15864   EVT VT = N->getValueType(0);
15865
15866   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15867   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15868     DebugLoc dl = N->getDebugLoc();
15869     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15870     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15871     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15872   }
15873
15874   return SDValue();
15875 }
15876
15877 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15878 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15879                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15880   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15881   // the result is either zero or one (depending on the input carry bit).
15882   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15883   if (X86::isZeroNode(N->getOperand(0)) &&
15884       X86::isZeroNode(N->getOperand(1)) &&
15885       // We don't have a good way to replace an EFLAGS use, so only do this when
15886       // dead right now.
15887       SDValue(N, 1).use_empty()) {
15888     DebugLoc DL = N->getDebugLoc();
15889     EVT VT = N->getValueType(0);
15890     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15891     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15892                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15893                                            DAG.getConstant(X86::COND_B,MVT::i8),
15894                                            N->getOperand(2)),
15895                                DAG.getConstant(1, VT));
15896     return DCI.CombineTo(N, Res1, CarryOut);
15897   }
15898
15899   return SDValue();
15900 }
15901
15902 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15903 //      (add Y, (setne X, 0)) -> sbb -1, Y
15904 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15905 //      (sub (setne X, 0), Y) -> adc -1, Y
15906 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15907   DebugLoc DL = N->getDebugLoc();
15908
15909   // Look through ZExts.
15910   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15911   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15912     return SDValue();
15913
15914   SDValue SetCC = Ext.getOperand(0);
15915   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15916     return SDValue();
15917
15918   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15919   if (CC != X86::COND_E && CC != X86::COND_NE)
15920     return SDValue();
15921
15922   SDValue Cmp = SetCC.getOperand(1);
15923   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15924       !X86::isZeroNode(Cmp.getOperand(1)) ||
15925       !Cmp.getOperand(0).getValueType().isInteger())
15926     return SDValue();
15927
15928   SDValue CmpOp0 = Cmp.getOperand(0);
15929   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15930                                DAG.getConstant(1, CmpOp0.getValueType()));
15931
15932   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15933   if (CC == X86::COND_NE)
15934     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15935                        DL, OtherVal.getValueType(), OtherVal,
15936                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15937   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15938                      DL, OtherVal.getValueType(), OtherVal,
15939                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15940 }
15941
15942 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15943 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15944                                  const X86Subtarget *Subtarget) {
15945   EVT VT = N->getValueType(0);
15946   SDValue Op0 = N->getOperand(0);
15947   SDValue Op1 = N->getOperand(1);
15948
15949   // Try to synthesize horizontal adds from adds of shuffles.
15950   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15951        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15952       isHorizontalBinOp(Op0, Op1, true))
15953     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15954
15955   return OptimizeConditionalInDecrement(N, DAG);
15956 }
15957
15958 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15959                                  const X86Subtarget *Subtarget) {
15960   SDValue Op0 = N->getOperand(0);
15961   SDValue Op1 = N->getOperand(1);
15962
15963   // X86 can't encode an immediate LHS of a sub. See if we can push the
15964   // negation into a preceding instruction.
15965   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15966     // If the RHS of the sub is a XOR with one use and a constant, invert the
15967     // immediate. Then add one to the LHS of the sub so we can turn
15968     // X-Y -> X+~Y+1, saving one register.
15969     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15970         isa<ConstantSDNode>(Op1.getOperand(1))) {
15971       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15972       EVT VT = Op0.getValueType();
15973       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15974                                    Op1.getOperand(0),
15975                                    DAG.getConstant(~XorC, VT));
15976       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15977                          DAG.getConstant(C->getAPIntValue()+1, VT));
15978     }
15979   }
15980
15981   // Try to synthesize horizontal adds from adds of shuffles.
15982   EVT VT = N->getValueType(0);
15983   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15984        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15985       isHorizontalBinOp(Op0, Op1, true))
15986     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15987
15988   return OptimizeConditionalInDecrement(N, DAG);
15989 }
15990
15991 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15992                                              DAGCombinerInfo &DCI) const {
15993   SelectionDAG &DAG = DCI.DAG;
15994   switch (N->getOpcode()) {
15995   default: break;
15996   case ISD::EXTRACT_VECTOR_ELT:
15997     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15998   case ISD::VSELECT:
15999   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16000   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16001   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16002   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16003   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16004   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16005   case ISD::SHL:
16006   case ISD::SRA:
16007   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16008   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16009   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16010   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16011   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16012   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16013   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16014   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16015   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
16016   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16017   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16018   case X86ISD::FXOR:
16019   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16020   case X86ISD::FMIN:
16021   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16022   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16023   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16024   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16025   case ISD::ANY_EXTEND:
16026   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16027   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16028   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
16029   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16030   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16031   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16032   case X86ISD::SHUFP:       // Handle all target specific shuffles
16033   case X86ISD::PALIGN:
16034   case X86ISD::UNPCKH:
16035   case X86ISD::UNPCKL:
16036   case X86ISD::MOVHLPS:
16037   case X86ISD::MOVLHPS:
16038   case X86ISD::PSHUFD:
16039   case X86ISD::PSHUFHW:
16040   case X86ISD::PSHUFLW:
16041   case X86ISD::MOVSS:
16042   case X86ISD::MOVSD:
16043   case X86ISD::VPERMILP:
16044   case X86ISD::VPERM2X128:
16045   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16046   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16047   }
16048
16049   return SDValue();
16050 }
16051
16052 /// isTypeDesirableForOp - Return true if the target has native support for
16053 /// the specified value type and it is 'desirable' to use the type for the
16054 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16055 /// instruction encodings are longer and some i16 instructions are slow.
16056 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16057   if (!isTypeLegal(VT))
16058     return false;
16059   if (VT != MVT::i16)
16060     return true;
16061
16062   switch (Opc) {
16063   default:
16064     return true;
16065   case ISD::LOAD:
16066   case ISD::SIGN_EXTEND:
16067   case ISD::ZERO_EXTEND:
16068   case ISD::ANY_EXTEND:
16069   case ISD::SHL:
16070   case ISD::SRL:
16071   case ISD::SUB:
16072   case ISD::ADD:
16073   case ISD::MUL:
16074   case ISD::AND:
16075   case ISD::OR:
16076   case ISD::XOR:
16077     return false;
16078   }
16079 }
16080
16081 /// IsDesirableToPromoteOp - This method query the target whether it is
16082 /// beneficial for dag combiner to promote the specified node. If true, it
16083 /// should return the desired promotion type by reference.
16084 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16085   EVT VT = Op.getValueType();
16086   if (VT != MVT::i16)
16087     return false;
16088
16089   bool Promote = false;
16090   bool Commute = false;
16091   switch (Op.getOpcode()) {
16092   default: break;
16093   case ISD::LOAD: {
16094     LoadSDNode *LD = cast<LoadSDNode>(Op);
16095     // If the non-extending load has a single use and it's not live out, then it
16096     // might be folded.
16097     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16098                                                      Op.hasOneUse()*/) {
16099       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16100              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16101         // The only case where we'd want to promote LOAD (rather then it being
16102         // promoted as an operand is when it's only use is liveout.
16103         if (UI->getOpcode() != ISD::CopyToReg)
16104           return false;
16105       }
16106     }
16107     Promote = true;
16108     break;
16109   }
16110   case ISD::SIGN_EXTEND:
16111   case ISD::ZERO_EXTEND:
16112   case ISD::ANY_EXTEND:
16113     Promote = true;
16114     break;
16115   case ISD::SHL:
16116   case ISD::SRL: {
16117     SDValue N0 = Op.getOperand(0);
16118     // Look out for (store (shl (load), x)).
16119     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16120       return false;
16121     Promote = true;
16122     break;
16123   }
16124   case ISD::ADD:
16125   case ISD::MUL:
16126   case ISD::AND:
16127   case ISD::OR:
16128   case ISD::XOR:
16129     Commute = true;
16130     // fallthrough
16131   case ISD::SUB: {
16132     SDValue N0 = Op.getOperand(0);
16133     SDValue N1 = Op.getOperand(1);
16134     if (!Commute && MayFoldLoad(N1))
16135       return false;
16136     // Avoid disabling potential load folding opportunities.
16137     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16138       return false;
16139     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16140       return false;
16141     Promote = true;
16142   }
16143   }
16144
16145   PVT = MVT::i32;
16146   return Promote;
16147 }
16148
16149 //===----------------------------------------------------------------------===//
16150 //                           X86 Inline Assembly Support
16151 //===----------------------------------------------------------------------===//
16152
16153 namespace {
16154   // Helper to match a string separated by whitespace.
16155   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16156     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16157
16158     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16159       StringRef piece(*args[i]);
16160       if (!s.startswith(piece)) // Check if the piece matches.
16161         return false;
16162
16163       s = s.substr(piece.size());
16164       StringRef::size_type pos = s.find_first_not_of(" \t");
16165       if (pos == 0) // We matched a prefix.
16166         return false;
16167
16168       s = s.substr(pos);
16169     }
16170
16171     return s.empty();
16172   }
16173   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16174 }
16175
16176 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16177   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16178
16179   std::string AsmStr = IA->getAsmString();
16180
16181   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16182   if (!Ty || Ty->getBitWidth() % 16 != 0)
16183     return false;
16184
16185   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16186   SmallVector<StringRef, 4> AsmPieces;
16187   SplitString(AsmStr, AsmPieces, ";\n");
16188
16189   switch (AsmPieces.size()) {
16190   default: return false;
16191   case 1:
16192     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16193     // we will turn this bswap into something that will be lowered to logical
16194     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16195     // lower so don't worry about this.
16196     // bswap $0
16197     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16198         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16199         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16200         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16201         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16202         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16203       // No need to check constraints, nothing other than the equivalent of
16204       // "=r,0" would be valid here.
16205       return IntrinsicLowering::LowerToByteSwap(CI);
16206     }
16207
16208     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16209     if (CI->getType()->isIntegerTy(16) &&
16210         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16211         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16212          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16213       AsmPieces.clear();
16214       const std::string &ConstraintsStr = IA->getConstraintString();
16215       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16216       std::sort(AsmPieces.begin(), AsmPieces.end());
16217       if (AsmPieces.size() == 4 &&
16218           AsmPieces[0] == "~{cc}" &&
16219           AsmPieces[1] == "~{dirflag}" &&
16220           AsmPieces[2] == "~{flags}" &&
16221           AsmPieces[3] == "~{fpsr}")
16222       return IntrinsicLowering::LowerToByteSwap(CI);
16223     }
16224     break;
16225   case 3:
16226     if (CI->getType()->isIntegerTy(32) &&
16227         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16228         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16229         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16230         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16231       AsmPieces.clear();
16232       const std::string &ConstraintsStr = IA->getConstraintString();
16233       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16234       std::sort(AsmPieces.begin(), AsmPieces.end());
16235       if (AsmPieces.size() == 4 &&
16236           AsmPieces[0] == "~{cc}" &&
16237           AsmPieces[1] == "~{dirflag}" &&
16238           AsmPieces[2] == "~{flags}" &&
16239           AsmPieces[3] == "~{fpsr}")
16240         return IntrinsicLowering::LowerToByteSwap(CI);
16241     }
16242
16243     if (CI->getType()->isIntegerTy(64)) {
16244       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16245       if (Constraints.size() >= 2 &&
16246           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16247           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16248         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16249         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16250             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16251             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16252           return IntrinsicLowering::LowerToByteSwap(CI);
16253       }
16254     }
16255     break;
16256   }
16257   return false;
16258 }
16259
16260
16261
16262 /// getConstraintType - Given a constraint letter, return the type of
16263 /// constraint it is for this target.
16264 X86TargetLowering::ConstraintType
16265 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16266   if (Constraint.size() == 1) {
16267     switch (Constraint[0]) {
16268     case 'R':
16269     case 'q':
16270     case 'Q':
16271     case 'f':
16272     case 't':
16273     case 'u':
16274     case 'y':
16275     case 'x':
16276     case 'Y':
16277     case 'l':
16278       return C_RegisterClass;
16279     case 'a':
16280     case 'b':
16281     case 'c':
16282     case 'd':
16283     case 'S':
16284     case 'D':
16285     case 'A':
16286       return C_Register;
16287     case 'I':
16288     case 'J':
16289     case 'K':
16290     case 'L':
16291     case 'M':
16292     case 'N':
16293     case 'G':
16294     case 'C':
16295     case 'e':
16296     case 'Z':
16297       return C_Other;
16298     default:
16299       break;
16300     }
16301   }
16302   return TargetLowering::getConstraintType(Constraint);
16303 }
16304
16305 /// Examine constraint type and operand type and determine a weight value.
16306 /// This object must already have been set up with the operand type
16307 /// and the current alternative constraint selected.
16308 TargetLowering::ConstraintWeight
16309   X86TargetLowering::getSingleConstraintMatchWeight(
16310     AsmOperandInfo &info, const char *constraint) const {
16311   ConstraintWeight weight = CW_Invalid;
16312   Value *CallOperandVal = info.CallOperandVal;
16313     // If we don't have a value, we can't do a match,
16314     // but allow it at the lowest weight.
16315   if (CallOperandVal == NULL)
16316     return CW_Default;
16317   Type *type = CallOperandVal->getType();
16318   // Look at the constraint type.
16319   switch (*constraint) {
16320   default:
16321     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16322   case 'R':
16323   case 'q':
16324   case 'Q':
16325   case 'a':
16326   case 'b':
16327   case 'c':
16328   case 'd':
16329   case 'S':
16330   case 'D':
16331   case 'A':
16332     if (CallOperandVal->getType()->isIntegerTy())
16333       weight = CW_SpecificReg;
16334     break;
16335   case 'f':
16336   case 't':
16337   case 'u':
16338       if (type->isFloatingPointTy())
16339         weight = CW_SpecificReg;
16340       break;
16341   case 'y':
16342       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16343         weight = CW_SpecificReg;
16344       break;
16345   case 'x':
16346   case 'Y':
16347     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16348         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16349       weight = CW_Register;
16350     break;
16351   case 'I':
16352     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16353       if (C->getZExtValue() <= 31)
16354         weight = CW_Constant;
16355     }
16356     break;
16357   case 'J':
16358     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16359       if (C->getZExtValue() <= 63)
16360         weight = CW_Constant;
16361     }
16362     break;
16363   case 'K':
16364     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16365       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16366         weight = CW_Constant;
16367     }
16368     break;
16369   case 'L':
16370     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16371       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16372         weight = CW_Constant;
16373     }
16374     break;
16375   case 'M':
16376     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16377       if (C->getZExtValue() <= 3)
16378         weight = CW_Constant;
16379     }
16380     break;
16381   case 'N':
16382     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16383       if (C->getZExtValue() <= 0xff)
16384         weight = CW_Constant;
16385     }
16386     break;
16387   case 'G':
16388   case 'C':
16389     if (dyn_cast<ConstantFP>(CallOperandVal)) {
16390       weight = CW_Constant;
16391     }
16392     break;
16393   case 'e':
16394     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16395       if ((C->getSExtValue() >= -0x80000000LL) &&
16396           (C->getSExtValue() <= 0x7fffffffLL))
16397         weight = CW_Constant;
16398     }
16399     break;
16400   case 'Z':
16401     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16402       if (C->getZExtValue() <= 0xffffffff)
16403         weight = CW_Constant;
16404     }
16405     break;
16406   }
16407   return weight;
16408 }
16409
16410 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16411 /// with another that has more specific requirements based on the type of the
16412 /// corresponding operand.
16413 const char *X86TargetLowering::
16414 LowerXConstraint(EVT ConstraintVT) const {
16415   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16416   // 'f' like normal targets.
16417   if (ConstraintVT.isFloatingPoint()) {
16418     if (Subtarget->hasSSE2())
16419       return "Y";
16420     if (Subtarget->hasSSE1())
16421       return "x";
16422   }
16423
16424   return TargetLowering::LowerXConstraint(ConstraintVT);
16425 }
16426
16427 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16428 /// vector.  If it is invalid, don't add anything to Ops.
16429 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16430                                                      std::string &Constraint,
16431                                                      std::vector<SDValue>&Ops,
16432                                                      SelectionDAG &DAG) const {
16433   SDValue Result(0, 0);
16434
16435   // Only support length 1 constraints for now.
16436   if (Constraint.length() > 1) return;
16437
16438   char ConstraintLetter = Constraint[0];
16439   switch (ConstraintLetter) {
16440   default: break;
16441   case 'I':
16442     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16443       if (C->getZExtValue() <= 31) {
16444         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16445         break;
16446       }
16447     }
16448     return;
16449   case 'J':
16450     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16451       if (C->getZExtValue() <= 63) {
16452         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16453         break;
16454       }
16455     }
16456     return;
16457   case 'K':
16458     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16459       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16460         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16461         break;
16462       }
16463     }
16464     return;
16465   case 'N':
16466     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16467       if (C->getZExtValue() <= 255) {
16468         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16469         break;
16470       }
16471     }
16472     return;
16473   case 'e': {
16474     // 32-bit signed value
16475     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16476       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16477                                            C->getSExtValue())) {
16478         // Widen to 64 bits here to get it sign extended.
16479         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16480         break;
16481       }
16482     // FIXME gcc accepts some relocatable values here too, but only in certain
16483     // memory models; it's complicated.
16484     }
16485     return;
16486   }
16487   case 'Z': {
16488     // 32-bit unsigned value
16489     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16490       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16491                                            C->getZExtValue())) {
16492         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16493         break;
16494       }
16495     }
16496     // FIXME gcc accepts some relocatable values here too, but only in certain
16497     // memory models; it's complicated.
16498     return;
16499   }
16500   case 'i': {
16501     // Literal immediates are always ok.
16502     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16503       // Widen to 64 bits here to get it sign extended.
16504       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16505       break;
16506     }
16507
16508     // In any sort of PIC mode addresses need to be computed at runtime by
16509     // adding in a register or some sort of table lookup.  These can't
16510     // be used as immediates.
16511     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16512       return;
16513
16514     // If we are in non-pic codegen mode, we allow the address of a global (with
16515     // an optional displacement) to be used with 'i'.
16516     GlobalAddressSDNode *GA = 0;
16517     int64_t Offset = 0;
16518
16519     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16520     while (1) {
16521       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16522         Offset += GA->getOffset();
16523         break;
16524       } else if (Op.getOpcode() == ISD::ADD) {
16525         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16526           Offset += C->getZExtValue();
16527           Op = Op.getOperand(0);
16528           continue;
16529         }
16530       } else if (Op.getOpcode() == ISD::SUB) {
16531         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16532           Offset += -C->getZExtValue();
16533           Op = Op.getOperand(0);
16534           continue;
16535         }
16536       }
16537
16538       // Otherwise, this isn't something we can handle, reject it.
16539       return;
16540     }
16541
16542     const GlobalValue *GV = GA->getGlobal();
16543     // If we require an extra load to get this address, as in PIC mode, we
16544     // can't accept it.
16545     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16546                                                         getTargetMachine())))
16547       return;
16548
16549     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16550                                         GA->getValueType(0), Offset);
16551     break;
16552   }
16553   }
16554
16555   if (Result.getNode()) {
16556     Ops.push_back(Result);
16557     return;
16558   }
16559   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16560 }
16561
16562 std::pair<unsigned, const TargetRegisterClass*>
16563 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16564                                                 EVT VT) const {
16565   // First, see if this is a constraint that directly corresponds to an LLVM
16566   // register class.
16567   if (Constraint.size() == 1) {
16568     // GCC Constraint Letters
16569     switch (Constraint[0]) {
16570     default: break;
16571       // TODO: Slight differences here in allocation order and leaving
16572       // RIP in the class. Do they matter any more here than they do
16573       // in the normal allocation?
16574     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16575       if (Subtarget->is64Bit()) {
16576         if (VT == MVT::i32 || VT == MVT::f32)
16577           return std::make_pair(0U, &X86::GR32RegClass);
16578         if (VT == MVT::i16)
16579           return std::make_pair(0U, &X86::GR16RegClass);
16580         if (VT == MVT::i8 || VT == MVT::i1)
16581           return std::make_pair(0U, &X86::GR8RegClass);
16582         if (VT == MVT::i64 || VT == MVT::f64)
16583           return std::make_pair(0U, &X86::GR64RegClass);
16584         break;
16585       }
16586       // 32-bit fallthrough
16587     case 'Q':   // Q_REGS
16588       if (VT == MVT::i32 || VT == MVT::f32)
16589         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16590       if (VT == MVT::i16)
16591         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16592       if (VT == MVT::i8 || VT == MVT::i1)
16593         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16594       if (VT == MVT::i64)
16595         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16596       break;
16597     case 'r':   // GENERAL_REGS
16598     case 'l':   // INDEX_REGS
16599       if (VT == MVT::i8 || VT == MVT::i1)
16600         return std::make_pair(0U, &X86::GR8RegClass);
16601       if (VT == MVT::i16)
16602         return std::make_pair(0U, &X86::GR16RegClass);
16603       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16604         return std::make_pair(0U, &X86::GR32RegClass);
16605       return std::make_pair(0U, &X86::GR64RegClass);
16606     case 'R':   // LEGACY_REGS
16607       if (VT == MVT::i8 || VT == MVT::i1)
16608         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16609       if (VT == MVT::i16)
16610         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16611       if (VT == MVT::i32 || !Subtarget->is64Bit())
16612         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16613       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16614     case 'f':  // FP Stack registers.
16615       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16616       // value to the correct fpstack register class.
16617       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16618         return std::make_pair(0U, &X86::RFP32RegClass);
16619       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16620         return std::make_pair(0U, &X86::RFP64RegClass);
16621       return std::make_pair(0U, &X86::RFP80RegClass);
16622     case 'y':   // MMX_REGS if MMX allowed.
16623       if (!Subtarget->hasMMX()) break;
16624       return std::make_pair(0U, &X86::VR64RegClass);
16625     case 'Y':   // SSE_REGS if SSE2 allowed
16626       if (!Subtarget->hasSSE2()) break;
16627       // FALL THROUGH.
16628     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16629       if (!Subtarget->hasSSE1()) break;
16630
16631       switch (VT.getSimpleVT().SimpleTy) {
16632       default: break;
16633       // Scalar SSE types.
16634       case MVT::f32:
16635       case MVT::i32:
16636         return std::make_pair(0U, &X86::FR32RegClass);
16637       case MVT::f64:
16638       case MVT::i64:
16639         return std::make_pair(0U, &X86::FR64RegClass);
16640       // Vector types.
16641       case MVT::v16i8:
16642       case MVT::v8i16:
16643       case MVT::v4i32:
16644       case MVT::v2i64:
16645       case MVT::v4f32:
16646       case MVT::v2f64:
16647         return std::make_pair(0U, &X86::VR128RegClass);
16648       // AVX types.
16649       case MVT::v32i8:
16650       case MVT::v16i16:
16651       case MVT::v8i32:
16652       case MVT::v4i64:
16653       case MVT::v8f32:
16654       case MVT::v4f64:
16655         return std::make_pair(0U, &X86::VR256RegClass);
16656       }
16657       break;
16658     }
16659   }
16660
16661   // Use the default implementation in TargetLowering to convert the register
16662   // constraint into a member of a register class.
16663   std::pair<unsigned, const TargetRegisterClass*> Res;
16664   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16665
16666   // Not found as a standard register?
16667   if (Res.second == 0) {
16668     // Map st(0) -> st(7) -> ST0
16669     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16670         tolower(Constraint[1]) == 's' &&
16671         tolower(Constraint[2]) == 't' &&
16672         Constraint[3] == '(' &&
16673         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16674         Constraint[5] == ')' &&
16675         Constraint[6] == '}') {
16676
16677       Res.first = X86::ST0+Constraint[4]-'0';
16678       Res.second = &X86::RFP80RegClass;
16679       return Res;
16680     }
16681
16682     // GCC allows "st(0)" to be called just plain "st".
16683     if (StringRef("{st}").equals_lower(Constraint)) {
16684       Res.first = X86::ST0;
16685       Res.second = &X86::RFP80RegClass;
16686       return Res;
16687     }
16688
16689     // flags -> EFLAGS
16690     if (StringRef("{flags}").equals_lower(Constraint)) {
16691       Res.first = X86::EFLAGS;
16692       Res.second = &X86::CCRRegClass;
16693       return Res;
16694     }
16695
16696     // 'A' means EAX + EDX.
16697     if (Constraint == "A") {
16698       Res.first = X86::EAX;
16699       Res.second = &X86::GR32_ADRegClass;
16700       return Res;
16701     }
16702     return Res;
16703   }
16704
16705   // Otherwise, check to see if this is a register class of the wrong value
16706   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16707   // turn into {ax},{dx}.
16708   if (Res.second->hasType(VT))
16709     return Res;   // Correct type already, nothing to do.
16710
16711   // All of the single-register GCC register classes map their values onto
16712   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16713   // really want an 8-bit or 32-bit register, map to the appropriate register
16714   // class and return the appropriate register.
16715   if (Res.second == &X86::GR16RegClass) {
16716     if (VT == MVT::i8) {
16717       unsigned DestReg = 0;
16718       switch (Res.first) {
16719       default: break;
16720       case X86::AX: DestReg = X86::AL; break;
16721       case X86::DX: DestReg = X86::DL; break;
16722       case X86::CX: DestReg = X86::CL; break;
16723       case X86::BX: DestReg = X86::BL; break;
16724       }
16725       if (DestReg) {
16726         Res.first = DestReg;
16727         Res.second = &X86::GR8RegClass;
16728       }
16729     } else if (VT == MVT::i32) {
16730       unsigned DestReg = 0;
16731       switch (Res.first) {
16732       default: break;
16733       case X86::AX: DestReg = X86::EAX; break;
16734       case X86::DX: DestReg = X86::EDX; break;
16735       case X86::CX: DestReg = X86::ECX; break;
16736       case X86::BX: DestReg = X86::EBX; break;
16737       case X86::SI: DestReg = X86::ESI; break;
16738       case X86::DI: DestReg = X86::EDI; break;
16739       case X86::BP: DestReg = X86::EBP; break;
16740       case X86::SP: DestReg = X86::ESP; break;
16741       }
16742       if (DestReg) {
16743         Res.first = DestReg;
16744         Res.second = &X86::GR32RegClass;
16745       }
16746     } else if (VT == MVT::i64) {
16747       unsigned DestReg = 0;
16748       switch (Res.first) {
16749       default: break;
16750       case X86::AX: DestReg = X86::RAX; break;
16751       case X86::DX: DestReg = X86::RDX; break;
16752       case X86::CX: DestReg = X86::RCX; break;
16753       case X86::BX: DestReg = X86::RBX; break;
16754       case X86::SI: DestReg = X86::RSI; break;
16755       case X86::DI: DestReg = X86::RDI; break;
16756       case X86::BP: DestReg = X86::RBP; break;
16757       case X86::SP: DestReg = X86::RSP; break;
16758       }
16759       if (DestReg) {
16760         Res.first = DestReg;
16761         Res.second = &X86::GR64RegClass;
16762       }
16763     }
16764   } else if (Res.second == &X86::FR32RegClass ||
16765              Res.second == &X86::FR64RegClass ||
16766              Res.second == &X86::VR128RegClass) {
16767     // Handle references to XMM physical registers that got mapped into the
16768     // wrong class.  This can happen with constraints like {xmm0} where the
16769     // target independent register mapper will just pick the first match it can
16770     // find, ignoring the required type.
16771
16772     if (VT == MVT::f32 || VT == MVT::i32)
16773       Res.second = &X86::FR32RegClass;
16774     else if (VT == MVT::f64 || VT == MVT::i64)
16775       Res.second = &X86::FR64RegClass;
16776     else if (X86::VR128RegClass.hasType(VT))
16777       Res.second = &X86::VR128RegClass;
16778     else if (X86::VR256RegClass.hasType(VT))
16779       Res.second = &X86::VR256RegClass;
16780   }
16781
16782   return Res;
16783 }