b0dc5b7b687afea36af34e96dce5c1e996c47802
[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.getIntPtrConstant(NormalizedIdxVal);
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.getIntPtrConstant(NormalizedIdxVal);
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::FFLOOR, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
758     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
763     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
764     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
765     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
766     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
767     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
768     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
769     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
770     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
771     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
772     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
773     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
774     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
775     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
776              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
777       setTruncStoreAction((MVT::SimpleValueType)VT,
778                           (MVT::SimpleValueType)InnerVT, Expand);
779     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
780     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
781     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
782   }
783
784   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
785   // with -msoft-float, disable use of MMX as well.
786   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
787     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
788     // No operations on x86mmx supported, everything uses intrinsics.
789   }
790
791   // MMX-sized vectors (other than x86mmx) are expected to be expanded
792   // into smaller operations.
793   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
794   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
795   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
796   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
797   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
798   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
799   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
800   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
801   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
802   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
803   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
804   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
805   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
806   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
807   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
808   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
809   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
810   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
811   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
812   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
813   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
814   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
815   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
816   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
817   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
818   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
819   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
820   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
821   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
822
823   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
824     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
825
826     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
832     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
833     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
834     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
835     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
836     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
837     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
838   }
839
840   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
841     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
842
843     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
844     // registers cannot be used even for integer operations.
845     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
846     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
847     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
848     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
849
850     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
851     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
852     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
853     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
854     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
855     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
856     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
857     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
858     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
859     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
860     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
861     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
862     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
863     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
864     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
865     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
866     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
867
868     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
869     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
870     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
871     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
872
873     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
874     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
875     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
876     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
877     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
878
879     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
880     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
881       MVT VT = (MVT::SimpleValueType)i;
882       // Do not attempt to custom lower non-power-of-2 vectors
883       if (!isPowerOf2_32(VT.getVectorNumElements()))
884         continue;
885       // Do not attempt to custom lower non-128-bit vectors
886       if (!VT.is128BitVector())
887         continue;
888       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
889       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
890       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
891     }
892
893     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
894     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
895     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
896     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
897     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
898     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
899
900     if (Subtarget->is64Bit()) {
901       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
902       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
903     }
904
905     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
906     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
907       MVT VT = (MVT::SimpleValueType)i;
908
909       // Do not attempt to promote non-128-bit vectors
910       if (!VT.is128BitVector())
911         continue;
912
913       setOperationAction(ISD::AND,    VT, Promote);
914       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
915       setOperationAction(ISD::OR,     VT, Promote);
916       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
917       setOperationAction(ISD::XOR,    VT, Promote);
918       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
919       setOperationAction(ISD::LOAD,   VT, Promote);
920       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
921       setOperationAction(ISD::SELECT, VT, Promote);
922       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
923     }
924
925     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
926
927     // Custom lower v2i64 and v2f64 selects.
928     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
929     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
930     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
931     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
932
933     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
934     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
935   }
936
937   if (Subtarget->hasSSE41()) {
938     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
939     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
940     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
941     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
942     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
943     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
944     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
945     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
946     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
947     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
948
949     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
950     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
951
952     // FIXME: Do we need to handle scalar-to-vector here?
953     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
954
955     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
956     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
957     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
958     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
959     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
960
961     // i8 and i16 vectors are custom , because the source register and source
962     // source memory operand types are not the same width.  f32 vectors are
963     // custom since the immediate controlling the insert encodes additional
964     // information.
965     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
968     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
969
970     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
971     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
972     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
973     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
974
975     // FIXME: these should be Legal but thats only for the case where
976     // the index is constant.  For now custom expand to deal with that.
977     if (Subtarget->is64Bit()) {
978       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
979       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
980     }
981   }
982
983   if (Subtarget->hasSSE2()) {
984     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
985     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
986
987     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
988     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
989
990     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
991     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
992
993     if (Subtarget->hasAVX2()) {
994       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
995       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
996
997       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
998       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
999
1000       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1001     } else {
1002       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1003       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1004
1005       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1006       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1007
1008       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1009     }
1010   }
1011
1012   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1013     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1014     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1015     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1016     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1017     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1018     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1019
1020     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1021     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1022     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1023
1024     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1025     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1026     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1027     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1028     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1029     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1030     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1031     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1032
1033     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1034     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1035     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1036     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1037     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1038     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1039     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1040     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1041
1042     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1043     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1044     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1045
1046     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1047     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1048
1049     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1050     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1051
1052     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1053     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1054
1055     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1056     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1057     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1058     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1059
1060     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1061     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1062     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1065     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1066     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1067     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1068
1069     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1070       setOperationAction(ISD::FMA,             MVT::v8f32, Custom);
1071       setOperationAction(ISD::FMA,             MVT::v4f64, Custom);
1072       setOperationAction(ISD::FMA,             MVT::v4f32, Custom);
1073       setOperationAction(ISD::FMA,             MVT::v2f64, Custom);
1074       setOperationAction(ISD::FMA,             MVT::f32, Custom);
1075       setOperationAction(ISD::FMA,             MVT::f64, Custom);
1076     }
1077
1078     if (Subtarget->hasAVX2()) {
1079       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1080       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1081       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1082       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1083
1084       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1085       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1086       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1087       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1088
1089       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1090       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1091       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1092       // Don't lower v32i8 because there is no 128-bit byte mul
1093
1094       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1095
1096       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1097       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1098
1099       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1100       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1101
1102       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1103     } else {
1104       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1105       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1106       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1107       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1108
1109       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1110       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1111       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1112       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1113
1114       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1115       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1116       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1117       // Don't lower v32i8 because there is no 128-bit byte mul
1118
1119       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1120       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1121
1122       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1123       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1124
1125       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1126     }
1127
1128     // Custom lower several nodes for 256-bit types.
1129     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1130              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1131       MVT VT = (MVT::SimpleValueType)i;
1132
1133       // Extract subvector is special because the value type
1134       // (result) is 128-bit but the source is 256-bit wide.
1135       if (VT.is128BitVector())
1136         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1137
1138       // Do not attempt to custom lower other non-256-bit vectors
1139       if (!VT.is256BitVector())
1140         continue;
1141
1142       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1143       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1144       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1145       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1146       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1147       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1148       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1149     }
1150
1151     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1152     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1153       MVT VT = (MVT::SimpleValueType)i;
1154
1155       // Do not attempt to promote non-256-bit vectors
1156       if (!VT.is256BitVector())
1157         continue;
1158
1159       setOperationAction(ISD::AND,    VT, Promote);
1160       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1161       setOperationAction(ISD::OR,     VT, Promote);
1162       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1163       setOperationAction(ISD::XOR,    VT, Promote);
1164       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1165       setOperationAction(ISD::LOAD,   VT, Promote);
1166       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1167       setOperationAction(ISD::SELECT, VT, Promote);
1168       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1169     }
1170   }
1171
1172   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1173   // of this type with custom code.
1174   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1175            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1176     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1177                        Custom);
1178   }
1179
1180   // We want to custom lower some of our intrinsics.
1181   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1182   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1183
1184
1185   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1186   // handle type legalization for these operations here.
1187   //
1188   // FIXME: We really should do custom legalization for addition and
1189   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1190   // than generic legalization for 64-bit multiplication-with-overflow, though.
1191   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1192     // Add/Sub/Mul with overflow operations are custom lowered.
1193     MVT VT = IntVTs[i];
1194     setOperationAction(ISD::SADDO, VT, Custom);
1195     setOperationAction(ISD::UADDO, VT, Custom);
1196     setOperationAction(ISD::SSUBO, VT, Custom);
1197     setOperationAction(ISD::USUBO, VT, Custom);
1198     setOperationAction(ISD::SMULO, VT, Custom);
1199     setOperationAction(ISD::UMULO, VT, Custom);
1200   }
1201
1202   // There are no 8-bit 3-address imul/mul instructions
1203   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1204   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1205
1206   if (!Subtarget->is64Bit()) {
1207     // These libcalls are not available in 32-bit.
1208     setLibcallName(RTLIB::SHL_I128, 0);
1209     setLibcallName(RTLIB::SRL_I128, 0);
1210     setLibcallName(RTLIB::SRA_I128, 0);
1211   }
1212
1213   // We have target-specific dag combine patterns for the following nodes:
1214   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1215   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1216   setTargetDAGCombine(ISD::VSELECT);
1217   setTargetDAGCombine(ISD::SELECT);
1218   setTargetDAGCombine(ISD::SHL);
1219   setTargetDAGCombine(ISD::SRA);
1220   setTargetDAGCombine(ISD::SRL);
1221   setTargetDAGCombine(ISD::OR);
1222   setTargetDAGCombine(ISD::AND);
1223   setTargetDAGCombine(ISD::ADD);
1224   setTargetDAGCombine(ISD::FADD);
1225   setTargetDAGCombine(ISD::FSUB);
1226   setTargetDAGCombine(ISD::FMA);
1227   setTargetDAGCombine(ISD::SUB);
1228   setTargetDAGCombine(ISD::LOAD);
1229   setTargetDAGCombine(ISD::STORE);
1230   setTargetDAGCombine(ISD::ZERO_EXTEND);
1231   setTargetDAGCombine(ISD::ANY_EXTEND);
1232   setTargetDAGCombine(ISD::SIGN_EXTEND);
1233   setTargetDAGCombine(ISD::TRUNCATE);
1234   setTargetDAGCombine(ISD::UINT_TO_FP);
1235   setTargetDAGCombine(ISD::SINT_TO_FP);
1236   setTargetDAGCombine(ISD::SETCC);
1237   setTargetDAGCombine(ISD::FP_TO_SINT);
1238   if (Subtarget->is64Bit())
1239     setTargetDAGCombine(ISD::MUL);
1240   setTargetDAGCombine(ISD::XOR);
1241
1242   computeRegisterProperties();
1243
1244   // On Darwin, -Os means optimize for size without hurting performance,
1245   // do not reduce the limit.
1246   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1247   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1248   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1249   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1250   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1251   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1252   setPrefLoopAlignment(4); // 2^4 bytes.
1253   benefitFromCodePlacementOpt = true;
1254
1255   // Predictable cmov don't hurt on atom because it's in-order.
1256   predictableSelectIsExpensive = !Subtarget->isAtom();
1257
1258   setPrefFunctionAlignment(4); // 2^4 bytes.
1259 }
1260
1261
1262 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1263   if (!VT.isVector()) return MVT::i8;
1264   return VT.changeVectorElementTypeToInteger();
1265 }
1266
1267
1268 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1269 /// the desired ByVal argument alignment.
1270 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1271   if (MaxAlign == 16)
1272     return;
1273   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1274     if (VTy->getBitWidth() == 128)
1275       MaxAlign = 16;
1276   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1277     unsigned EltAlign = 0;
1278     getMaxByValAlign(ATy->getElementType(), EltAlign);
1279     if (EltAlign > MaxAlign)
1280       MaxAlign = EltAlign;
1281   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1282     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1283       unsigned EltAlign = 0;
1284       getMaxByValAlign(STy->getElementType(i), EltAlign);
1285       if (EltAlign > MaxAlign)
1286         MaxAlign = EltAlign;
1287       if (MaxAlign == 16)
1288         break;
1289     }
1290   }
1291 }
1292
1293 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1294 /// function arguments in the caller parameter area. For X86, aggregates
1295 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1296 /// are at 4-byte boundaries.
1297 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1298   if (Subtarget->is64Bit()) {
1299     // Max of 8 and alignment of type.
1300     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1301     if (TyAlign > 8)
1302       return TyAlign;
1303     return 8;
1304   }
1305
1306   unsigned Align = 4;
1307   if (Subtarget->hasSSE1())
1308     getMaxByValAlign(Ty, Align);
1309   return Align;
1310 }
1311
1312 /// getOptimalMemOpType - Returns the target specific optimal type for load
1313 /// and store operations as a result of memset, memcpy, and memmove
1314 /// lowering. If DstAlign is zero that means it's safe to destination
1315 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1316 /// means there isn't a need to check it against alignment requirement,
1317 /// probably because the source does not need to be loaded. If
1318 /// 'IsZeroVal' is true, that means it's safe to return a
1319 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1320 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1321 /// constant so it does not need to be loaded.
1322 /// It returns EVT::Other if the type should be determined using generic
1323 /// target-independent logic.
1324 EVT
1325 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1326                                        unsigned DstAlign, unsigned SrcAlign,
1327                                        bool IsZeroVal,
1328                                        bool MemcpyStrSrc,
1329                                        MachineFunction &MF) const {
1330   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1331   // linux.  This is because the stack realignment code can't handle certain
1332   // cases like PR2962.  This should be removed when PR2962 is fixed.
1333   const Function *F = MF.getFunction();
1334   if (IsZeroVal &&
1335       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1336     if (Size >= 16 &&
1337         (Subtarget->isUnalignedMemAccessFast() ||
1338          ((DstAlign == 0 || DstAlign >= 16) &&
1339           (SrcAlign == 0 || SrcAlign >= 16))) &&
1340         Subtarget->getStackAlignment() >= 16) {
1341       if (Subtarget->getStackAlignment() >= 32) {
1342         if (Subtarget->hasAVX2())
1343           return MVT::v8i32;
1344         if (Subtarget->hasAVX())
1345           return MVT::v8f32;
1346       }
1347       if (Subtarget->hasSSE2())
1348         return MVT::v4i32;
1349       if (Subtarget->hasSSE1())
1350         return MVT::v4f32;
1351     } else if (!MemcpyStrSrc && Size >= 8 &&
1352                !Subtarget->is64Bit() &&
1353                Subtarget->getStackAlignment() >= 8 &&
1354                Subtarget->hasSSE2()) {
1355       // Do not use f64 to lower memcpy if source is string constant. It's
1356       // better to use i32 to avoid the loads.
1357       return MVT::f64;
1358     }
1359   }
1360   if (Subtarget->is64Bit() && Size >= 8)
1361     return MVT::i64;
1362   return MVT::i32;
1363 }
1364
1365 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1366 /// current function.  The returned value is a member of the
1367 /// MachineJumpTableInfo::JTEntryKind enum.
1368 unsigned X86TargetLowering::getJumpTableEncoding() const {
1369   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1370   // symbol.
1371   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1372       Subtarget->isPICStyleGOT())
1373     return MachineJumpTableInfo::EK_Custom32;
1374
1375   // Otherwise, use the normal jump table encoding heuristics.
1376   return TargetLowering::getJumpTableEncoding();
1377 }
1378
1379 const MCExpr *
1380 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1381                                              const MachineBasicBlock *MBB,
1382                                              unsigned uid,MCContext &Ctx) const{
1383   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1384          Subtarget->isPICStyleGOT());
1385   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1386   // entries.
1387   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1388                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1389 }
1390
1391 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1392 /// jumptable.
1393 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1394                                                     SelectionDAG &DAG) const {
1395   if (!Subtarget->is64Bit())
1396     // This doesn't have DebugLoc associated with it, but is not really the
1397     // same as a Register.
1398     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1399   return Table;
1400 }
1401
1402 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1403 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1404 /// MCExpr.
1405 const MCExpr *X86TargetLowering::
1406 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1407                              MCContext &Ctx) const {
1408   // X86-64 uses RIP relative addressing based on the jump table label.
1409   if (Subtarget->isPICStyleRIPRel())
1410     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1411
1412   // Otherwise, the reference is relative to the PIC base.
1413   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1414 }
1415
1416 // FIXME: Why this routine is here? Move to RegInfo!
1417 std::pair<const TargetRegisterClass*, uint8_t>
1418 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1419   const TargetRegisterClass *RRC = 0;
1420   uint8_t Cost = 1;
1421   switch (VT.getSimpleVT().SimpleTy) {
1422   default:
1423     return TargetLowering::findRepresentativeClass(VT);
1424   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1425     RRC = Subtarget->is64Bit() ?
1426       (const TargetRegisterClass*)&X86::GR64RegClass :
1427       (const TargetRegisterClass*)&X86::GR32RegClass;
1428     break;
1429   case MVT::x86mmx:
1430     RRC = &X86::VR64RegClass;
1431     break;
1432   case MVT::f32: case MVT::f64:
1433   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1434   case MVT::v4f32: case MVT::v2f64:
1435   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1436   case MVT::v4f64:
1437     RRC = &X86::VR128RegClass;
1438     break;
1439   }
1440   return std::make_pair(RRC, Cost);
1441 }
1442
1443 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1444                                                unsigned &Offset) const {
1445   if (!Subtarget->isTargetLinux())
1446     return false;
1447
1448   if (Subtarget->is64Bit()) {
1449     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1450     Offset = 0x28;
1451     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1452       AddressSpace = 256;
1453     else
1454       AddressSpace = 257;
1455   } else {
1456     // %gs:0x14 on i386
1457     Offset = 0x14;
1458     AddressSpace = 256;
1459   }
1460   return true;
1461 }
1462
1463
1464 //===----------------------------------------------------------------------===//
1465 //               Return Value Calling Convention Implementation
1466 //===----------------------------------------------------------------------===//
1467
1468 #include "X86GenCallingConv.inc"
1469
1470 bool
1471 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1472                                   MachineFunction &MF, bool isVarArg,
1473                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1474                         LLVMContext &Context) const {
1475   SmallVector<CCValAssign, 16> RVLocs;
1476   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1477                  RVLocs, Context);
1478   return CCInfo.CheckReturn(Outs, RetCC_X86);
1479 }
1480
1481 SDValue
1482 X86TargetLowering::LowerReturn(SDValue Chain,
1483                                CallingConv::ID CallConv, bool isVarArg,
1484                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1485                                const SmallVectorImpl<SDValue> &OutVals,
1486                                DebugLoc dl, SelectionDAG &DAG) const {
1487   MachineFunction &MF = DAG.getMachineFunction();
1488   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1489
1490   SmallVector<CCValAssign, 16> RVLocs;
1491   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1492                  RVLocs, *DAG.getContext());
1493   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1494
1495   // Add the regs to the liveout set for the function.
1496   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1497   for (unsigned i = 0; i != RVLocs.size(); ++i)
1498     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1499       MRI.addLiveOut(RVLocs[i].getLocReg());
1500
1501   SDValue Flag;
1502
1503   SmallVector<SDValue, 6> RetOps;
1504   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1505   // Operand #1 = Bytes To Pop
1506   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1507                    MVT::i16));
1508
1509   // Copy the result values into the output registers.
1510   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1511     CCValAssign &VA = RVLocs[i];
1512     assert(VA.isRegLoc() && "Can only return in registers!");
1513     SDValue ValToCopy = OutVals[i];
1514     EVT ValVT = ValToCopy.getValueType();
1515
1516     // Promote values to the appropriate types
1517     if (VA.getLocInfo() == CCValAssign::SExt)
1518       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1519     else if (VA.getLocInfo() == CCValAssign::ZExt)
1520       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1521     else if (VA.getLocInfo() == CCValAssign::AExt)
1522       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1523     else if (VA.getLocInfo() == CCValAssign::BCvt)
1524       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1525
1526     // If this is x86-64, and we disabled SSE, we can't return FP values,
1527     // or SSE or MMX vectors.
1528     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1529          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1530           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1531       report_fatal_error("SSE register return with SSE disabled");
1532     }
1533     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1534     // llvm-gcc has never done it right and no one has noticed, so this
1535     // should be OK for now.
1536     if (ValVT == MVT::f64 &&
1537         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1538       report_fatal_error("SSE2 register return with SSE2 disabled");
1539
1540     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1541     // the RET instruction and handled by the FP Stackifier.
1542     if (VA.getLocReg() == X86::ST0 ||
1543         VA.getLocReg() == X86::ST1) {
1544       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1545       // change the value to the FP stack register class.
1546       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1547         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1548       RetOps.push_back(ValToCopy);
1549       // Don't emit a copytoreg.
1550       continue;
1551     }
1552
1553     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1554     // which is returned in RAX / RDX.
1555     if (Subtarget->is64Bit()) {
1556       if (ValVT == MVT::x86mmx) {
1557         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1558           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1559           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1560                                   ValToCopy);
1561           // If we don't have SSE2 available, convert to v4f32 so the generated
1562           // register is legal.
1563           if (!Subtarget->hasSSE2())
1564             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1565         }
1566       }
1567     }
1568
1569     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1570     Flag = Chain.getValue(1);
1571   }
1572
1573   // The x86-64 ABI for returning structs by value requires that we copy
1574   // the sret argument into %rax for the return. We saved the argument into
1575   // a virtual register in the entry block, so now we copy the value out
1576   // and into %rax.
1577   if (Subtarget->is64Bit() &&
1578       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1579     MachineFunction &MF = DAG.getMachineFunction();
1580     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1581     unsigned Reg = FuncInfo->getSRetReturnReg();
1582     assert(Reg &&
1583            "SRetReturnReg should have been set in LowerFormalArguments().");
1584     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1585
1586     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1587     Flag = Chain.getValue(1);
1588
1589     // RAX now acts like a return value.
1590     MRI.addLiveOut(X86::RAX);
1591   }
1592
1593   RetOps[0] = Chain;  // Update chain.
1594
1595   // Add the flag if we have it.
1596   if (Flag.getNode())
1597     RetOps.push_back(Flag);
1598
1599   return DAG.getNode(X86ISD::RET_FLAG, dl,
1600                      MVT::Other, &RetOps[0], RetOps.size());
1601 }
1602
1603 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1604   if (N->getNumValues() != 1)
1605     return false;
1606   if (!N->hasNUsesOfValue(1, 0))
1607     return false;
1608
1609   SDValue TCChain = Chain;
1610   SDNode *Copy = *N->use_begin();
1611   if (Copy->getOpcode() == ISD::CopyToReg) {
1612     // If the copy has a glue operand, we conservatively assume it isn't safe to
1613     // perform a tail call.
1614     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1615       return false;
1616     TCChain = Copy->getOperand(0);
1617   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1618     return false;
1619
1620   bool HasRet = false;
1621   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1622        UI != UE; ++UI) {
1623     if (UI->getOpcode() != X86ISD::RET_FLAG)
1624       return false;
1625     HasRet = true;
1626   }
1627
1628   if (!HasRet)
1629     return false;
1630
1631   Chain = TCChain;
1632   return true;
1633 }
1634
1635 EVT
1636 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1637                                             ISD::NodeType ExtendKind) const {
1638   MVT ReturnMVT;
1639   // TODO: Is this also valid on 32-bit?
1640   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1641     ReturnMVT = MVT::i8;
1642   else
1643     ReturnMVT = MVT::i32;
1644
1645   EVT MinVT = getRegisterType(Context, ReturnMVT);
1646   return VT.bitsLT(MinVT) ? MinVT : VT;
1647 }
1648
1649 /// LowerCallResult - Lower the result values of a call into the
1650 /// appropriate copies out of appropriate physical registers.
1651 ///
1652 SDValue
1653 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1654                                    CallingConv::ID CallConv, bool isVarArg,
1655                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1656                                    DebugLoc dl, SelectionDAG &DAG,
1657                                    SmallVectorImpl<SDValue> &InVals) const {
1658
1659   // Assign locations to each value returned by this call.
1660   SmallVector<CCValAssign, 16> RVLocs;
1661   bool Is64Bit = Subtarget->is64Bit();
1662   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1663                  getTargetMachine(), RVLocs, *DAG.getContext());
1664   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1665
1666   // Copy all of the result registers out of their specified physreg.
1667   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1668     CCValAssign &VA = RVLocs[i];
1669     EVT CopyVT = VA.getValVT();
1670
1671     // If this is x86-64, and we disabled SSE, we can't return FP values
1672     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1673         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1674       report_fatal_error("SSE register return with SSE disabled");
1675     }
1676
1677     SDValue Val;
1678
1679     // If this is a call to a function that returns an fp value on the floating
1680     // point stack, we must guarantee the value is popped from the stack, so
1681     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1682     // if the return value is not used. We use the FpPOP_RETVAL instruction
1683     // instead.
1684     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1685       // If we prefer to use the value in xmm registers, copy it out as f80 and
1686       // use a truncate to move it from fp stack reg to xmm reg.
1687       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1688       SDValue Ops[] = { Chain, InFlag };
1689       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1690                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1691       Val = Chain.getValue(0);
1692
1693       // Round the f80 to the right size, which also moves it to the appropriate
1694       // xmm register.
1695       if (CopyVT != VA.getValVT())
1696         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1697                           // This truncation won't change the value.
1698                           DAG.getIntPtrConstant(1));
1699     } else {
1700       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1701                                  CopyVT, InFlag).getValue(1);
1702       Val = Chain.getValue(0);
1703     }
1704     InFlag = Chain.getValue(2);
1705     InVals.push_back(Val);
1706   }
1707
1708   return Chain;
1709 }
1710
1711
1712 //===----------------------------------------------------------------------===//
1713 //                C & StdCall & Fast Calling Convention implementation
1714 //===----------------------------------------------------------------------===//
1715 //  StdCall calling convention seems to be standard for many Windows' API
1716 //  routines and around. It differs from C calling convention just a little:
1717 //  callee should clean up the stack, not caller. Symbols should be also
1718 //  decorated in some fancy way :) It doesn't support any vector arguments.
1719 //  For info on fast calling convention see Fast Calling Convention (tail call)
1720 //  implementation LowerX86_32FastCCCallTo.
1721
1722 /// CallIsStructReturn - Determines whether a call uses struct return
1723 /// semantics.
1724 enum StructReturnType {
1725   NotStructReturn,
1726   RegStructReturn,
1727   StackStructReturn
1728 };
1729 static StructReturnType
1730 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1731   if (Outs.empty())
1732     return NotStructReturn;
1733
1734   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1735   if (!Flags.isSRet())
1736     return NotStructReturn;
1737   if (Flags.isInReg())
1738     return RegStructReturn;
1739   return StackStructReturn;
1740 }
1741
1742 /// ArgsAreStructReturn - Determines whether a function uses struct
1743 /// return semantics.
1744 static StructReturnType
1745 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1746   if (Ins.empty())
1747     return NotStructReturn;
1748
1749   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1750   if (!Flags.isSRet())
1751     return NotStructReturn;
1752   if (Flags.isInReg())
1753     return RegStructReturn;
1754   return StackStructReturn;
1755 }
1756
1757 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1758 /// by "Src" to address "Dst" with size and alignment information specified by
1759 /// the specific parameter attribute. The copy will be passed as a byval
1760 /// function parameter.
1761 static SDValue
1762 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1763                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1764                           DebugLoc dl) {
1765   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1766
1767   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1768                        /*isVolatile*/false, /*AlwaysInline=*/true,
1769                        MachinePointerInfo(), MachinePointerInfo());
1770 }
1771
1772 /// IsTailCallConvention - Return true if the calling convention is one that
1773 /// supports tail call optimization.
1774 static bool IsTailCallConvention(CallingConv::ID CC) {
1775   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1776 }
1777
1778 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1779   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1780     return false;
1781
1782   CallSite CS(CI);
1783   CallingConv::ID CalleeCC = CS.getCallingConv();
1784   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1785     return false;
1786
1787   return true;
1788 }
1789
1790 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1791 /// a tailcall target by changing its ABI.
1792 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1793                                    bool GuaranteedTailCallOpt) {
1794   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1795 }
1796
1797 SDValue
1798 X86TargetLowering::LowerMemArgument(SDValue Chain,
1799                                     CallingConv::ID CallConv,
1800                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1801                                     DebugLoc dl, SelectionDAG &DAG,
1802                                     const CCValAssign &VA,
1803                                     MachineFrameInfo *MFI,
1804                                     unsigned i) const {
1805   // Create the nodes corresponding to a load from this parameter slot.
1806   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1807   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1808                               getTargetMachine().Options.GuaranteedTailCallOpt);
1809   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1810   EVT ValVT;
1811
1812   // If value is passed by pointer we have address passed instead of the value
1813   // itself.
1814   if (VA.getLocInfo() == CCValAssign::Indirect)
1815     ValVT = VA.getLocVT();
1816   else
1817     ValVT = VA.getValVT();
1818
1819   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1820   // changed with more analysis.
1821   // In case of tail call optimization mark all arguments mutable. Since they
1822   // could be overwritten by lowering of arguments in case of a tail call.
1823   if (Flags.isByVal()) {
1824     unsigned Bytes = Flags.getByValSize();
1825     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1826     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1827     return DAG.getFrameIndex(FI, getPointerTy());
1828   } else {
1829     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1830                                     VA.getLocMemOffset(), isImmutable);
1831     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1832     return DAG.getLoad(ValVT, dl, Chain, FIN,
1833                        MachinePointerInfo::getFixedStack(FI),
1834                        false, false, false, 0);
1835   }
1836 }
1837
1838 SDValue
1839 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1840                                         CallingConv::ID CallConv,
1841                                         bool isVarArg,
1842                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1843                                         DebugLoc dl,
1844                                         SelectionDAG &DAG,
1845                                         SmallVectorImpl<SDValue> &InVals)
1846                                           const {
1847   MachineFunction &MF = DAG.getMachineFunction();
1848   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1849
1850   const Function* Fn = MF.getFunction();
1851   if (Fn->hasExternalLinkage() &&
1852       Subtarget->isTargetCygMing() &&
1853       Fn->getName() == "main")
1854     FuncInfo->setForceFramePointer(true);
1855
1856   MachineFrameInfo *MFI = MF.getFrameInfo();
1857   bool Is64Bit = Subtarget->is64Bit();
1858   bool IsWindows = Subtarget->isTargetWindows();
1859   bool IsWin64 = Subtarget->isTargetWin64();
1860
1861   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1862          "Var args not supported with calling convention fastcc or ghc");
1863
1864   // Assign locations to all of the incoming arguments.
1865   SmallVector<CCValAssign, 16> ArgLocs;
1866   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1867                  ArgLocs, *DAG.getContext());
1868
1869   // Allocate shadow area for Win64
1870   if (IsWin64) {
1871     CCInfo.AllocateStack(32, 8);
1872   }
1873
1874   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1875
1876   unsigned LastVal = ~0U;
1877   SDValue ArgValue;
1878   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1879     CCValAssign &VA = ArgLocs[i];
1880     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1881     // places.
1882     assert(VA.getValNo() != LastVal &&
1883            "Don't support value assigned to multiple locs yet");
1884     (void)LastVal;
1885     LastVal = VA.getValNo();
1886
1887     if (VA.isRegLoc()) {
1888       EVT RegVT = VA.getLocVT();
1889       const TargetRegisterClass *RC;
1890       if (RegVT == MVT::i32)
1891         RC = &X86::GR32RegClass;
1892       else if (Is64Bit && RegVT == MVT::i64)
1893         RC = &X86::GR64RegClass;
1894       else if (RegVT == MVT::f32)
1895         RC = &X86::FR32RegClass;
1896       else if (RegVT == MVT::f64)
1897         RC = &X86::FR64RegClass;
1898       else if (RegVT.is256BitVector())
1899         RC = &X86::VR256RegClass;
1900       else if (RegVT.is128BitVector())
1901         RC = &X86::VR128RegClass;
1902       else if (RegVT == MVT::x86mmx)
1903         RC = &X86::VR64RegClass;
1904       else
1905         llvm_unreachable("Unknown argument type!");
1906
1907       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1908       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1909
1910       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1911       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1912       // right size.
1913       if (VA.getLocInfo() == CCValAssign::SExt)
1914         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1915                                DAG.getValueType(VA.getValVT()));
1916       else if (VA.getLocInfo() == CCValAssign::ZExt)
1917         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1918                                DAG.getValueType(VA.getValVT()));
1919       else if (VA.getLocInfo() == CCValAssign::BCvt)
1920         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1921
1922       if (VA.isExtInLoc()) {
1923         // Handle MMX values passed in XMM regs.
1924         if (RegVT.isVector()) {
1925           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1926                                  ArgValue);
1927         } else
1928           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1929       }
1930     } else {
1931       assert(VA.isMemLoc());
1932       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1933     }
1934
1935     // If value is passed via pointer - do a load.
1936     if (VA.getLocInfo() == CCValAssign::Indirect)
1937       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1938                              MachinePointerInfo(), false, false, false, 0);
1939
1940     InVals.push_back(ArgValue);
1941   }
1942
1943   // The x86-64 ABI for returning structs by value requires that we copy
1944   // the sret argument into %rax for the return. Save the argument into
1945   // a virtual register so that we can access it from the return points.
1946   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1947     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1948     unsigned Reg = FuncInfo->getSRetReturnReg();
1949     if (!Reg) {
1950       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1951       FuncInfo->setSRetReturnReg(Reg);
1952     }
1953     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1954     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1955   }
1956
1957   unsigned StackSize = CCInfo.getNextStackOffset();
1958   // Align stack specially for tail calls.
1959   if (FuncIsMadeTailCallSafe(CallConv,
1960                              MF.getTarget().Options.GuaranteedTailCallOpt))
1961     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1962
1963   // If the function takes variable number of arguments, make a frame index for
1964   // the start of the first vararg value... for expansion of llvm.va_start.
1965   if (isVarArg) {
1966     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1967                     CallConv != CallingConv::X86_ThisCall)) {
1968       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1969     }
1970     if (Is64Bit) {
1971       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1972
1973       // FIXME: We should really autogenerate these arrays
1974       static const uint16_t GPR64ArgRegsWin64[] = {
1975         X86::RCX, X86::RDX, X86::R8,  X86::R9
1976       };
1977       static const uint16_t GPR64ArgRegs64Bit[] = {
1978         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1979       };
1980       static const uint16_t XMMArgRegs64Bit[] = {
1981         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1982         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1983       };
1984       const uint16_t *GPR64ArgRegs;
1985       unsigned NumXMMRegs = 0;
1986
1987       if (IsWin64) {
1988         // The XMM registers which might contain var arg parameters are shadowed
1989         // in their paired GPR.  So we only need to save the GPR to their home
1990         // slots.
1991         TotalNumIntRegs = 4;
1992         GPR64ArgRegs = GPR64ArgRegsWin64;
1993       } else {
1994         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1995         GPR64ArgRegs = GPR64ArgRegs64Bit;
1996
1997         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1998                                                 TotalNumXMMRegs);
1999       }
2000       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2001                                                        TotalNumIntRegs);
2002
2003       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
2004       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2005              "SSE register cannot be used when SSE is disabled!");
2006       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2007                NoImplicitFloatOps) &&
2008              "SSE register cannot be used when SSE is disabled!");
2009       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2010           !Subtarget->hasSSE1())
2011         // Kernel mode asks for SSE to be disabled, so don't push them
2012         // on the stack.
2013         TotalNumXMMRegs = 0;
2014
2015       if (IsWin64) {
2016         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2017         // Get to the caller-allocated home save location.  Add 8 to account
2018         // for the return address.
2019         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2020         FuncInfo->setRegSaveFrameIndex(
2021           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2022         // Fixup to set vararg frame on shadow area (4 x i64).
2023         if (NumIntRegs < 4)
2024           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2025       } else {
2026         // For X86-64, if there are vararg parameters that are passed via
2027         // registers, then we must store them to their spots on the stack so
2028         // they may be loaded by deferencing the result of va_next.
2029         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2030         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2031         FuncInfo->setRegSaveFrameIndex(
2032           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2033                                false));
2034       }
2035
2036       // Store the integer parameter registers.
2037       SmallVector<SDValue, 8> MemOps;
2038       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2039                                         getPointerTy());
2040       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2041       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2042         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2043                                   DAG.getIntPtrConstant(Offset));
2044         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2045                                      &X86::GR64RegClass);
2046         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2047         SDValue Store =
2048           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2049                        MachinePointerInfo::getFixedStack(
2050                          FuncInfo->getRegSaveFrameIndex(), Offset),
2051                        false, false, 0);
2052         MemOps.push_back(Store);
2053         Offset += 8;
2054       }
2055
2056       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2057         // Now store the XMM (fp + vector) parameter registers.
2058         SmallVector<SDValue, 11> SaveXMMOps;
2059         SaveXMMOps.push_back(Chain);
2060
2061         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2062         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2063         SaveXMMOps.push_back(ALVal);
2064
2065         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2066                                FuncInfo->getRegSaveFrameIndex()));
2067         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2068                                FuncInfo->getVarArgsFPOffset()));
2069
2070         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2071           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2072                                        &X86::VR128RegClass);
2073           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2074           SaveXMMOps.push_back(Val);
2075         }
2076         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2077                                      MVT::Other,
2078                                      &SaveXMMOps[0], SaveXMMOps.size()));
2079       }
2080
2081       if (!MemOps.empty())
2082         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2083                             &MemOps[0], MemOps.size());
2084     }
2085   }
2086
2087   // Some CCs need callee pop.
2088   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2089                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2090     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2091   } else {
2092     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2093     // If this is an sret function, the return should pop the hidden pointer.
2094     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2095         argsAreStructReturn(Ins) == StackStructReturn)
2096       FuncInfo->setBytesToPopOnReturn(4);
2097   }
2098
2099   if (!Is64Bit) {
2100     // RegSaveFrameIndex is X86-64 only.
2101     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2102     if (CallConv == CallingConv::X86_FastCall ||
2103         CallConv == CallingConv::X86_ThisCall)
2104       // fastcc functions can't have varargs.
2105       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2106   }
2107
2108   FuncInfo->setArgumentStackSize(StackSize);
2109
2110   return Chain;
2111 }
2112
2113 SDValue
2114 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2115                                     SDValue StackPtr, SDValue Arg,
2116                                     DebugLoc dl, SelectionDAG &DAG,
2117                                     const CCValAssign &VA,
2118                                     ISD::ArgFlagsTy Flags) const {
2119   unsigned LocMemOffset = VA.getLocMemOffset();
2120   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2121   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2122   if (Flags.isByVal())
2123     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2124
2125   return DAG.getStore(Chain, dl, Arg, PtrOff,
2126                       MachinePointerInfo::getStack(LocMemOffset),
2127                       false, false, 0);
2128 }
2129
2130 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2131 /// optimization is performed and it is required.
2132 SDValue
2133 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2134                                            SDValue &OutRetAddr, SDValue Chain,
2135                                            bool IsTailCall, bool Is64Bit,
2136                                            int FPDiff, DebugLoc dl) const {
2137   // Adjust the Return address stack slot.
2138   EVT VT = getPointerTy();
2139   OutRetAddr = getReturnAddressFrameIndex(DAG);
2140
2141   // Load the "old" Return address.
2142   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2143                            false, false, false, 0);
2144   return SDValue(OutRetAddr.getNode(), 1);
2145 }
2146
2147 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2148 /// optimization is performed and it is required (FPDiff!=0).
2149 static SDValue
2150 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2151                          SDValue Chain, SDValue RetAddrFrIdx,
2152                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2153   // Store the return address to the appropriate stack slot.
2154   if (!FPDiff) return Chain;
2155   // Calculate the new stack slot for the return address.
2156   int SlotSize = Is64Bit ? 8 : 4;
2157   int NewReturnAddrFI =
2158     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2159   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2160   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2161   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2162                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2163                        false, false, 0);
2164   return Chain;
2165 }
2166
2167 SDValue
2168 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2169                              SmallVectorImpl<SDValue> &InVals) const {
2170   SelectionDAG &DAG                     = CLI.DAG;
2171   DebugLoc &dl                          = CLI.DL;
2172   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2173   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2174   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2175   SDValue Chain                         = CLI.Chain;
2176   SDValue Callee                        = CLI.Callee;
2177   CallingConv::ID CallConv              = CLI.CallConv;
2178   bool &isTailCall                      = CLI.IsTailCall;
2179   bool isVarArg                         = CLI.IsVarArg;
2180
2181   MachineFunction &MF = DAG.getMachineFunction();
2182   bool Is64Bit        = Subtarget->is64Bit();
2183   bool IsWin64        = Subtarget->isTargetWin64();
2184   bool IsWindows      = Subtarget->isTargetWindows();
2185   StructReturnType SR = callIsStructReturn(Outs);
2186   bool IsSibcall      = false;
2187
2188   if (MF.getTarget().Options.DisableTailCalls)
2189     isTailCall = false;
2190
2191   if (isTailCall) {
2192     // Check if it's really possible to do a tail call.
2193     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2194                     isVarArg, SR != NotStructReturn,
2195                     MF.getFunction()->hasStructRetAttr(),
2196                     Outs, OutVals, Ins, DAG);
2197
2198     // Sibcalls are automatically detected tailcalls which do not require
2199     // ABI changes.
2200     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2201       IsSibcall = true;
2202
2203     if (isTailCall)
2204       ++NumTailCalls;
2205   }
2206
2207   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2208          "Var args not supported with calling convention fastcc or ghc");
2209
2210   // Analyze operands of the call, assigning locations to each operand.
2211   SmallVector<CCValAssign, 16> ArgLocs;
2212   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2213                  ArgLocs, *DAG.getContext());
2214
2215   // Allocate shadow area for Win64
2216   if (IsWin64) {
2217     CCInfo.AllocateStack(32, 8);
2218   }
2219
2220   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2221
2222   // Get a count of how many bytes are to be pushed on the stack.
2223   unsigned NumBytes = CCInfo.getNextStackOffset();
2224   if (IsSibcall)
2225     // This is a sibcall. The memory operands are available in caller's
2226     // own caller's stack.
2227     NumBytes = 0;
2228   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2229            IsTailCallConvention(CallConv))
2230     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2231
2232   int FPDiff = 0;
2233   if (isTailCall && !IsSibcall) {
2234     // Lower arguments at fp - stackoffset + fpdiff.
2235     unsigned NumBytesCallerPushed =
2236       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2237     FPDiff = NumBytesCallerPushed - NumBytes;
2238
2239     // Set the delta of movement of the returnaddr stackslot.
2240     // But only set if delta is greater than previous delta.
2241     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2242       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2243   }
2244
2245   if (!IsSibcall)
2246     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2247
2248   SDValue RetAddrFrIdx;
2249   // Load return address for tail calls.
2250   if (isTailCall && FPDiff)
2251     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2252                                     Is64Bit, FPDiff, dl);
2253
2254   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2255   SmallVector<SDValue, 8> MemOpChains;
2256   SDValue StackPtr;
2257
2258   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2259   // of tail call optimization arguments are handle later.
2260   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2261     CCValAssign &VA = ArgLocs[i];
2262     EVT RegVT = VA.getLocVT();
2263     SDValue Arg = OutVals[i];
2264     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2265     bool isByVal = Flags.isByVal();
2266
2267     // Promote the value if needed.
2268     switch (VA.getLocInfo()) {
2269     default: llvm_unreachable("Unknown loc info!");
2270     case CCValAssign::Full: break;
2271     case CCValAssign::SExt:
2272       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2273       break;
2274     case CCValAssign::ZExt:
2275       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2276       break;
2277     case CCValAssign::AExt:
2278       if (RegVT.is128BitVector()) {
2279         // Special case: passing MMX values in XMM registers.
2280         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2281         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2282         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2283       } else
2284         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2285       break;
2286     case CCValAssign::BCvt:
2287       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2288       break;
2289     case CCValAssign::Indirect: {
2290       // Store the argument.
2291       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2292       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2293       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2294                            MachinePointerInfo::getFixedStack(FI),
2295                            false, false, 0);
2296       Arg = SpillSlot;
2297       break;
2298     }
2299     }
2300
2301     if (VA.isRegLoc()) {
2302       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2303       if (isVarArg && IsWin64) {
2304         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2305         // shadow reg if callee is a varargs function.
2306         unsigned ShadowReg = 0;
2307         switch (VA.getLocReg()) {
2308         case X86::XMM0: ShadowReg = X86::RCX; break;
2309         case X86::XMM1: ShadowReg = X86::RDX; break;
2310         case X86::XMM2: ShadowReg = X86::R8; break;
2311         case X86::XMM3: ShadowReg = X86::R9; break;
2312         }
2313         if (ShadowReg)
2314           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2315       }
2316     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2317       assert(VA.isMemLoc());
2318       if (StackPtr.getNode() == 0)
2319         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2320       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2321                                              dl, DAG, VA, Flags));
2322     }
2323   }
2324
2325   if (!MemOpChains.empty())
2326     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2327                         &MemOpChains[0], MemOpChains.size());
2328
2329   if (Subtarget->isPICStyleGOT()) {
2330     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2331     // GOT pointer.
2332     if (!isTailCall) {
2333       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2334                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2335     } else {
2336       // If we are tail calling and generating PIC/GOT style code load the
2337       // address of the callee into ECX. The value in ecx is used as target of
2338       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2339       // for tail calls on PIC/GOT architectures. Normally we would just put the
2340       // address of GOT into ebx and then call target@PLT. But for tail calls
2341       // ebx would be restored (since ebx is callee saved) before jumping to the
2342       // target@PLT.
2343
2344       // Note: The actual moving to ECX is done further down.
2345       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2346       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2347           !G->getGlobal()->hasProtectedVisibility())
2348         Callee = LowerGlobalAddress(Callee, DAG);
2349       else if (isa<ExternalSymbolSDNode>(Callee))
2350         Callee = LowerExternalSymbol(Callee, DAG);
2351     }
2352   }
2353
2354   if (Is64Bit && isVarArg && !IsWin64) {
2355     // From AMD64 ABI document:
2356     // For calls that may call functions that use varargs or stdargs
2357     // (prototype-less calls or calls to functions containing ellipsis (...) in
2358     // the declaration) %al is used as hidden argument to specify the number
2359     // of SSE registers used. The contents of %al do not need to match exactly
2360     // the number of registers, but must be an ubound on the number of SSE
2361     // registers used and is in the range 0 - 8 inclusive.
2362
2363     // Count the number of XMM registers allocated.
2364     static const uint16_t XMMArgRegs[] = {
2365       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2366       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2367     };
2368     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2369     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2370            && "SSE registers cannot be used when SSE is disabled");
2371
2372     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2373                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2374   }
2375
2376   // For tail calls lower the arguments to the 'real' stack slot.
2377   if (isTailCall) {
2378     // Force all the incoming stack arguments to be loaded from the stack
2379     // before any new outgoing arguments are stored to the stack, because the
2380     // outgoing stack slots may alias the incoming argument stack slots, and
2381     // the alias isn't otherwise explicit. This is slightly more conservative
2382     // than necessary, because it means that each store effectively depends
2383     // on every argument instead of just those arguments it would clobber.
2384     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2385
2386     SmallVector<SDValue, 8> MemOpChains2;
2387     SDValue FIN;
2388     int FI = 0;
2389     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2390       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2391         CCValAssign &VA = ArgLocs[i];
2392         if (VA.isRegLoc())
2393           continue;
2394         assert(VA.isMemLoc());
2395         SDValue Arg = OutVals[i];
2396         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2397         // Create frame index.
2398         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2399         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2400         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2401         FIN = DAG.getFrameIndex(FI, getPointerTy());
2402
2403         if (Flags.isByVal()) {
2404           // Copy relative to framepointer.
2405           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2406           if (StackPtr.getNode() == 0)
2407             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2408                                           getPointerTy());
2409           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2410
2411           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2412                                                            ArgChain,
2413                                                            Flags, DAG, dl));
2414         } else {
2415           // Store relative to framepointer.
2416           MemOpChains2.push_back(
2417             DAG.getStore(ArgChain, dl, Arg, FIN,
2418                          MachinePointerInfo::getFixedStack(FI),
2419                          false, false, 0));
2420         }
2421       }
2422     }
2423
2424     if (!MemOpChains2.empty())
2425       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2426                           &MemOpChains2[0], MemOpChains2.size());
2427
2428     // Store the return address to the appropriate stack slot.
2429     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2430                                      FPDiff, dl);
2431   }
2432
2433   // Build a sequence of copy-to-reg nodes chained together with token chain
2434   // and flag operands which copy the outgoing args into registers.
2435   SDValue InFlag;
2436   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2437     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2438                              RegsToPass[i].second, InFlag);
2439     InFlag = Chain.getValue(1);
2440   }
2441
2442   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2443     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2444     // In the 64-bit large code model, we have to make all calls
2445     // through a register, since the call instruction's 32-bit
2446     // pc-relative offset may not be large enough to hold the whole
2447     // address.
2448   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2449     // If the callee is a GlobalAddress node (quite common, every direct call
2450     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2451     // it.
2452
2453     // We should use extra load for direct calls to dllimported functions in
2454     // non-JIT mode.
2455     const GlobalValue *GV = G->getGlobal();
2456     if (!GV->hasDLLImportLinkage()) {
2457       unsigned char OpFlags = 0;
2458       bool ExtraLoad = false;
2459       unsigned WrapperKind = ISD::DELETED_NODE;
2460
2461       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2462       // external symbols most go through the PLT in PIC mode.  If the symbol
2463       // has hidden or protected visibility, or if it is static or local, then
2464       // we don't need to use the PLT - we can directly call it.
2465       if (Subtarget->isTargetELF() &&
2466           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2467           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2468         OpFlags = X86II::MO_PLT;
2469       } else if (Subtarget->isPICStyleStubAny() &&
2470                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2471                  (!Subtarget->getTargetTriple().isMacOSX() ||
2472                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2473         // PC-relative references to external symbols should go through $stub,
2474         // unless we're building with the leopard linker or later, which
2475         // automatically synthesizes these stubs.
2476         OpFlags = X86II::MO_DARWIN_STUB;
2477       } else if (Subtarget->isPICStyleRIPRel() &&
2478                  isa<Function>(GV) &&
2479                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2480         // If the function is marked as non-lazy, generate an indirect call
2481         // which loads from the GOT directly. This avoids runtime overhead
2482         // at the cost of eager binding (and one extra byte of encoding).
2483         OpFlags = X86II::MO_GOTPCREL;
2484         WrapperKind = X86ISD::WrapperRIP;
2485         ExtraLoad = true;
2486       }
2487
2488       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2489                                           G->getOffset(), OpFlags);
2490
2491       // Add a wrapper if needed.
2492       if (WrapperKind != ISD::DELETED_NODE)
2493         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2494       // Add extra indirection if needed.
2495       if (ExtraLoad)
2496         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2497                              MachinePointerInfo::getGOT(),
2498                              false, false, false, 0);
2499     }
2500   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2501     unsigned char OpFlags = 0;
2502
2503     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2504     // external symbols should go through the PLT.
2505     if (Subtarget->isTargetELF() &&
2506         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2507       OpFlags = X86II::MO_PLT;
2508     } else if (Subtarget->isPICStyleStubAny() &&
2509                (!Subtarget->getTargetTriple().isMacOSX() ||
2510                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2511       // PC-relative references to external symbols should go through $stub,
2512       // unless we're building with the leopard linker or later, which
2513       // automatically synthesizes these stubs.
2514       OpFlags = X86II::MO_DARWIN_STUB;
2515     }
2516
2517     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2518                                          OpFlags);
2519   }
2520
2521   // Returns a chain & a flag for retval copy to use.
2522   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2523   SmallVector<SDValue, 8> Ops;
2524
2525   if (!IsSibcall && isTailCall) {
2526     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2527                            DAG.getIntPtrConstant(0, true), InFlag);
2528     InFlag = Chain.getValue(1);
2529   }
2530
2531   Ops.push_back(Chain);
2532   Ops.push_back(Callee);
2533
2534   if (isTailCall)
2535     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2536
2537   // Add argument registers to the end of the list so that they are known live
2538   // into the call.
2539   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2540     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2541                                   RegsToPass[i].second.getValueType()));
2542
2543   // Add a register mask operand representing the call-preserved registers.
2544   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2545   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2546   assert(Mask && "Missing call preserved mask for calling convention");
2547   Ops.push_back(DAG.getRegisterMask(Mask));
2548
2549   if (InFlag.getNode())
2550     Ops.push_back(InFlag);
2551
2552   if (isTailCall) {
2553     // We used to do:
2554     //// If this is the first return lowered for this function, add the regs
2555     //// to the liveout set for the function.
2556     // This isn't right, although it's probably harmless on x86; liveouts
2557     // should be computed from returns not tail calls.  Consider a void
2558     // function making a tail call to a function returning int.
2559     return DAG.getNode(X86ISD::TC_RETURN, dl,
2560                        NodeTys, &Ops[0], Ops.size());
2561   }
2562
2563   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2564   InFlag = Chain.getValue(1);
2565
2566   // Create the CALLSEQ_END node.
2567   unsigned NumBytesForCalleeToPush;
2568   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2569                        getTargetMachine().Options.GuaranteedTailCallOpt))
2570     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2571   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2572            SR == StackStructReturn)
2573     // If this is a call to a struct-return function, the callee
2574     // pops the hidden struct pointer, so we have to push it back.
2575     // This is common for Darwin/X86, Linux & Mingw32 targets.
2576     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2577     NumBytesForCalleeToPush = 4;
2578   else
2579     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2580
2581   // Returns a flag for retval copy to use.
2582   if (!IsSibcall) {
2583     Chain = DAG.getCALLSEQ_END(Chain,
2584                                DAG.getIntPtrConstant(NumBytes, true),
2585                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2586                                                      true),
2587                                InFlag);
2588     InFlag = Chain.getValue(1);
2589   }
2590
2591   // Handle result values, copying them out of physregs into vregs that we
2592   // return.
2593   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2594                          Ins, dl, DAG, InVals);
2595 }
2596
2597
2598 //===----------------------------------------------------------------------===//
2599 //                Fast Calling Convention (tail call) implementation
2600 //===----------------------------------------------------------------------===//
2601
2602 //  Like std call, callee cleans arguments, convention except that ECX is
2603 //  reserved for storing the tail called function address. Only 2 registers are
2604 //  free for argument passing (inreg). Tail call optimization is performed
2605 //  provided:
2606 //                * tailcallopt is enabled
2607 //                * caller/callee are fastcc
2608 //  On X86_64 architecture with GOT-style position independent code only local
2609 //  (within module) calls are supported at the moment.
2610 //  To keep the stack aligned according to platform abi the function
2611 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2612 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2613 //  If a tail called function callee has more arguments than the caller the
2614 //  caller needs to make sure that there is room to move the RETADDR to. This is
2615 //  achieved by reserving an area the size of the argument delta right after the
2616 //  original REtADDR, but before the saved framepointer or the spilled registers
2617 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2618 //  stack layout:
2619 //    arg1
2620 //    arg2
2621 //    RETADDR
2622 //    [ new RETADDR
2623 //      move area ]
2624 //    (possible EBP)
2625 //    ESI
2626 //    EDI
2627 //    local1 ..
2628
2629 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2630 /// for a 16 byte align requirement.
2631 unsigned
2632 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2633                                                SelectionDAG& DAG) const {
2634   MachineFunction &MF = DAG.getMachineFunction();
2635   const TargetMachine &TM = MF.getTarget();
2636   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2637   unsigned StackAlignment = TFI.getStackAlignment();
2638   uint64_t AlignMask = StackAlignment - 1;
2639   int64_t Offset = StackSize;
2640   uint64_t SlotSize = TD->getPointerSize();
2641   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2642     // Number smaller than 12 so just add the difference.
2643     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2644   } else {
2645     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2646     Offset = ((~AlignMask) & Offset) + StackAlignment +
2647       (StackAlignment-SlotSize);
2648   }
2649   return Offset;
2650 }
2651
2652 /// MatchingStackOffset - Return true if the given stack call argument is
2653 /// already available in the same position (relatively) of the caller's
2654 /// incoming argument stack.
2655 static
2656 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2657                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2658                          const X86InstrInfo *TII) {
2659   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2660   int FI = INT_MAX;
2661   if (Arg.getOpcode() == ISD::CopyFromReg) {
2662     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2663     if (!TargetRegisterInfo::isVirtualRegister(VR))
2664       return false;
2665     MachineInstr *Def = MRI->getVRegDef(VR);
2666     if (!Def)
2667       return false;
2668     if (!Flags.isByVal()) {
2669       if (!TII->isLoadFromStackSlot(Def, FI))
2670         return false;
2671     } else {
2672       unsigned Opcode = Def->getOpcode();
2673       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2674           Def->getOperand(1).isFI()) {
2675         FI = Def->getOperand(1).getIndex();
2676         Bytes = Flags.getByValSize();
2677       } else
2678         return false;
2679     }
2680   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2681     if (Flags.isByVal())
2682       // ByVal argument is passed in as a pointer but it's now being
2683       // dereferenced. e.g.
2684       // define @foo(%struct.X* %A) {
2685       //   tail call @bar(%struct.X* byval %A)
2686       // }
2687       return false;
2688     SDValue Ptr = Ld->getBasePtr();
2689     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2690     if (!FINode)
2691       return false;
2692     FI = FINode->getIndex();
2693   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2694     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2695     FI = FINode->getIndex();
2696     Bytes = Flags.getByValSize();
2697   } else
2698     return false;
2699
2700   assert(FI != INT_MAX);
2701   if (!MFI->isFixedObjectIndex(FI))
2702     return false;
2703   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2704 }
2705
2706 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2707 /// for tail call optimization. Targets which want to do tail call
2708 /// optimization should implement this function.
2709 bool
2710 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2711                                                      CallingConv::ID CalleeCC,
2712                                                      bool isVarArg,
2713                                                      bool isCalleeStructRet,
2714                                                      bool isCallerStructRet,
2715                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2716                                     const SmallVectorImpl<SDValue> &OutVals,
2717                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2718                                                      SelectionDAG& DAG) const {
2719   if (!IsTailCallConvention(CalleeCC) &&
2720       CalleeCC != CallingConv::C)
2721     return false;
2722
2723   // If -tailcallopt is specified, make fastcc functions tail-callable.
2724   const MachineFunction &MF = DAG.getMachineFunction();
2725   const Function *CallerF = DAG.getMachineFunction().getFunction();
2726   CallingConv::ID CallerCC = CallerF->getCallingConv();
2727   bool CCMatch = CallerCC == CalleeCC;
2728
2729   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2730     if (IsTailCallConvention(CalleeCC) && CCMatch)
2731       return true;
2732     return false;
2733   }
2734
2735   // Look for obvious safe cases to perform tail call optimization that do not
2736   // require ABI changes. This is what gcc calls sibcall.
2737
2738   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2739   // emit a special epilogue.
2740   if (RegInfo->needsStackRealignment(MF))
2741     return false;
2742
2743   // Also avoid sibcall optimization if either caller or callee uses struct
2744   // return semantics.
2745   if (isCalleeStructRet || isCallerStructRet)
2746     return false;
2747
2748   // An stdcall caller is expected to clean up its arguments; the callee
2749   // isn't going to do that.
2750   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2751     return false;
2752
2753   // Do not sibcall optimize vararg calls unless all arguments are passed via
2754   // registers.
2755   if (isVarArg && !Outs.empty()) {
2756
2757     // Optimizing for varargs on Win64 is unlikely to be safe without
2758     // additional testing.
2759     if (Subtarget->isTargetWin64())
2760       return false;
2761
2762     SmallVector<CCValAssign, 16> ArgLocs;
2763     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2764                    getTargetMachine(), ArgLocs, *DAG.getContext());
2765
2766     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2767     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2768       if (!ArgLocs[i].isRegLoc())
2769         return false;
2770   }
2771
2772   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2773   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2774   // this into a sibcall.
2775   bool Unused = false;
2776   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2777     if (!Ins[i].Used) {
2778       Unused = true;
2779       break;
2780     }
2781   }
2782   if (Unused) {
2783     SmallVector<CCValAssign, 16> RVLocs;
2784     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2785                    getTargetMachine(), RVLocs, *DAG.getContext());
2786     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2787     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2788       CCValAssign &VA = RVLocs[i];
2789       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2790         return false;
2791     }
2792   }
2793
2794   // If the calling conventions do not match, then we'd better make sure the
2795   // results are returned in the same way as what the caller expects.
2796   if (!CCMatch) {
2797     SmallVector<CCValAssign, 16> RVLocs1;
2798     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2799                     getTargetMachine(), RVLocs1, *DAG.getContext());
2800     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2801
2802     SmallVector<CCValAssign, 16> RVLocs2;
2803     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2804                     getTargetMachine(), RVLocs2, *DAG.getContext());
2805     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2806
2807     if (RVLocs1.size() != RVLocs2.size())
2808       return false;
2809     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2810       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2811         return false;
2812       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2813         return false;
2814       if (RVLocs1[i].isRegLoc()) {
2815         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2816           return false;
2817       } else {
2818         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2819           return false;
2820       }
2821     }
2822   }
2823
2824   // If the callee takes no arguments then go on to check the results of the
2825   // call.
2826   if (!Outs.empty()) {
2827     // Check if stack adjustment is needed. For now, do not do this if any
2828     // argument is passed on the stack.
2829     SmallVector<CCValAssign, 16> ArgLocs;
2830     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2831                    getTargetMachine(), ArgLocs, *DAG.getContext());
2832
2833     // Allocate shadow area for Win64
2834     if (Subtarget->isTargetWin64()) {
2835       CCInfo.AllocateStack(32, 8);
2836     }
2837
2838     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2839     if (CCInfo.getNextStackOffset()) {
2840       MachineFunction &MF = DAG.getMachineFunction();
2841       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2842         return false;
2843
2844       // Check if the arguments are already laid out in the right way as
2845       // the caller's fixed stack objects.
2846       MachineFrameInfo *MFI = MF.getFrameInfo();
2847       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2848       const X86InstrInfo *TII =
2849         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2850       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2851         CCValAssign &VA = ArgLocs[i];
2852         SDValue Arg = OutVals[i];
2853         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2854         if (VA.getLocInfo() == CCValAssign::Indirect)
2855           return false;
2856         if (!VA.isRegLoc()) {
2857           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2858                                    MFI, MRI, TII))
2859             return false;
2860         }
2861       }
2862     }
2863
2864     // If the tailcall address may be in a register, then make sure it's
2865     // possible to register allocate for it. In 32-bit, the call address can
2866     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2867     // callee-saved registers are restored. These happen to be the same
2868     // registers used to pass 'inreg' arguments so watch out for those.
2869     if (!Subtarget->is64Bit() &&
2870         !isa<GlobalAddressSDNode>(Callee) &&
2871         !isa<ExternalSymbolSDNode>(Callee)) {
2872       unsigned NumInRegs = 0;
2873       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2874         CCValAssign &VA = ArgLocs[i];
2875         if (!VA.isRegLoc())
2876           continue;
2877         unsigned Reg = VA.getLocReg();
2878         switch (Reg) {
2879         default: break;
2880         case X86::EAX: case X86::EDX: case X86::ECX:
2881           if (++NumInRegs == 3)
2882             return false;
2883           break;
2884         }
2885       }
2886     }
2887   }
2888
2889   return true;
2890 }
2891
2892 FastISel *
2893 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2894                                   const TargetLibraryInfo *libInfo) const {
2895   return X86::createFastISel(funcInfo, libInfo);
2896 }
2897
2898
2899 //===----------------------------------------------------------------------===//
2900 //                           Other Lowering Hooks
2901 //===----------------------------------------------------------------------===//
2902
2903 static bool MayFoldLoad(SDValue Op) {
2904   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2905 }
2906
2907 static bool MayFoldIntoStore(SDValue Op) {
2908   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2909 }
2910
2911 static bool isTargetShuffle(unsigned Opcode) {
2912   switch(Opcode) {
2913   default: return false;
2914   case X86ISD::PSHUFD:
2915   case X86ISD::PSHUFHW:
2916   case X86ISD::PSHUFLW:
2917   case X86ISD::SHUFP:
2918   case X86ISD::PALIGN:
2919   case X86ISD::MOVLHPS:
2920   case X86ISD::MOVLHPD:
2921   case X86ISD::MOVHLPS:
2922   case X86ISD::MOVLPS:
2923   case X86ISD::MOVLPD:
2924   case X86ISD::MOVSHDUP:
2925   case X86ISD::MOVSLDUP:
2926   case X86ISD::MOVDDUP:
2927   case X86ISD::MOVSS:
2928   case X86ISD::MOVSD:
2929   case X86ISD::UNPCKL:
2930   case X86ISD::UNPCKH:
2931   case X86ISD::VPERMILP:
2932   case X86ISD::VPERM2X128:
2933   case X86ISD::VPERMI:
2934     return true;
2935   }
2936 }
2937
2938 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2939                                     SDValue V1, SelectionDAG &DAG) {
2940   switch(Opc) {
2941   default: llvm_unreachable("Unknown x86 shuffle node");
2942   case X86ISD::MOVSHDUP:
2943   case X86ISD::MOVSLDUP:
2944   case X86ISD::MOVDDUP:
2945     return DAG.getNode(Opc, dl, VT, V1);
2946   }
2947 }
2948
2949 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2950                                     SDValue V1, unsigned TargetMask,
2951                                     SelectionDAG &DAG) {
2952   switch(Opc) {
2953   default: llvm_unreachable("Unknown x86 shuffle node");
2954   case X86ISD::PSHUFD:
2955   case X86ISD::PSHUFHW:
2956   case X86ISD::PSHUFLW:
2957   case X86ISD::VPERMILP:
2958   case X86ISD::VPERMI:
2959     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2960   }
2961 }
2962
2963 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2964                                     SDValue V1, SDValue V2, unsigned TargetMask,
2965                                     SelectionDAG &DAG) {
2966   switch(Opc) {
2967   default: llvm_unreachable("Unknown x86 shuffle node");
2968   case X86ISD::PALIGN:
2969   case X86ISD::SHUFP:
2970   case X86ISD::VPERM2X128:
2971     return DAG.getNode(Opc, dl, VT, V1, V2,
2972                        DAG.getConstant(TargetMask, MVT::i8));
2973   }
2974 }
2975
2976 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2977                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2978   switch(Opc) {
2979   default: llvm_unreachable("Unknown x86 shuffle node");
2980   case X86ISD::MOVLHPS:
2981   case X86ISD::MOVLHPD:
2982   case X86ISD::MOVHLPS:
2983   case X86ISD::MOVLPS:
2984   case X86ISD::MOVLPD:
2985   case X86ISD::MOVSS:
2986   case X86ISD::MOVSD:
2987   case X86ISD::UNPCKL:
2988   case X86ISD::UNPCKH:
2989     return DAG.getNode(Opc, dl, VT, V1, V2);
2990   }
2991 }
2992
2993 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2994   MachineFunction &MF = DAG.getMachineFunction();
2995   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2996   int ReturnAddrIndex = FuncInfo->getRAIndex();
2997
2998   if (ReturnAddrIndex == 0) {
2999     // Set up a frame object for the return address.
3000     uint64_t SlotSize = TD->getPointerSize();
3001     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3002                                                            false);
3003     FuncInfo->setRAIndex(ReturnAddrIndex);
3004   }
3005
3006   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3007 }
3008
3009
3010 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3011                                        bool hasSymbolicDisplacement) {
3012   // Offset should fit into 32 bit immediate field.
3013   if (!isInt<32>(Offset))
3014     return false;
3015
3016   // If we don't have a symbolic displacement - we don't have any extra
3017   // restrictions.
3018   if (!hasSymbolicDisplacement)
3019     return true;
3020
3021   // FIXME: Some tweaks might be needed for medium code model.
3022   if (M != CodeModel::Small && M != CodeModel::Kernel)
3023     return false;
3024
3025   // For small code model we assume that latest object is 16MB before end of 31
3026   // bits boundary. We may also accept pretty large negative constants knowing
3027   // that all objects are in the positive half of address space.
3028   if (M == CodeModel::Small && Offset < 16*1024*1024)
3029     return true;
3030
3031   // For kernel code model we know that all object resist in the negative half
3032   // of 32bits address space. We may not accept negative offsets, since they may
3033   // be just off and we may accept pretty large positive ones.
3034   if (M == CodeModel::Kernel && Offset > 0)
3035     return true;
3036
3037   return false;
3038 }
3039
3040 /// isCalleePop - Determines whether the callee is required to pop its
3041 /// own arguments. Callee pop is necessary to support tail calls.
3042 bool X86::isCalleePop(CallingConv::ID CallingConv,
3043                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3044   if (IsVarArg)
3045     return false;
3046
3047   switch (CallingConv) {
3048   default:
3049     return false;
3050   case CallingConv::X86_StdCall:
3051     return !is64Bit;
3052   case CallingConv::X86_FastCall:
3053     return !is64Bit;
3054   case CallingConv::X86_ThisCall:
3055     return !is64Bit;
3056   case CallingConv::Fast:
3057     return TailCallOpt;
3058   case CallingConv::GHC:
3059     return TailCallOpt;
3060   }
3061 }
3062
3063 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3064 /// specific condition code, returning the condition code and the LHS/RHS of the
3065 /// comparison to make.
3066 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3067                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3068   if (!isFP) {
3069     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3070       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3071         // X > -1   -> X == 0, jump !sign.
3072         RHS = DAG.getConstant(0, RHS.getValueType());
3073         return X86::COND_NS;
3074       }
3075       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3076         // X < 0   -> X == 0, jump on sign.
3077         return X86::COND_S;
3078       }
3079       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3080         // X < 1   -> X <= 0
3081         RHS = DAG.getConstant(0, RHS.getValueType());
3082         return X86::COND_LE;
3083       }
3084     }
3085
3086     switch (SetCCOpcode) {
3087     default: llvm_unreachable("Invalid integer condition!");
3088     case ISD::SETEQ:  return X86::COND_E;
3089     case ISD::SETGT:  return X86::COND_G;
3090     case ISD::SETGE:  return X86::COND_GE;
3091     case ISD::SETLT:  return X86::COND_L;
3092     case ISD::SETLE:  return X86::COND_LE;
3093     case ISD::SETNE:  return X86::COND_NE;
3094     case ISD::SETULT: return X86::COND_B;
3095     case ISD::SETUGT: return X86::COND_A;
3096     case ISD::SETULE: return X86::COND_BE;
3097     case ISD::SETUGE: return X86::COND_AE;
3098     }
3099   }
3100
3101   // First determine if it is required or is profitable to flip the operands.
3102
3103   // If LHS is a foldable load, but RHS is not, flip the condition.
3104   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3105       !ISD::isNON_EXTLoad(RHS.getNode())) {
3106     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3107     std::swap(LHS, RHS);
3108   }
3109
3110   switch (SetCCOpcode) {
3111   default: break;
3112   case ISD::SETOLT:
3113   case ISD::SETOLE:
3114   case ISD::SETUGT:
3115   case ISD::SETUGE:
3116     std::swap(LHS, RHS);
3117     break;
3118   }
3119
3120   // On a floating point condition, the flags are set as follows:
3121   // ZF  PF  CF   op
3122   //  0 | 0 | 0 | X > Y
3123   //  0 | 0 | 1 | X < Y
3124   //  1 | 0 | 0 | X == Y
3125   //  1 | 1 | 1 | unordered
3126   switch (SetCCOpcode) {
3127   default: llvm_unreachable("Condcode should be pre-legalized away");
3128   case ISD::SETUEQ:
3129   case ISD::SETEQ:   return X86::COND_E;
3130   case ISD::SETOLT:              // flipped
3131   case ISD::SETOGT:
3132   case ISD::SETGT:   return X86::COND_A;
3133   case ISD::SETOLE:              // flipped
3134   case ISD::SETOGE:
3135   case ISD::SETGE:   return X86::COND_AE;
3136   case ISD::SETUGT:              // flipped
3137   case ISD::SETULT:
3138   case ISD::SETLT:   return X86::COND_B;
3139   case ISD::SETUGE:              // flipped
3140   case ISD::SETULE:
3141   case ISD::SETLE:   return X86::COND_BE;
3142   case ISD::SETONE:
3143   case ISD::SETNE:   return X86::COND_NE;
3144   case ISD::SETUO:   return X86::COND_P;
3145   case ISD::SETO:    return X86::COND_NP;
3146   case ISD::SETOEQ:
3147   case ISD::SETUNE:  return X86::COND_INVALID;
3148   }
3149 }
3150
3151 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3152 /// code. Current x86 isa includes the following FP cmov instructions:
3153 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3154 static bool hasFPCMov(unsigned X86CC) {
3155   switch (X86CC) {
3156   default:
3157     return false;
3158   case X86::COND_B:
3159   case X86::COND_BE:
3160   case X86::COND_E:
3161   case X86::COND_P:
3162   case X86::COND_A:
3163   case X86::COND_AE:
3164   case X86::COND_NE:
3165   case X86::COND_NP:
3166     return true;
3167   }
3168 }
3169
3170 /// isFPImmLegal - Returns true if the target can instruction select the
3171 /// specified FP immediate natively. If false, the legalizer will
3172 /// materialize the FP immediate as a load from a constant pool.
3173 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3174   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3175     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3176       return true;
3177   }
3178   return false;
3179 }
3180
3181 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3182 /// the specified range (L, H].
3183 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3184   return (Val < 0) || (Val >= Low && Val < Hi);
3185 }
3186
3187 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3188 /// specified value.
3189 static bool isUndefOrEqual(int Val, int CmpVal) {
3190   if (Val < 0 || Val == CmpVal)
3191     return true;
3192   return false;
3193 }
3194
3195 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3196 /// from position Pos and ending in Pos+Size, falls within the specified
3197 /// sequential range (L, L+Pos]. or is undef.
3198 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3199                                        unsigned Pos, unsigned Size, int Low) {
3200   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3201     if (!isUndefOrEqual(Mask[i], Low))
3202       return false;
3203   return true;
3204 }
3205
3206 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3207 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3208 /// the second operand.
3209 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3210   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3211     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3212   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3213     return (Mask[0] < 2 && Mask[1] < 2);
3214   return false;
3215 }
3216
3217 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3218 /// is suitable for input to PSHUFHW.
3219 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3220   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3221     return false;
3222
3223   // Lower quadword copied in order or undef.
3224   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3225     return false;
3226
3227   // Upper quadword shuffled.
3228   for (unsigned i = 4; i != 8; ++i)
3229     if (!isUndefOrInRange(Mask[i], 4, 8))
3230       return false;
3231
3232   if (VT == MVT::v16i16) {
3233     // Lower quadword copied in order or undef.
3234     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3235       return false;
3236
3237     // Upper quadword shuffled.
3238     for (unsigned i = 12; i != 16; ++i)
3239       if (!isUndefOrInRange(Mask[i], 12, 16))
3240         return false;
3241   }
3242
3243   return true;
3244 }
3245
3246 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3247 /// is suitable for input to PSHUFLW.
3248 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3249   if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3250     return false;
3251
3252   // Upper quadword copied in order.
3253   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3254     return false;
3255
3256   // Lower quadword shuffled.
3257   for (unsigned i = 0; i != 4; ++i)
3258     if (!isUndefOrInRange(Mask[i], 0, 4))
3259       return false;
3260
3261   if (VT == MVT::v16i16) {
3262     // Upper quadword copied in order.
3263     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3264       return false;
3265
3266     // Lower quadword shuffled.
3267     for (unsigned i = 8; i != 12; ++i)
3268       if (!isUndefOrInRange(Mask[i], 8, 12))
3269         return false;
3270   }
3271
3272   return true;
3273 }
3274
3275 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3276 /// is suitable for input to PALIGNR.
3277 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3278                           const X86Subtarget *Subtarget) {
3279   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3280       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3281     return false;
3282
3283   unsigned NumElts = VT.getVectorNumElements();
3284   unsigned NumLanes = VT.getSizeInBits()/128;
3285   unsigned NumLaneElts = NumElts/NumLanes;
3286
3287   // Do not handle 64-bit element shuffles with palignr.
3288   if (NumLaneElts == 2)
3289     return false;
3290
3291   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3292     unsigned i;
3293     for (i = 0; i != NumLaneElts; ++i) {
3294       if (Mask[i+l] >= 0)
3295         break;
3296     }
3297
3298     // Lane is all undef, go to next lane
3299     if (i == NumLaneElts)
3300       continue;
3301
3302     int Start = Mask[i+l];
3303
3304     // Make sure its in this lane in one of the sources
3305     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3306         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3307       return false;
3308
3309     // If not lane 0, then we must match lane 0
3310     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3311       return false;
3312
3313     // Correct second source to be contiguous with first source
3314     if (Start >= (int)NumElts)
3315       Start -= NumElts - NumLaneElts;
3316
3317     // Make sure we're shifting in the right direction.
3318     if (Start <= (int)(i+l))
3319       return false;
3320
3321     Start -= i;
3322
3323     // Check the rest of the elements to see if they are consecutive.
3324     for (++i; i != NumLaneElts; ++i) {
3325       int Idx = Mask[i+l];
3326
3327       // Make sure its in this lane
3328       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3329           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3330         return false;
3331
3332       // If not lane 0, then we must match lane 0
3333       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3334         return false;
3335
3336       if (Idx >= (int)NumElts)
3337         Idx -= NumElts - NumLaneElts;
3338
3339       if (!isUndefOrEqual(Idx, Start+i))
3340         return false;
3341
3342     }
3343   }
3344
3345   return true;
3346 }
3347
3348 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3349 /// the two vector operands have swapped position.
3350 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3351                                      unsigned NumElems) {
3352   for (unsigned i = 0; i != NumElems; ++i) {
3353     int idx = Mask[i];
3354     if (idx < 0)
3355       continue;
3356     else if (idx < (int)NumElems)
3357       Mask[i] = idx + NumElems;
3358     else
3359       Mask[i] = idx - NumElems;
3360   }
3361 }
3362
3363 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3364 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3365 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3366 /// reverse of what x86 shuffles want.
3367 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3368                         bool Commuted = false) {
3369   if (!HasAVX && VT.getSizeInBits() == 256)
3370     return false;
3371
3372   unsigned NumElems = VT.getVectorNumElements();
3373   unsigned NumLanes = VT.getSizeInBits()/128;
3374   unsigned NumLaneElems = NumElems/NumLanes;
3375
3376   if (NumLaneElems != 2 && NumLaneElems != 4)
3377     return false;
3378
3379   // VSHUFPSY 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 =>   X7    X6    X5    X4    X3    X2    X1    X0
3384   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3385   //
3386   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3387   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3388   //
3389   // VSHUFPDY divides the resulting vector into 4 chunks.
3390   // The sources are also splitted into 4 chunks, and each destination
3391   // chunk must come from a different source chunk.
3392   //
3393   //  SRC1 =>      X3       X2       X1       X0
3394   //  SRC2 =>      Y3       Y2       Y1       Y0
3395   //
3396   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3397   //
3398   unsigned HalfLaneElems = NumLaneElems/2;
3399   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3400     for (unsigned i = 0; i != NumLaneElems; ++i) {
3401       int Idx = Mask[i+l];
3402       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3403       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3404         return false;
3405       // For VSHUFPSY, the mask of the second half must be the same as the
3406       // first but with the appropriate offsets. This works in the same way as
3407       // VPERMILPS works with masks.
3408       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3409         continue;
3410       if (!isUndefOrEqual(Idx, Mask[i]+l))
3411         return false;
3412     }
3413   }
3414
3415   return true;
3416 }
3417
3418 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3419 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3420 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3421   if (!VT.is128BitVector())
3422     return false;
3423
3424   unsigned NumElems = VT.getVectorNumElements();
3425
3426   if (NumElems != 4)
3427     return false;
3428
3429   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3430   return isUndefOrEqual(Mask[0], 6) &&
3431          isUndefOrEqual(Mask[1], 7) &&
3432          isUndefOrEqual(Mask[2], 2) &&
3433          isUndefOrEqual(Mask[3], 3);
3434 }
3435
3436 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3437 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3438 /// <2, 3, 2, 3>
3439 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3440   if (!VT.is128BitVector())
3441     return false;
3442
3443   unsigned NumElems = VT.getVectorNumElements();
3444
3445   if (NumElems != 4)
3446     return false;
3447
3448   return isUndefOrEqual(Mask[0], 2) &&
3449          isUndefOrEqual(Mask[1], 3) &&
3450          isUndefOrEqual(Mask[2], 2) &&
3451          isUndefOrEqual(Mask[3], 3);
3452 }
3453
3454 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3455 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3456 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3457   if (!VT.is128BitVector())
3458     return false;
3459
3460   unsigned NumElems = VT.getVectorNumElements();
3461
3462   if (NumElems != 2 && NumElems != 4)
3463     return false;
3464
3465   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3466     if (!isUndefOrEqual(Mask[i], i + NumElems))
3467       return false;
3468
3469   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3470     if (!isUndefOrEqual(Mask[i], i))
3471       return false;
3472
3473   return true;
3474 }
3475
3476 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3477 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3478 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3479   if (!VT.is128BitVector())
3480     return false;
3481
3482   unsigned NumElems = VT.getVectorNumElements();
3483
3484   if (NumElems != 2 && NumElems != 4)
3485     return false;
3486
3487   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3488     if (!isUndefOrEqual(Mask[i], i))
3489       return false;
3490
3491   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3492     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3493       return false;
3494
3495   return true;
3496 }
3497
3498 //
3499 // Some special combinations that can be optimized.
3500 //
3501 static
3502 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3503                                SelectionDAG &DAG) {
3504   EVT VT = SVOp->getValueType(0);
3505   DebugLoc dl = SVOp->getDebugLoc();
3506
3507   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3508     return SDValue();
3509
3510   ArrayRef<int> Mask = SVOp->getMask();
3511
3512   // These are the special masks that may be optimized.
3513   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3514   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3515   bool MatchEvenMask = true;
3516   bool MatchOddMask  = true;
3517   for (int i=0; i<8; ++i) {
3518     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3519       MatchEvenMask = false;
3520     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3521       MatchOddMask = false;
3522   }
3523
3524   if (!MatchEvenMask && !MatchOddMask)
3525     return SDValue();
3526   
3527   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3528
3529   SDValue Op0 = SVOp->getOperand(0);
3530   SDValue Op1 = SVOp->getOperand(1);
3531
3532   if (MatchEvenMask) {
3533     // Shift the second operand right to 32 bits.
3534     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3535     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3536   } else {
3537     // Shift the first operand left to 32 bits.
3538     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3539     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3540   }
3541   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3542   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3543 }
3544
3545 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3546 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3547 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3548                          bool HasAVX2, bool V2IsSplat = false) {
3549   unsigned NumElts = VT.getVectorNumElements();
3550
3551   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3552          "Unsupported vector type for unpckh");
3553
3554   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3555       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3556     return false;
3557
3558   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3559   // independently on 128-bit lanes.
3560   unsigned NumLanes = VT.getSizeInBits()/128;
3561   unsigned NumLaneElts = NumElts/NumLanes;
3562
3563   for (unsigned l = 0; l != NumLanes; ++l) {
3564     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3565          i != (l+1)*NumLaneElts;
3566          i += 2, ++j) {
3567       int BitI  = Mask[i];
3568       int BitI1 = Mask[i+1];
3569       if (!isUndefOrEqual(BitI, j))
3570         return false;
3571       if (V2IsSplat) {
3572         if (!isUndefOrEqual(BitI1, NumElts))
3573           return false;
3574       } else {
3575         if (!isUndefOrEqual(BitI1, j + NumElts))
3576           return false;
3577       }
3578     }
3579   }
3580
3581   return true;
3582 }
3583
3584 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3585 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3586 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3587                          bool HasAVX2, bool V2IsSplat = false) {
3588   unsigned NumElts = VT.getVectorNumElements();
3589
3590   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3591          "Unsupported vector type for unpckh");
3592
3593   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3594       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3595     return false;
3596
3597   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3598   // independently on 128-bit lanes.
3599   unsigned NumLanes = VT.getSizeInBits()/128;
3600   unsigned NumLaneElts = NumElts/NumLanes;
3601
3602   for (unsigned l = 0; l != NumLanes; ++l) {
3603     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3604          i != (l+1)*NumLaneElts; i += 2, ++j) {
3605       int BitI  = Mask[i];
3606       int BitI1 = Mask[i+1];
3607       if (!isUndefOrEqual(BitI, j))
3608         return false;
3609       if (V2IsSplat) {
3610         if (isUndefOrEqual(BitI1, NumElts))
3611           return false;
3612       } else {
3613         if (!isUndefOrEqual(BitI1, j+NumElts))
3614           return false;
3615       }
3616     }
3617   }
3618   return true;
3619 }
3620
3621 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3622 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3623 /// <0, 0, 1, 1>
3624 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3625                                   bool HasAVX2) {
3626   unsigned NumElts = VT.getVectorNumElements();
3627
3628   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3629          "Unsupported vector type for unpckh");
3630
3631   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3632       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3633     return false;
3634
3635   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3636   // FIXME: Need a better way to get rid of this, there's no latency difference
3637   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3638   // the former later. We should also remove the "_undef" special mask.
3639   if (NumElts == 4 && VT.getSizeInBits() == 256)
3640     return false;
3641
3642   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3643   // independently on 128-bit lanes.
3644   unsigned NumLanes = VT.getSizeInBits()/128;
3645   unsigned NumLaneElts = NumElts/NumLanes;
3646
3647   for (unsigned l = 0; l != NumLanes; ++l) {
3648     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3649          i != (l+1)*NumLaneElts;
3650          i += 2, ++j) {
3651       int BitI  = Mask[i];
3652       int BitI1 = Mask[i+1];
3653
3654       if (!isUndefOrEqual(BitI, j))
3655         return false;
3656       if (!isUndefOrEqual(BitI1, j))
3657         return false;
3658     }
3659   }
3660
3661   return true;
3662 }
3663
3664 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3665 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3666 /// <2, 2, 3, 3>
3667 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3668   unsigned NumElts = VT.getVectorNumElements();
3669
3670   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3671          "Unsupported vector type for unpckh");
3672
3673   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3674       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3675     return false;
3676
3677   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3678   // independently on 128-bit lanes.
3679   unsigned NumLanes = VT.getSizeInBits()/128;
3680   unsigned NumLaneElts = NumElts/NumLanes;
3681
3682   for (unsigned l = 0; l != NumLanes; ++l) {
3683     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3684          i != (l+1)*NumLaneElts; i += 2, ++j) {
3685       int BitI  = Mask[i];
3686       int BitI1 = Mask[i+1];
3687       if (!isUndefOrEqual(BitI, j))
3688         return false;
3689       if (!isUndefOrEqual(BitI1, j))
3690         return false;
3691     }
3692   }
3693   return true;
3694 }
3695
3696 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3697 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3698 /// MOVSD, and MOVD, i.e. setting the lowest element.
3699 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3700   if (VT.getVectorElementType().getSizeInBits() < 32)
3701     return false;
3702   if (!VT.is128BitVector())
3703     return false;
3704
3705   unsigned NumElts = VT.getVectorNumElements();
3706
3707   if (!isUndefOrEqual(Mask[0], NumElts))
3708     return false;
3709
3710   for (unsigned i = 1; i != NumElts; ++i)
3711     if (!isUndefOrEqual(Mask[i], i))
3712       return false;
3713
3714   return true;
3715 }
3716
3717 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3718 /// as permutations between 128-bit chunks or halves. As an example: this
3719 /// shuffle bellow:
3720 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3721 /// The first half comes from the second half of V1 and the second half from the
3722 /// the second half of V2.
3723 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3724   if (!HasAVX || !VT.is256BitVector())
3725     return false;
3726
3727   // The shuffle result is divided into half A and half B. In total the two
3728   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3729   // B must come from C, D, E or F.
3730   unsigned HalfSize = VT.getVectorNumElements()/2;
3731   bool MatchA = false, MatchB = false;
3732
3733   // Check if A comes from one of C, D, E, F.
3734   for (unsigned Half = 0; Half != 4; ++Half) {
3735     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3736       MatchA = true;
3737       break;
3738     }
3739   }
3740
3741   // Check if B comes from one of C, D, E, F.
3742   for (unsigned Half = 0; Half != 4; ++Half) {
3743     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3744       MatchB = true;
3745       break;
3746     }
3747   }
3748
3749   return MatchA && MatchB;
3750 }
3751
3752 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3753 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3754 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3755   EVT VT = SVOp->getValueType(0);
3756
3757   unsigned HalfSize = VT.getVectorNumElements()/2;
3758
3759   unsigned FstHalf = 0, SndHalf = 0;
3760   for (unsigned i = 0; i < HalfSize; ++i) {
3761     if (SVOp->getMaskElt(i) > 0) {
3762       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3763       break;
3764     }
3765   }
3766   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3767     if (SVOp->getMaskElt(i) > 0) {
3768       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3769       break;
3770     }
3771   }
3772
3773   return (FstHalf | (SndHalf << 4));
3774 }
3775
3776 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3777 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3778 /// Note that VPERMIL mask matching is different depending whether theunderlying
3779 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3780 /// to the same elements of the low, but to the higher half of the source.
3781 /// In VPERMILPD the two lanes could be shuffled independently of each other
3782 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3783 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3784   if (!HasAVX)
3785     return false;
3786
3787   unsigned NumElts = VT.getVectorNumElements();
3788   // Only match 256-bit with 32/64-bit types
3789   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3790     return false;
3791
3792   unsigned NumLanes = VT.getSizeInBits()/128;
3793   unsigned LaneSize = NumElts/NumLanes;
3794   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3795     for (unsigned i = 0; i != LaneSize; ++i) {
3796       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3797         return false;
3798       if (NumElts != 8 || l == 0)
3799         continue;
3800       // VPERMILPS handling
3801       if (Mask[i] < 0)
3802         continue;
3803       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3804         return false;
3805     }
3806   }
3807
3808   return true;
3809 }
3810
3811 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3812 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3813 /// element of vector 2 and the other elements to come from vector 1 in order.
3814 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3815                                bool V2IsSplat = false, bool V2IsUndef = false) {
3816   if (!VT.is128BitVector())
3817     return false;
3818
3819   unsigned NumOps = VT.getVectorNumElements();
3820   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3821     return false;
3822
3823   if (!isUndefOrEqual(Mask[0], 0))
3824     return false;
3825
3826   for (unsigned i = 1; i != NumOps; ++i)
3827     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3828           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3829           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3830       return false;
3831
3832   return true;
3833 }
3834
3835 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3836 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3837 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3838 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3839                            const X86Subtarget *Subtarget) {
3840   if (!Subtarget->hasSSE3())
3841     return false;
3842
3843   unsigned NumElems = VT.getVectorNumElements();
3844
3845   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3846       (VT.getSizeInBits() == 256 && NumElems != 8))
3847     return false;
3848
3849   // "i+1" is the value the indexed mask element must have
3850   for (unsigned i = 0; i != NumElems; i += 2)
3851     if (!isUndefOrEqual(Mask[i], i+1) ||
3852         !isUndefOrEqual(Mask[i+1], i+1))
3853       return false;
3854
3855   return true;
3856 }
3857
3858 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3859 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3860 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3861 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3862                            const X86Subtarget *Subtarget) {
3863   if (!Subtarget->hasSSE3())
3864     return false;
3865
3866   unsigned NumElems = VT.getVectorNumElements();
3867
3868   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3869       (VT.getSizeInBits() == 256 && NumElems != 8))
3870     return false;
3871
3872   // "i" is the value the indexed mask element must have
3873   for (unsigned i = 0; i != NumElems; i += 2)
3874     if (!isUndefOrEqual(Mask[i], i) ||
3875         !isUndefOrEqual(Mask[i+1], i))
3876       return false;
3877
3878   return true;
3879 }
3880
3881 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3882 /// specifies a shuffle of elements that is suitable for input to 256-bit
3883 /// version of MOVDDUP.
3884 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3885   if (!HasAVX || !VT.is256BitVector())
3886     return false;
3887
3888   unsigned NumElts = VT.getVectorNumElements();
3889   if (NumElts != 4)
3890     return false;
3891
3892   for (unsigned i = 0; i != NumElts/2; ++i)
3893     if (!isUndefOrEqual(Mask[i], 0))
3894       return false;
3895   for (unsigned i = NumElts/2; i != NumElts; ++i)
3896     if (!isUndefOrEqual(Mask[i], NumElts/2))
3897       return false;
3898   return true;
3899 }
3900
3901 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3902 /// specifies a shuffle of elements that is suitable for input to 128-bit
3903 /// version of MOVDDUP.
3904 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3905   if (!VT.is128BitVector())
3906     return false;
3907
3908   unsigned e = VT.getVectorNumElements() / 2;
3909   for (unsigned i = 0; i != e; ++i)
3910     if (!isUndefOrEqual(Mask[i], i))
3911       return false;
3912   for (unsigned i = 0; i != e; ++i)
3913     if (!isUndefOrEqual(Mask[e+i], i))
3914       return false;
3915   return true;
3916 }
3917
3918 /// isVEXTRACTF128Index - Return true if the specified
3919 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3920 /// suitable for input to VEXTRACTF128.
3921 bool X86::isVEXTRACTF128Index(SDNode *N) {
3922   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3923     return false;
3924
3925   // The index should be aligned on a 128-bit boundary.
3926   uint64_t Index =
3927     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3928
3929   unsigned VL = N->getValueType(0).getVectorNumElements();
3930   unsigned VBits = N->getValueType(0).getSizeInBits();
3931   unsigned ElSize = VBits / VL;
3932   bool Result = (Index * ElSize) % 128 == 0;
3933
3934   return Result;
3935 }
3936
3937 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3938 /// operand specifies a subvector insert that is suitable for input to
3939 /// VINSERTF128.
3940 bool X86::isVINSERTF128Index(SDNode *N) {
3941   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3942     return false;
3943
3944   // The index should be aligned on a 128-bit boundary.
3945   uint64_t Index =
3946     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3947
3948   unsigned VL = N->getValueType(0).getVectorNumElements();
3949   unsigned VBits = N->getValueType(0).getSizeInBits();
3950   unsigned ElSize = VBits / VL;
3951   bool Result = (Index * ElSize) % 128 == 0;
3952
3953   return Result;
3954 }
3955
3956 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3957 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3958 /// Handles 128-bit and 256-bit.
3959 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3960   EVT VT = N->getValueType(0);
3961
3962   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3963          "Unsupported vector type for PSHUF/SHUFP");
3964
3965   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3966   // independently on 128-bit lanes.
3967   unsigned NumElts = VT.getVectorNumElements();
3968   unsigned NumLanes = VT.getSizeInBits()/128;
3969   unsigned NumLaneElts = NumElts/NumLanes;
3970
3971   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3972          "Only supports 2 or 4 elements per lane");
3973
3974   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3975   unsigned Mask = 0;
3976   for (unsigned i = 0; i != NumElts; ++i) {
3977     int Elt = N->getMaskElt(i);
3978     if (Elt < 0) continue;
3979     Elt &= NumLaneElts - 1;
3980     unsigned ShAmt = (i << Shift) % 8;
3981     Mask |= Elt << ShAmt;
3982   }
3983
3984   return Mask;
3985 }
3986
3987 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3988 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3989 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3990   EVT VT = N->getValueType(0);
3991
3992   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3993          "Unsupported vector type for PSHUFHW");
3994
3995   unsigned NumElts = VT.getVectorNumElements();
3996
3997   unsigned Mask = 0;
3998   for (unsigned l = 0; l != NumElts; l += 8) {
3999     // 8 nodes per lane, but we only care about the last 4.
4000     for (unsigned i = 0; i < 4; ++i) {
4001       int Elt = N->getMaskElt(l+i+4);
4002       if (Elt < 0) continue;
4003       Elt &= 0x3; // only 2-bits.
4004       Mask |= Elt << (i * 2);
4005     }
4006   }
4007
4008   return Mask;
4009 }
4010
4011 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4012 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4013 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4014   EVT VT = N->getValueType(0);
4015
4016   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4017          "Unsupported vector type for PSHUFHW");
4018
4019   unsigned NumElts = VT.getVectorNumElements();
4020
4021   unsigned Mask = 0;
4022   for (unsigned l = 0; l != NumElts; l += 8) {
4023     // 8 nodes per lane, but we only care about the first 4.
4024     for (unsigned i = 0; i < 4; ++i) {
4025       int Elt = N->getMaskElt(l+i);
4026       if (Elt < 0) continue;
4027       Elt &= 0x3; // only 2-bits
4028       Mask |= Elt << (i * 2);
4029     }
4030   }
4031
4032   return Mask;
4033 }
4034
4035 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4036 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4037 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4038   EVT VT = SVOp->getValueType(0);
4039   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4040
4041   unsigned NumElts = VT.getVectorNumElements();
4042   unsigned NumLanes = VT.getSizeInBits()/128;
4043   unsigned NumLaneElts = NumElts/NumLanes;
4044
4045   int Val = 0;
4046   unsigned i;
4047   for (i = 0; i != NumElts; ++i) {
4048     Val = SVOp->getMaskElt(i);
4049     if (Val >= 0)
4050       break;
4051   }
4052   if (Val >= (int)NumElts)
4053     Val -= NumElts - NumLaneElts;
4054
4055   assert(Val - i > 0 && "PALIGNR imm should be positive");
4056   return (Val - i) * EltSize;
4057 }
4058
4059 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4060 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4061 /// instructions.
4062 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4063   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4064     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4065
4066   uint64_t Index =
4067     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4068
4069   EVT VecVT = N->getOperand(0).getValueType();
4070   EVT ElVT = VecVT.getVectorElementType();
4071
4072   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4073   return Index / NumElemsPerChunk;
4074 }
4075
4076 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4077 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4078 /// instructions.
4079 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4080   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4081     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4082
4083   uint64_t Index =
4084     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4085
4086   EVT VecVT = N->getValueType(0);
4087   EVT ElVT = VecVT.getVectorElementType();
4088
4089   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4090   return Index / NumElemsPerChunk;
4091 }
4092
4093 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4094 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4095 /// Handles 256-bit.
4096 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4097   EVT VT = N->getValueType(0);
4098
4099   unsigned NumElts = VT.getVectorNumElements();
4100
4101   assert((VT.is256BitVector() && NumElts == 4) &&
4102          "Unsupported vector type for VPERMQ/VPERMPD");
4103
4104   unsigned Mask = 0;
4105   for (unsigned i = 0; i != NumElts; ++i) {
4106     int Elt = N->getMaskElt(i);
4107     if (Elt < 0)
4108       continue;
4109     Mask |= Elt << (i*2);
4110   }
4111
4112   return Mask;
4113 }
4114 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4115 /// constant +0.0.
4116 bool X86::isZeroNode(SDValue Elt) {
4117   return ((isa<ConstantSDNode>(Elt) &&
4118            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4119           (isa<ConstantFPSDNode>(Elt) &&
4120            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4121 }
4122
4123 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4124 /// their permute mask.
4125 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4126                                     SelectionDAG &DAG) {
4127   EVT VT = SVOp->getValueType(0);
4128   unsigned NumElems = VT.getVectorNumElements();
4129   SmallVector<int, 8> MaskVec;
4130
4131   for (unsigned i = 0; i != NumElems; ++i) {
4132     int Idx = SVOp->getMaskElt(i);
4133     if (Idx >= 0) {
4134       if (Idx < (int)NumElems)
4135         Idx += NumElems;
4136       else
4137         Idx -= NumElems;
4138     }
4139     MaskVec.push_back(Idx);
4140   }
4141   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4142                               SVOp->getOperand(0), &MaskVec[0]);
4143 }
4144
4145 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4146 /// match movhlps. The lower half elements should come from upper half of
4147 /// V1 (and in order), and the upper half elements should come from the upper
4148 /// half of V2 (and in order).
4149 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4150   if (!VT.is128BitVector())
4151     return false;
4152   if (VT.getVectorNumElements() != 4)
4153     return false;
4154   for (unsigned i = 0, e = 2; i != e; ++i)
4155     if (!isUndefOrEqual(Mask[i], i+2))
4156       return false;
4157   for (unsigned i = 2; i != 4; ++i)
4158     if (!isUndefOrEqual(Mask[i], i+4))
4159       return false;
4160   return true;
4161 }
4162
4163 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4164 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4165 /// required.
4166 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4167   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4168     return false;
4169   N = N->getOperand(0).getNode();
4170   if (!ISD::isNON_EXTLoad(N))
4171     return false;
4172   if (LD)
4173     *LD = cast<LoadSDNode>(N);
4174   return true;
4175 }
4176
4177 // Test whether the given value is a vector value which will be legalized
4178 // into a load.
4179 static bool WillBeConstantPoolLoad(SDNode *N) {
4180   if (N->getOpcode() != ISD::BUILD_VECTOR)
4181     return false;
4182
4183   // Check for any non-constant elements.
4184   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4185     switch (N->getOperand(i).getNode()->getOpcode()) {
4186     case ISD::UNDEF:
4187     case ISD::ConstantFP:
4188     case ISD::Constant:
4189       break;
4190     default:
4191       return false;
4192     }
4193
4194   // Vectors of all-zeros and all-ones are materialized with special
4195   // instructions rather than being loaded.
4196   return !ISD::isBuildVectorAllZeros(N) &&
4197          !ISD::isBuildVectorAllOnes(N);
4198 }
4199
4200 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4201 /// match movlp{s|d}. The lower half elements should come from lower half of
4202 /// V1 (and in order), and the upper half elements should come from the upper
4203 /// half of V2 (and in order). And since V1 will become the source of the
4204 /// MOVLP, it must be either a vector load or a scalar load to vector.
4205 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4206                                ArrayRef<int> Mask, EVT VT) {
4207   if (!VT.is128BitVector())
4208     return false;
4209
4210   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4211     return false;
4212   // Is V2 is a vector load, don't do this transformation. We will try to use
4213   // load folding shufps op.
4214   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4215     return false;
4216
4217   unsigned NumElems = VT.getVectorNumElements();
4218
4219   if (NumElems != 2 && NumElems != 4)
4220     return false;
4221   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4222     if (!isUndefOrEqual(Mask[i], i))
4223       return false;
4224   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4225     if (!isUndefOrEqual(Mask[i], i+NumElems))
4226       return false;
4227   return true;
4228 }
4229
4230 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4231 /// all the same.
4232 static bool isSplatVector(SDNode *N) {
4233   if (N->getOpcode() != ISD::BUILD_VECTOR)
4234     return false;
4235
4236   SDValue SplatValue = N->getOperand(0);
4237   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4238     if (N->getOperand(i) != SplatValue)
4239       return false;
4240   return true;
4241 }
4242
4243 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4244 /// to an zero vector.
4245 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4246 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4247   SDValue V1 = N->getOperand(0);
4248   SDValue V2 = N->getOperand(1);
4249   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4250   for (unsigned i = 0; i != NumElems; ++i) {
4251     int Idx = N->getMaskElt(i);
4252     if (Idx >= (int)NumElems) {
4253       unsigned Opc = V2.getOpcode();
4254       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4255         continue;
4256       if (Opc != ISD::BUILD_VECTOR ||
4257           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4258         return false;
4259     } else if (Idx >= 0) {
4260       unsigned Opc = V1.getOpcode();
4261       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4262         continue;
4263       if (Opc != ISD::BUILD_VECTOR ||
4264           !X86::isZeroNode(V1.getOperand(Idx)))
4265         return false;
4266     }
4267   }
4268   return true;
4269 }
4270
4271 /// getZeroVector - Returns a vector of specified type with all zero elements.
4272 ///
4273 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4274                              SelectionDAG &DAG, DebugLoc dl) {
4275   assert(VT.isVector() && "Expected a vector type");
4276   unsigned Size = VT.getSizeInBits();
4277
4278   // Always build SSE zero vectors as <4 x i32> bitcasted
4279   // to their dest type. This ensures they get CSE'd.
4280   SDValue Vec;
4281   if (Size == 128) {  // SSE
4282     if (Subtarget->hasSSE2()) {  // SSE2
4283       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4284       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4285     } else { // SSE1
4286       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4287       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4288     }
4289   } else if (Size == 256) { // AVX
4290     if (Subtarget->hasAVX2()) { // AVX2
4291       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4292       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4293       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4294     } else {
4295       // 256-bit logic and arithmetic instructions in AVX are all
4296       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4297       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4298       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4299       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4300     }
4301   } else
4302     llvm_unreachable("Unexpected vector type");
4303
4304   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4305 }
4306
4307 /// getOnesVector - Returns a vector of specified type with all bits set.
4308 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4309 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4310 /// Then bitcast to their original type, ensuring they get CSE'd.
4311 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4312                              DebugLoc dl) {
4313   assert(VT.isVector() && "Expected a vector type");
4314   unsigned Size = VT.getSizeInBits();
4315
4316   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4317   SDValue Vec;
4318   if (Size == 256) {
4319     if (HasAVX2) { // AVX2
4320       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4321       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4322     } else { // AVX
4323       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4324       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4325     }
4326   } else if (Size == 128) {
4327     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4328   } else
4329     llvm_unreachable("Unexpected vector type");
4330
4331   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4332 }
4333
4334 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4335 /// that point to V2 points to its first element.
4336 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4337   for (unsigned i = 0; i != NumElems; ++i) {
4338     if (Mask[i] > (int)NumElems) {
4339       Mask[i] = NumElems;
4340     }
4341   }
4342 }
4343
4344 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4345 /// operation of specified width.
4346 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4347                        SDValue V2) {
4348   unsigned NumElems = VT.getVectorNumElements();
4349   SmallVector<int, 8> Mask;
4350   Mask.push_back(NumElems);
4351   for (unsigned i = 1; i != NumElems; ++i)
4352     Mask.push_back(i);
4353   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4354 }
4355
4356 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4357 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4358                           SDValue V2) {
4359   unsigned NumElems = VT.getVectorNumElements();
4360   SmallVector<int, 8> Mask;
4361   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4362     Mask.push_back(i);
4363     Mask.push_back(i + NumElems);
4364   }
4365   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4366 }
4367
4368 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4369 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4370                           SDValue V2) {
4371   unsigned NumElems = VT.getVectorNumElements();
4372   SmallVector<int, 8> Mask;
4373   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4374     Mask.push_back(i + Half);
4375     Mask.push_back(i + NumElems + Half);
4376   }
4377   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4378 }
4379
4380 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4381 // a generic shuffle instruction because the target has no such instructions.
4382 // Generate shuffles which repeat i16 and i8 several times until they can be
4383 // represented by v4f32 and then be manipulated by target suported shuffles.
4384 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4385   EVT VT = V.getValueType();
4386   int NumElems = VT.getVectorNumElements();
4387   DebugLoc dl = V.getDebugLoc();
4388
4389   while (NumElems > 4) {
4390     if (EltNo < NumElems/2) {
4391       V = getUnpackl(DAG, dl, VT, V, V);
4392     } else {
4393       V = getUnpackh(DAG, dl, VT, V, V);
4394       EltNo -= NumElems/2;
4395     }
4396     NumElems >>= 1;
4397   }
4398   return V;
4399 }
4400
4401 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4402 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4403   EVT VT = V.getValueType();
4404   DebugLoc dl = V.getDebugLoc();
4405   unsigned Size = VT.getSizeInBits();
4406
4407   if (Size == 128) {
4408     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4409     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4410     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4411                              &SplatMask[0]);
4412   } else if (Size == 256) {
4413     // To use VPERMILPS to splat scalars, the second half of indicies must
4414     // refer to the higher part, which is a duplication of the lower one,
4415     // because VPERMILPS can only handle in-lane permutations.
4416     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4417                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4418
4419     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4420     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4421                              &SplatMask[0]);
4422   } else
4423     llvm_unreachable("Vector size not supported");
4424
4425   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4426 }
4427
4428 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4429 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4430   EVT SrcVT = SV->getValueType(0);
4431   SDValue V1 = SV->getOperand(0);
4432   DebugLoc dl = SV->getDebugLoc();
4433
4434   int EltNo = SV->getSplatIndex();
4435   int NumElems = SrcVT.getVectorNumElements();
4436   unsigned Size = SrcVT.getSizeInBits();
4437
4438   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4439           "Unknown how to promote splat for type");
4440
4441   // Extract the 128-bit part containing the splat element and update
4442   // the splat element index when it refers to the higher register.
4443   if (Size == 256) {
4444     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4445     if (EltNo >= NumElems/2)
4446       EltNo -= NumElems/2;
4447   }
4448
4449   // All i16 and i8 vector types can't be used directly by a generic shuffle
4450   // instruction because the target has no such instruction. Generate shuffles
4451   // which repeat i16 and i8 several times until they fit in i32, and then can
4452   // be manipulated by target suported shuffles.
4453   EVT EltVT = SrcVT.getVectorElementType();
4454   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4455     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4456
4457   // Recreate the 256-bit vector and place the same 128-bit vector
4458   // into the low and high part. This is necessary because we want
4459   // to use VPERM* to shuffle the vectors
4460   if (Size == 256) {
4461     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4462   }
4463
4464   return getLegalSplat(DAG, V1, EltNo);
4465 }
4466
4467 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4468 /// vector of zero or undef vector.  This produces a shuffle where the low
4469 /// element of V2 is swizzled into the zero/undef vector, landing at element
4470 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4471 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4472                                            bool IsZero,
4473                                            const X86Subtarget *Subtarget,
4474                                            SelectionDAG &DAG) {
4475   EVT VT = V2.getValueType();
4476   SDValue V1 = IsZero
4477     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4478   unsigned NumElems = VT.getVectorNumElements();
4479   SmallVector<int, 16> MaskVec;
4480   for (unsigned i = 0; i != NumElems; ++i)
4481     // If this is the insertion idx, put the low elt of V2 here.
4482     MaskVec.push_back(i == Idx ? NumElems : i);
4483   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4484 }
4485
4486 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4487 /// target specific opcode. Returns true if the Mask could be calculated.
4488 /// Sets IsUnary to true if only uses one source.
4489 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4490                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4491   unsigned NumElems = VT.getVectorNumElements();
4492   SDValue ImmN;
4493
4494   IsUnary = false;
4495   switch(N->getOpcode()) {
4496   case X86ISD::SHUFP:
4497     ImmN = N->getOperand(N->getNumOperands()-1);
4498     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4499     break;
4500   case X86ISD::UNPCKH:
4501     DecodeUNPCKHMask(VT, Mask);
4502     break;
4503   case X86ISD::UNPCKL:
4504     DecodeUNPCKLMask(VT, Mask);
4505     break;
4506   case X86ISD::MOVHLPS:
4507     DecodeMOVHLPSMask(NumElems, Mask);
4508     break;
4509   case X86ISD::MOVLHPS:
4510     DecodeMOVLHPSMask(NumElems, Mask);
4511     break;
4512   case X86ISD::PSHUFD:
4513   case X86ISD::VPERMILP:
4514     ImmN = N->getOperand(N->getNumOperands()-1);
4515     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4516     IsUnary = true;
4517     break;
4518   case X86ISD::PSHUFHW:
4519     ImmN = N->getOperand(N->getNumOperands()-1);
4520     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4521     IsUnary = true;
4522     break;
4523   case X86ISD::PSHUFLW:
4524     ImmN = N->getOperand(N->getNumOperands()-1);
4525     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4526     IsUnary = true;
4527     break;
4528   case X86ISD::VPERMI:
4529     ImmN = N->getOperand(N->getNumOperands()-1);
4530     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4531     IsUnary = true;
4532     break;
4533   case X86ISD::MOVSS:
4534   case X86ISD::MOVSD: {
4535     // The index 0 always comes from the first element of the second source,
4536     // this is why MOVSS and MOVSD are used in the first place. The other
4537     // elements come from the other positions of the first source vector
4538     Mask.push_back(NumElems);
4539     for (unsigned i = 1; i != NumElems; ++i) {
4540       Mask.push_back(i);
4541     }
4542     break;
4543   }
4544   case X86ISD::VPERM2X128:
4545     ImmN = N->getOperand(N->getNumOperands()-1);
4546     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4547     if (Mask.empty()) return false;
4548     break;
4549   case X86ISD::MOVDDUP:
4550   case X86ISD::MOVLHPD:
4551   case X86ISD::MOVLPD:
4552   case X86ISD::MOVLPS:
4553   case X86ISD::MOVSHDUP:
4554   case X86ISD::MOVSLDUP:
4555   case X86ISD::PALIGN:
4556     // Not yet implemented
4557     return false;
4558   default: llvm_unreachable("unknown target shuffle node");
4559   }
4560
4561   return true;
4562 }
4563
4564 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4565 /// element of the result of the vector shuffle.
4566 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4567                                    unsigned Depth) {
4568   if (Depth == 6)
4569     return SDValue();  // Limit search depth.
4570
4571   SDValue V = SDValue(N, 0);
4572   EVT VT = V.getValueType();
4573   unsigned Opcode = V.getOpcode();
4574
4575   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4576   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4577     int Elt = SV->getMaskElt(Index);
4578
4579     if (Elt < 0)
4580       return DAG.getUNDEF(VT.getVectorElementType());
4581
4582     unsigned NumElems = VT.getVectorNumElements();
4583     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4584                                          : SV->getOperand(1);
4585     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4586   }
4587
4588   // Recurse into target specific vector shuffles to find scalars.
4589   if (isTargetShuffle(Opcode)) {
4590     MVT ShufVT = V.getValueType().getSimpleVT();
4591     unsigned NumElems = ShufVT.getVectorNumElements();
4592     SmallVector<int, 16> ShuffleMask;
4593     SDValue ImmN;
4594     bool IsUnary;
4595
4596     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4597       return SDValue();
4598
4599     int Elt = ShuffleMask[Index];
4600     if (Elt < 0)
4601       return DAG.getUNDEF(ShufVT.getVectorElementType());
4602
4603     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4604                                          : N->getOperand(1);
4605     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4606                                Depth+1);
4607   }
4608
4609   // Actual nodes that may contain scalar elements
4610   if (Opcode == ISD::BITCAST) {
4611     V = V.getOperand(0);
4612     EVT SrcVT = V.getValueType();
4613     unsigned NumElems = VT.getVectorNumElements();
4614
4615     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4616       return SDValue();
4617   }
4618
4619   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4620     return (Index == 0) ? V.getOperand(0)
4621                         : DAG.getUNDEF(VT.getVectorElementType());
4622
4623   if (V.getOpcode() == ISD::BUILD_VECTOR)
4624     return V.getOperand(Index);
4625
4626   return SDValue();
4627 }
4628
4629 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4630 /// shuffle operation which come from a consecutively from a zero. The
4631 /// search can start in two different directions, from left or right.
4632 static
4633 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4634                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4635   unsigned i;
4636   for (i = 0; i != NumElems; ++i) {
4637     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4638     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4639     if (!(Elt.getNode() &&
4640          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4641       break;
4642   }
4643
4644   return i;
4645 }
4646
4647 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4648 /// correspond consecutively to elements from one of the vector operands,
4649 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4650 static
4651 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4652                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4653                               unsigned NumElems, unsigned &OpNum) {
4654   bool SeenV1 = false;
4655   bool SeenV2 = false;
4656
4657   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4658     int Idx = SVOp->getMaskElt(i);
4659     // Ignore undef indicies
4660     if (Idx < 0)
4661       continue;
4662
4663     if (Idx < (int)NumElems)
4664       SeenV1 = true;
4665     else
4666       SeenV2 = true;
4667
4668     // Only accept consecutive elements from the same vector
4669     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4670       return false;
4671   }
4672
4673   OpNum = SeenV1 ? 0 : 1;
4674   return true;
4675 }
4676
4677 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4678 /// logical left shift of a vector.
4679 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4680                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4681   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4682   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4683               false /* check zeros from right */, DAG);
4684   unsigned OpSrc;
4685
4686   if (!NumZeros)
4687     return false;
4688
4689   // Considering the elements in the mask that are not consecutive zeros,
4690   // check if they consecutively come from only one of the source vectors.
4691   //
4692   //               V1 = {X, A, B, C}     0
4693   //                         \  \  \    /
4694   //   vector_shuffle V1, V2 <1, 2, 3, X>
4695   //
4696   if (!isShuffleMaskConsecutive(SVOp,
4697             0,                   // Mask Start Index
4698             NumElems-NumZeros,   // Mask End Index(exclusive)
4699             NumZeros,            // Where to start looking in the src vector
4700             NumElems,            // Number of elements in vector
4701             OpSrc))              // Which source operand ?
4702     return false;
4703
4704   isLeft = false;
4705   ShAmt = NumZeros;
4706   ShVal = SVOp->getOperand(OpSrc);
4707   return true;
4708 }
4709
4710 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4711 /// logical left shift of a vector.
4712 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4713                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4714   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4715   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4716               true /* check zeros from left */, DAG);
4717   unsigned OpSrc;
4718
4719   if (!NumZeros)
4720     return false;
4721
4722   // Considering the elements in the mask that are not consecutive zeros,
4723   // check if they consecutively come from only one of the source vectors.
4724   //
4725   //                           0    { A, B, X, X } = V2
4726   //                          / \    /  /
4727   //   vector_shuffle V1, V2 <X, X, 4, 5>
4728   //
4729   if (!isShuffleMaskConsecutive(SVOp,
4730             NumZeros,     // Mask Start Index
4731             NumElems,     // Mask End Index(exclusive)
4732             0,            // Where to start looking in the src vector
4733             NumElems,     // Number of elements in vector
4734             OpSrc))       // Which source operand ?
4735     return false;
4736
4737   isLeft = true;
4738   ShAmt = NumZeros;
4739   ShVal = SVOp->getOperand(OpSrc);
4740   return true;
4741 }
4742
4743 /// isVectorShift - Returns true if the shuffle can be implemented as a
4744 /// logical left or right shift of a vector.
4745 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4746                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4747   // Although the logic below support any bitwidth size, there are no
4748   // shift instructions which handle more than 128-bit vectors.
4749   if (!SVOp->getValueType(0).is128BitVector())
4750     return false;
4751
4752   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4753       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4754     return true;
4755
4756   return false;
4757 }
4758
4759 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4760 ///
4761 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4762                                        unsigned NumNonZero, unsigned NumZero,
4763                                        SelectionDAG &DAG,
4764                                        const X86Subtarget* Subtarget,
4765                                        const TargetLowering &TLI) {
4766   if (NumNonZero > 8)
4767     return SDValue();
4768
4769   DebugLoc dl = Op.getDebugLoc();
4770   SDValue V(0, 0);
4771   bool First = true;
4772   for (unsigned i = 0; i < 16; ++i) {
4773     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4774     if (ThisIsNonZero && First) {
4775       if (NumZero)
4776         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4777       else
4778         V = DAG.getUNDEF(MVT::v8i16);
4779       First = false;
4780     }
4781
4782     if ((i & 1) != 0) {
4783       SDValue ThisElt(0, 0), LastElt(0, 0);
4784       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4785       if (LastIsNonZero) {
4786         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4787                               MVT::i16, Op.getOperand(i-1));
4788       }
4789       if (ThisIsNonZero) {
4790         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4791         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4792                               ThisElt, DAG.getConstant(8, MVT::i8));
4793         if (LastIsNonZero)
4794           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4795       } else
4796         ThisElt = LastElt;
4797
4798       if (ThisElt.getNode())
4799         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4800                         DAG.getIntPtrConstant(i/2));
4801     }
4802   }
4803
4804   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4805 }
4806
4807 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4808 ///
4809 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4810                                      unsigned NumNonZero, unsigned NumZero,
4811                                      SelectionDAG &DAG,
4812                                      const X86Subtarget* Subtarget,
4813                                      const TargetLowering &TLI) {
4814   if (NumNonZero > 4)
4815     return SDValue();
4816
4817   DebugLoc dl = Op.getDebugLoc();
4818   SDValue V(0, 0);
4819   bool First = true;
4820   for (unsigned i = 0; i < 8; ++i) {
4821     bool isNonZero = (NonZeros & (1 << i)) != 0;
4822     if (isNonZero) {
4823       if (First) {
4824         if (NumZero)
4825           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4826         else
4827           V = DAG.getUNDEF(MVT::v8i16);
4828         First = false;
4829       }
4830       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4831                       MVT::v8i16, V, Op.getOperand(i),
4832                       DAG.getIntPtrConstant(i));
4833     }
4834   }
4835
4836   return V;
4837 }
4838
4839 /// getVShift - Return a vector logical shift node.
4840 ///
4841 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4842                          unsigned NumBits, SelectionDAG &DAG,
4843                          const TargetLowering &TLI, DebugLoc dl) {
4844   assert(VT.is128BitVector() && "Unknown type for VShift");
4845   EVT ShVT = MVT::v2i64;
4846   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4847   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4848   return DAG.getNode(ISD::BITCAST, dl, VT,
4849                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4850                              DAG.getConstant(NumBits,
4851                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4852 }
4853
4854 SDValue
4855 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4856                                           SelectionDAG &DAG) const {
4857
4858   // Check if the scalar load can be widened into a vector load. And if
4859   // the address is "base + cst" see if the cst can be "absorbed" into
4860   // the shuffle mask.
4861   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4862     SDValue Ptr = LD->getBasePtr();
4863     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4864       return SDValue();
4865     EVT PVT = LD->getValueType(0);
4866     if (PVT != MVT::i32 && PVT != MVT::f32)
4867       return SDValue();
4868
4869     int FI = -1;
4870     int64_t Offset = 0;
4871     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4872       FI = FINode->getIndex();
4873       Offset = 0;
4874     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4875                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4876       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4877       Offset = Ptr.getConstantOperandVal(1);
4878       Ptr = Ptr.getOperand(0);
4879     } else {
4880       return SDValue();
4881     }
4882
4883     // FIXME: 256-bit vector instructions don't require a strict alignment,
4884     // improve this code to support it better.
4885     unsigned RequiredAlign = VT.getSizeInBits()/8;
4886     SDValue Chain = LD->getChain();
4887     // Make sure the stack object alignment is at least 16 or 32.
4888     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4889     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4890       if (MFI->isFixedObjectIndex(FI)) {
4891         // Can't change the alignment. FIXME: It's possible to compute
4892         // the exact stack offset and reference FI + adjust offset instead.
4893         // If someone *really* cares about this. That's the way to implement it.
4894         return SDValue();
4895       } else {
4896         MFI->setObjectAlignment(FI, RequiredAlign);
4897       }
4898     }
4899
4900     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4901     // Ptr + (Offset & ~15).
4902     if (Offset < 0)
4903       return SDValue();
4904     if ((Offset % RequiredAlign) & 3)
4905       return SDValue();
4906     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4907     if (StartOffset)
4908       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4909                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4910
4911     int EltNo = (Offset - StartOffset) >> 2;
4912     unsigned NumElems = VT.getVectorNumElements();
4913
4914     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4915     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4916                              LD->getPointerInfo().getWithOffset(StartOffset),
4917                              false, false, false, 0);
4918
4919     SmallVector<int, 8> Mask;
4920     for (unsigned i = 0; i != NumElems; ++i)
4921       Mask.push_back(EltNo);
4922
4923     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4924   }
4925
4926   return SDValue();
4927 }
4928
4929 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4930 /// vector of type 'VT', see if the elements can be replaced by a single large
4931 /// load which has the same value as a build_vector whose operands are 'elts'.
4932 ///
4933 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4934 ///
4935 /// FIXME: we'd also like to handle the case where the last elements are zero
4936 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4937 /// There's even a handy isZeroNode for that purpose.
4938 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4939                                         DebugLoc &DL, SelectionDAG &DAG) {
4940   EVT EltVT = VT.getVectorElementType();
4941   unsigned NumElems = Elts.size();
4942
4943   LoadSDNode *LDBase = NULL;
4944   unsigned LastLoadedElt = -1U;
4945
4946   // For each element in the initializer, see if we've found a load or an undef.
4947   // If we don't find an initial load element, or later load elements are
4948   // non-consecutive, bail out.
4949   for (unsigned i = 0; i < NumElems; ++i) {
4950     SDValue Elt = Elts[i];
4951
4952     if (!Elt.getNode() ||
4953         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4954       return SDValue();
4955     if (!LDBase) {
4956       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4957         return SDValue();
4958       LDBase = cast<LoadSDNode>(Elt.getNode());
4959       LastLoadedElt = i;
4960       continue;
4961     }
4962     if (Elt.getOpcode() == ISD::UNDEF)
4963       continue;
4964
4965     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4966     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4967       return SDValue();
4968     LastLoadedElt = i;
4969   }
4970
4971   // If we have found an entire vector of loads and undefs, then return a large
4972   // load of the entire vector width starting at the base pointer.  If we found
4973   // consecutive loads for the low half, generate a vzext_load node.
4974   if (LastLoadedElt == NumElems - 1) {
4975     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4976       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4977                          LDBase->getPointerInfo(),
4978                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4979                          LDBase->isInvariant(), 0);
4980     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4981                        LDBase->getPointerInfo(),
4982                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4983                        LDBase->isInvariant(), LDBase->getAlignment());
4984   }
4985   if (NumElems == 4 && LastLoadedElt == 1 &&
4986       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4987     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4988     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4989     SDValue ResNode =
4990         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4991                                 LDBase->getPointerInfo(),
4992                                 LDBase->getAlignment(),
4993                                 false/*isVolatile*/, true/*ReadMem*/,
4994                                 false/*WriteMem*/);
4995
4996     // Make sure the newly-created LOAD is in the same position as LDBase in
4997     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
4998     // update uses of LDBase's output chain to use the TokenFactor.
4999     if (LDBase->hasAnyUseOfValue(1)) {
5000       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5001                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5002       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5003       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5004                              SDValue(ResNode.getNode(), 1));
5005     }
5006
5007     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5008   }
5009   return SDValue();
5010 }
5011
5012 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5013 /// to generate a splat value for the following cases:
5014 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5015 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5016 /// a scalar load, or a constant.
5017 /// The VBROADCAST node is returned when a pattern is found,
5018 /// or SDValue() otherwise.
5019 SDValue
5020 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
5021   if (!Subtarget->hasAVX())
5022     return SDValue();
5023
5024   EVT VT = Op.getValueType();
5025   DebugLoc dl = Op.getDebugLoc();
5026
5027   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5028          "Unsupported vector type for broadcast.");
5029
5030   SDValue Ld;
5031   bool ConstSplatVal;
5032
5033   switch (Op.getOpcode()) {
5034     default:
5035       // Unknown pattern found.
5036       return SDValue();
5037
5038     case ISD::BUILD_VECTOR: {
5039       // The BUILD_VECTOR node must be a splat.
5040       if (!isSplatVector(Op.getNode()))
5041         return SDValue();
5042
5043       Ld = Op.getOperand(0);
5044       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5045                      Ld.getOpcode() == ISD::ConstantFP);
5046
5047       // The suspected load node has several users. Make sure that all
5048       // of its users are from the BUILD_VECTOR node.
5049       // Constants may have multiple users.
5050       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5051         return SDValue();
5052       break;
5053     }
5054
5055     case ISD::VECTOR_SHUFFLE: {
5056       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5057
5058       // Shuffles must have a splat mask where the first element is
5059       // broadcasted.
5060       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5061         return SDValue();
5062
5063       SDValue Sc = Op.getOperand(0);
5064       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5065           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5066
5067         if (!Subtarget->hasAVX2())
5068           return SDValue();
5069
5070         // Use the register form of the broadcast instruction available on AVX2.
5071         if (VT.is256BitVector())
5072           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5073         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5074       }
5075
5076       Ld = Sc.getOperand(0);
5077       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5078                        Ld.getOpcode() == ISD::ConstantFP);
5079
5080       // The scalar_to_vector node and the suspected
5081       // load node must have exactly one user.
5082       // Constants may have multiple users.
5083       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5084         return SDValue();
5085       break;
5086     }
5087   }
5088
5089   bool Is256 = VT.is256BitVector();
5090
5091   // Handle the broadcasting a single constant scalar from the constant pool
5092   // into a vector. On Sandybridge it is still better to load a constant vector
5093   // from the constant pool and not to broadcast it from a scalar.
5094   if (ConstSplatVal && Subtarget->hasAVX2()) {
5095     EVT CVT = Ld.getValueType();
5096     assert(!CVT.isVector() && "Must not broadcast a vector type");
5097     unsigned ScalarSize = CVT.getSizeInBits();
5098
5099     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5100       const Constant *C = 0;
5101       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5102         C = CI->getConstantIntValue();
5103       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5104         C = CF->getConstantFPValue();
5105
5106       assert(C && "Invalid constant type");
5107
5108       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5109       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5110       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5111                        MachinePointerInfo::getConstantPool(),
5112                        false, false, false, Alignment);
5113
5114       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5115     }
5116   }
5117
5118   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5119   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5120
5121   // Handle AVX2 in-register broadcasts.
5122   if (!IsLoad && Subtarget->hasAVX2() &&
5123       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5124     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5125
5126   // The scalar source must be a normal load.
5127   if (!IsLoad)
5128     return SDValue();
5129
5130   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5131     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5132
5133   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5134   // double since there is no vbroadcastsd xmm
5135   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5136     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5137       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5138   }
5139
5140   // Unsupported broadcast.
5141   return SDValue();
5142 }
5143
5144 // LowerVectorFpExtend - Recognize the scalarized FP_EXTEND from v2f32 to v2f64
5145 // and convert it into X86ISD::VFPEXT due to the current ISD::FP_EXTEND has the
5146 // constraint of matching input/output vector elements.
5147 SDValue
5148 X86TargetLowering::LowerVectorFpExtend(SDValue &Op, SelectionDAG &DAG) const {
5149   DebugLoc DL = Op.getDebugLoc();
5150   SDNode *N = Op.getNode();
5151   EVT VT = Op.getValueType();
5152   unsigned NumElts = Op.getNumOperands();
5153
5154   // Check supported types and sub-targets.
5155   //
5156   // Only v2f32 -> v2f64 needs special handling.
5157   if (VT != MVT::v2f64 || !Subtarget->hasSSE2())
5158     return SDValue();
5159
5160   SDValue VecIn;
5161   EVT VecInVT;
5162   SmallVector<int, 8> Mask;
5163   EVT SrcVT = MVT::Other;
5164
5165   // Check the patterns could be translated into X86vfpext.
5166   for (unsigned i = 0; i < NumElts; ++i) {
5167     SDValue In = N->getOperand(i);
5168     unsigned Opcode = In.getOpcode();
5169
5170     // Skip if the element is undefined.
5171     if (Opcode == ISD::UNDEF) {
5172       Mask.push_back(-1);
5173       continue;
5174     }
5175
5176     // Quit if one of the elements is not defined from 'fpext'.
5177     if (Opcode != ISD::FP_EXTEND)
5178       return SDValue();
5179
5180     // Check how the source of 'fpext' is defined.
5181     SDValue L2In = In.getOperand(0);
5182     EVT L2InVT = L2In.getValueType();
5183
5184     // Check the original type
5185     if (SrcVT == MVT::Other)
5186       SrcVT = L2InVT;
5187     else if (SrcVT != L2InVT) // Quit if non-homogenous typed.
5188       return SDValue();
5189
5190     // Check whether the value being 'fpext'ed is extracted from the same
5191     // source.
5192     Opcode = L2In.getOpcode();
5193
5194     // Quit if it's not extracted with a constant index.
5195     if (Opcode != ISD::EXTRACT_VECTOR_ELT ||
5196         !isa<ConstantSDNode>(L2In.getOperand(1)))
5197       return SDValue();
5198
5199     SDValue ExtractedFromVec = L2In.getOperand(0);
5200
5201     if (VecIn.getNode() == 0) {
5202       VecIn = ExtractedFromVec;
5203       VecInVT = ExtractedFromVec.getValueType();
5204     } else if (VecIn != ExtractedFromVec) // Quit if built from more than 1 vec.
5205       return SDValue();
5206
5207     Mask.push_back(cast<ConstantSDNode>(L2In.getOperand(1))->getZExtValue());
5208   }
5209
5210   // Quit if all operands of BUILD_VECTOR are undefined.
5211   if (!VecIn.getNode())
5212     return SDValue();
5213
5214   // Fill the remaining mask as undef.
5215   for (unsigned i = NumElts; i < VecInVT.getVectorNumElements(); ++i)
5216     Mask.push_back(-1);
5217
5218   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
5219                      DAG.getVectorShuffle(VecInVT, DL,
5220                                           VecIn, DAG.getUNDEF(VecInVT),
5221                                           &Mask[0]));
5222 }
5223
5224 SDValue
5225 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5226   DebugLoc dl = Op.getDebugLoc();
5227
5228   EVT VT = Op.getValueType();
5229   EVT ExtVT = VT.getVectorElementType();
5230   unsigned NumElems = Op.getNumOperands();
5231
5232   // Vectors containing all zeros can be matched by pxor and xorps later
5233   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5234     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5235     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5236     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5237       return Op;
5238
5239     return getZeroVector(VT, Subtarget, DAG, dl);
5240   }
5241
5242   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5243   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5244   // vpcmpeqd on 256-bit vectors.
5245   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5246     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5247       return Op;
5248
5249     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5250   }
5251
5252   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5253   if (Broadcast.getNode())
5254     return Broadcast;
5255
5256   SDValue FpExt = LowerVectorFpExtend(Op, DAG);
5257   if (FpExt.getNode())
5258     return FpExt;
5259
5260   unsigned EVTBits = ExtVT.getSizeInBits();
5261
5262   unsigned NumZero  = 0;
5263   unsigned NumNonZero = 0;
5264   unsigned NonZeros = 0;
5265   bool IsAllConstants = true;
5266   SmallSet<SDValue, 8> Values;
5267   for (unsigned i = 0; i < NumElems; ++i) {
5268     SDValue Elt = Op.getOperand(i);
5269     if (Elt.getOpcode() == ISD::UNDEF)
5270       continue;
5271     Values.insert(Elt);
5272     if (Elt.getOpcode() != ISD::Constant &&
5273         Elt.getOpcode() != ISD::ConstantFP)
5274       IsAllConstants = false;
5275     if (X86::isZeroNode(Elt))
5276       NumZero++;
5277     else {
5278       NonZeros |= (1 << i);
5279       NumNonZero++;
5280     }
5281   }
5282
5283   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5284   if (NumNonZero == 0)
5285     return DAG.getUNDEF(VT);
5286
5287   // Special case for single non-zero, non-undef, element.
5288   if (NumNonZero == 1) {
5289     unsigned Idx = CountTrailingZeros_32(NonZeros);
5290     SDValue Item = Op.getOperand(Idx);
5291
5292     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5293     // the value are obviously zero, truncate the value to i32 and do the
5294     // insertion that way.  Only do this if the value is non-constant or if the
5295     // value is a constant being inserted into element 0.  It is cheaper to do
5296     // a constant pool load than it is to do a movd + shuffle.
5297     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5298         (!IsAllConstants || Idx == 0)) {
5299       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5300         // Handle SSE only.
5301         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5302         EVT VecVT = MVT::v4i32;
5303         unsigned VecElts = 4;
5304
5305         // Truncate the value (which may itself be a constant) to i32, and
5306         // convert it to a vector with movd (S2V+shuffle to zero extend).
5307         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5308         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5309         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5310
5311         // Now we have our 32-bit value zero extended in the low element of
5312         // a vector.  If Idx != 0, swizzle it into place.
5313         if (Idx != 0) {
5314           SmallVector<int, 4> Mask;
5315           Mask.push_back(Idx);
5316           for (unsigned i = 1; i != VecElts; ++i)
5317             Mask.push_back(i);
5318           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5319                                       &Mask[0]);
5320         }
5321         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5322       }
5323     }
5324
5325     // If we have a constant or non-constant insertion into the low element of
5326     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5327     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5328     // depending on what the source datatype is.
5329     if (Idx == 0) {
5330       if (NumZero == 0)
5331         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5332
5333       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5334           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5335         if (VT.is256BitVector()) {
5336           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5337           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5338                              Item, DAG.getIntPtrConstant(0));
5339         }
5340         assert(VT.is128BitVector() && "Expected an SSE value type!");
5341         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5342         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5343         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5344       }
5345
5346       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5347         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5348         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5349         if (VT.is256BitVector()) {
5350           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5351           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5352         } else {
5353           assert(VT.is128BitVector() && "Expected an SSE value type!");
5354           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5355         }
5356         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5357       }
5358     }
5359
5360     // Is it a vector logical left shift?
5361     if (NumElems == 2 && Idx == 1 &&
5362         X86::isZeroNode(Op.getOperand(0)) &&
5363         !X86::isZeroNode(Op.getOperand(1))) {
5364       unsigned NumBits = VT.getSizeInBits();
5365       return getVShift(true, VT,
5366                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5367                                    VT, Op.getOperand(1)),
5368                        NumBits/2, DAG, *this, dl);
5369     }
5370
5371     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5372       return SDValue();
5373
5374     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5375     // is a non-constant being inserted into an element other than the low one,
5376     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5377     // movd/movss) to move this into the low element, then shuffle it into
5378     // place.
5379     if (EVTBits == 32) {
5380       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5381
5382       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5383       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5384       SmallVector<int, 8> MaskVec;
5385       for (unsigned i = 0; i != NumElems; ++i)
5386         MaskVec.push_back(i == Idx ? 0 : 1);
5387       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5388     }
5389   }
5390
5391   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5392   if (Values.size() == 1) {
5393     if (EVTBits == 32) {
5394       // Instead of a shuffle like this:
5395       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5396       // Check if it's possible to issue this instead.
5397       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5398       unsigned Idx = CountTrailingZeros_32(NonZeros);
5399       SDValue Item = Op.getOperand(Idx);
5400       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5401         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5402     }
5403     return SDValue();
5404   }
5405
5406   // A vector full of immediates; various special cases are already
5407   // handled, so this is best done with a single constant-pool load.
5408   if (IsAllConstants)
5409     return SDValue();
5410
5411   // For AVX-length vectors, build the individual 128-bit pieces and use
5412   // shuffles to put them in place.
5413   if (VT.is256BitVector()) {
5414     SmallVector<SDValue, 32> V;
5415     for (unsigned i = 0; i != NumElems; ++i)
5416       V.push_back(Op.getOperand(i));
5417
5418     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5419
5420     // Build both the lower and upper subvector.
5421     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5422     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5423                                 NumElems/2);
5424
5425     // Recreate the wider vector with the lower and upper part.
5426     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5427   }
5428
5429   // Let legalizer expand 2-wide build_vectors.
5430   if (EVTBits == 64) {
5431     if (NumNonZero == 1) {
5432       // One half is zero or undef.
5433       unsigned Idx = CountTrailingZeros_32(NonZeros);
5434       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5435                                  Op.getOperand(Idx));
5436       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5437     }
5438     return SDValue();
5439   }
5440
5441   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5442   if (EVTBits == 8 && NumElems == 16) {
5443     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5444                                         Subtarget, *this);
5445     if (V.getNode()) return V;
5446   }
5447
5448   if (EVTBits == 16 && NumElems == 8) {
5449     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5450                                       Subtarget, *this);
5451     if (V.getNode()) return V;
5452   }
5453
5454   // If element VT is == 32 bits, turn it into a number of shuffles.
5455   SmallVector<SDValue, 8> V(NumElems);
5456   if (NumElems == 4 && NumZero > 0) {
5457     for (unsigned i = 0; i < 4; ++i) {
5458       bool isZero = !(NonZeros & (1 << i));
5459       if (isZero)
5460         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5461       else
5462         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5463     }
5464
5465     for (unsigned i = 0; i < 2; ++i) {
5466       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5467         default: break;
5468         case 0:
5469           V[i] = V[i*2];  // Must be a zero vector.
5470           break;
5471         case 1:
5472           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5473           break;
5474         case 2:
5475           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5476           break;
5477         case 3:
5478           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5479           break;
5480       }
5481     }
5482
5483     bool Reverse1 = (NonZeros & 0x3) == 2;
5484     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5485     int MaskVec[] = {
5486       Reverse1 ? 1 : 0,
5487       Reverse1 ? 0 : 1,
5488       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5489       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5490     };
5491     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5492   }
5493
5494   if (Values.size() > 1 && VT.is128BitVector()) {
5495     // Check for a build vector of consecutive loads.
5496     for (unsigned i = 0; i < NumElems; ++i)
5497       V[i] = Op.getOperand(i);
5498
5499     // Check for elements which are consecutive loads.
5500     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5501     if (LD.getNode())
5502       return LD;
5503
5504     // For SSE 4.1, use insertps to put the high elements into the low element.
5505     if (getSubtarget()->hasSSE41()) {
5506       SDValue Result;
5507       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5508         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5509       else
5510         Result = DAG.getUNDEF(VT);
5511
5512       for (unsigned i = 1; i < NumElems; ++i) {
5513         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5514         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5515                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5516       }
5517       return Result;
5518     }
5519
5520     // Otherwise, expand into a number of unpckl*, start by extending each of
5521     // our (non-undef) elements to the full vector width with the element in the
5522     // bottom slot of the vector (which generates no code for SSE).
5523     for (unsigned i = 0; i < NumElems; ++i) {
5524       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5525         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5526       else
5527         V[i] = DAG.getUNDEF(VT);
5528     }
5529
5530     // Next, we iteratively mix elements, e.g. for v4f32:
5531     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5532     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5533     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5534     unsigned EltStride = NumElems >> 1;
5535     while (EltStride != 0) {
5536       for (unsigned i = 0; i < EltStride; ++i) {
5537         // If V[i+EltStride] is undef and this is the first round of mixing,
5538         // then it is safe to just drop this shuffle: V[i] is already in the
5539         // right place, the one element (since it's the first round) being
5540         // inserted as undef can be dropped.  This isn't safe for successive
5541         // rounds because they will permute elements within both vectors.
5542         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5543             EltStride == NumElems/2)
5544           continue;
5545
5546         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5547       }
5548       EltStride >>= 1;
5549     }
5550     return V[0];
5551   }
5552   return SDValue();
5553 }
5554
5555 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5556 // to create 256-bit vectors from two other 128-bit ones.
5557 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5558   DebugLoc dl = Op.getDebugLoc();
5559   EVT ResVT = Op.getValueType();
5560
5561   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5562
5563   SDValue V1 = Op.getOperand(0);
5564   SDValue V2 = Op.getOperand(1);
5565   unsigned NumElems = ResVT.getVectorNumElements();
5566
5567   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5568 }
5569
5570 SDValue
5571 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5572   assert(Op.getNumOperands() == 2);
5573
5574   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5575   // from two other 128-bit ones.
5576   return LowerAVXCONCAT_VECTORS(Op, DAG);
5577 }
5578
5579 // Try to lower a shuffle node into a simple blend instruction.
5580 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5581                                           const X86Subtarget *Subtarget,
5582                                           SelectionDAG &DAG) {
5583   SDValue V1 = SVOp->getOperand(0);
5584   SDValue V2 = SVOp->getOperand(1);
5585   DebugLoc dl = SVOp->getDebugLoc();
5586   MVT VT = SVOp->getValueType(0).getSimpleVT();
5587   unsigned NumElems = VT.getVectorNumElements();
5588
5589   if (!Subtarget->hasSSE41())
5590     return SDValue();
5591
5592   unsigned ISDNo = 0;
5593   MVT OpTy;
5594
5595   switch (VT.SimpleTy) {
5596   default: return SDValue();
5597   case MVT::v8i16:
5598     ISDNo = X86ISD::BLENDPW;
5599     OpTy = MVT::v8i16;
5600     break;
5601   case MVT::v4i32:
5602   case MVT::v4f32:
5603     ISDNo = X86ISD::BLENDPS;
5604     OpTy = MVT::v4f32;
5605     break;
5606   case MVT::v2i64:
5607   case MVT::v2f64:
5608     ISDNo = X86ISD::BLENDPD;
5609     OpTy = MVT::v2f64;
5610     break;
5611   case MVT::v8i32:
5612   case MVT::v8f32:
5613     if (!Subtarget->hasAVX())
5614       return SDValue();
5615     ISDNo = X86ISD::BLENDPS;
5616     OpTy = MVT::v8f32;
5617     break;
5618   case MVT::v4i64:
5619   case MVT::v4f64:
5620     if (!Subtarget->hasAVX())
5621       return SDValue();
5622     ISDNo = X86ISD::BLENDPD;
5623     OpTy = MVT::v4f64;
5624     break;
5625   }
5626   assert(ISDNo && "Invalid Op Number");
5627
5628   unsigned MaskVals = 0;
5629
5630   for (unsigned i = 0; i != NumElems; ++i) {
5631     int EltIdx = SVOp->getMaskElt(i);
5632     if (EltIdx == (int)i || EltIdx < 0)
5633       MaskVals |= (1<<i);
5634     else if (EltIdx == (int)(i + NumElems))
5635       continue; // Bit is set to zero;
5636     else
5637       return SDValue();
5638   }
5639
5640   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5641   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5642   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5643                              DAG.getConstant(MaskVals, MVT::i32));
5644   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5645 }
5646
5647 // v8i16 shuffles - Prefer shuffles in the following order:
5648 // 1. [all]   pshuflw, pshufhw, optional move
5649 // 2. [ssse3] 1 x pshufb
5650 // 3. [ssse3] 2 x pshufb + 1 x por
5651 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5652 SDValue
5653 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5654                                             SelectionDAG &DAG) const {
5655   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5656   SDValue V1 = SVOp->getOperand(0);
5657   SDValue V2 = SVOp->getOperand(1);
5658   DebugLoc dl = SVOp->getDebugLoc();
5659   SmallVector<int, 8> MaskVals;
5660
5661   // Determine if more than 1 of the words in each of the low and high quadwords
5662   // of the result come from the same quadword of one of the two inputs.  Undef
5663   // mask values count as coming from any quadword, for better codegen.
5664   unsigned LoQuad[] = { 0, 0, 0, 0 };
5665   unsigned HiQuad[] = { 0, 0, 0, 0 };
5666   std::bitset<4> InputQuads;
5667   for (unsigned i = 0; i < 8; ++i) {
5668     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5669     int EltIdx = SVOp->getMaskElt(i);
5670     MaskVals.push_back(EltIdx);
5671     if (EltIdx < 0) {
5672       ++Quad[0];
5673       ++Quad[1];
5674       ++Quad[2];
5675       ++Quad[3];
5676       continue;
5677     }
5678     ++Quad[EltIdx / 4];
5679     InputQuads.set(EltIdx / 4);
5680   }
5681
5682   int BestLoQuad = -1;
5683   unsigned MaxQuad = 1;
5684   for (unsigned i = 0; i < 4; ++i) {
5685     if (LoQuad[i] > MaxQuad) {
5686       BestLoQuad = i;
5687       MaxQuad = LoQuad[i];
5688     }
5689   }
5690
5691   int BestHiQuad = -1;
5692   MaxQuad = 1;
5693   for (unsigned i = 0; i < 4; ++i) {
5694     if (HiQuad[i] > MaxQuad) {
5695       BestHiQuad = i;
5696       MaxQuad = HiQuad[i];
5697     }
5698   }
5699
5700   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5701   // of the two input vectors, shuffle them into one input vector so only a
5702   // single pshufb instruction is necessary. If There are more than 2 input
5703   // quads, disable the next transformation since it does not help SSSE3.
5704   bool V1Used = InputQuads[0] || InputQuads[1];
5705   bool V2Used = InputQuads[2] || InputQuads[3];
5706   if (Subtarget->hasSSSE3()) {
5707     if (InputQuads.count() == 2 && V1Used && V2Used) {
5708       BestLoQuad = InputQuads[0] ? 0 : 1;
5709       BestHiQuad = InputQuads[2] ? 2 : 3;
5710     }
5711     if (InputQuads.count() > 2) {
5712       BestLoQuad = -1;
5713       BestHiQuad = -1;
5714     }
5715   }
5716
5717   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5718   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5719   // words from all 4 input quadwords.
5720   SDValue NewV;
5721   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5722     int MaskV[] = {
5723       BestLoQuad < 0 ? 0 : BestLoQuad,
5724       BestHiQuad < 0 ? 1 : BestHiQuad
5725     };
5726     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5727                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5728                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5729     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5730
5731     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5732     // source words for the shuffle, to aid later transformations.
5733     bool AllWordsInNewV = true;
5734     bool InOrder[2] = { true, true };
5735     for (unsigned i = 0; i != 8; ++i) {
5736       int idx = MaskVals[i];
5737       if (idx != (int)i)
5738         InOrder[i/4] = false;
5739       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5740         continue;
5741       AllWordsInNewV = false;
5742       break;
5743     }
5744
5745     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5746     if (AllWordsInNewV) {
5747       for (int i = 0; i != 8; ++i) {
5748         int idx = MaskVals[i];
5749         if (idx < 0)
5750           continue;
5751         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5752         if ((idx != i) && idx < 4)
5753           pshufhw = false;
5754         if ((idx != i) && idx > 3)
5755           pshuflw = false;
5756       }
5757       V1 = NewV;
5758       V2Used = false;
5759       BestLoQuad = 0;
5760       BestHiQuad = 1;
5761     }
5762
5763     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5764     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5765     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5766       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5767       unsigned TargetMask = 0;
5768       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5769                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5770       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5771       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5772                              getShufflePSHUFLWImmediate(SVOp);
5773       V1 = NewV.getOperand(0);
5774       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5775     }
5776   }
5777
5778   // If we have SSSE3, and all words of the result are from 1 input vector,
5779   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5780   // is present, fall back to case 4.
5781   if (Subtarget->hasSSSE3()) {
5782     SmallVector<SDValue,16> pshufbMask;
5783
5784     // If we have elements from both input vectors, set the high bit of the
5785     // shuffle mask element to zero out elements that come from V2 in the V1
5786     // mask, and elements that come from V1 in the V2 mask, so that the two
5787     // results can be OR'd together.
5788     bool TwoInputs = V1Used && V2Used;
5789     for (unsigned i = 0; i != 8; ++i) {
5790       int EltIdx = MaskVals[i] * 2;
5791       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5792       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5793       pshufbMask.push_back(DAG.getConstant(Idx0,   MVT::i8));
5794       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5795     }
5796     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5797     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5798                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5799                                  MVT::v16i8, &pshufbMask[0], 16));
5800     if (!TwoInputs)
5801       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5802
5803     // Calculate the shuffle mask for the second input, shuffle it, and
5804     // OR it with the first shuffled input.
5805     pshufbMask.clear();
5806     for (unsigned i = 0; i != 8; ++i) {
5807       int EltIdx = MaskVals[i] * 2;
5808       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5809       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5810       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5811       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5812     }
5813     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5814     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5815                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5816                                  MVT::v16i8, &pshufbMask[0], 16));
5817     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5818     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5819   }
5820
5821   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5822   // and update MaskVals with new element order.
5823   std::bitset<8> InOrder;
5824   if (BestLoQuad >= 0) {
5825     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5826     for (int i = 0; i != 4; ++i) {
5827       int idx = MaskVals[i];
5828       if (idx < 0) {
5829         InOrder.set(i);
5830       } else if ((idx / 4) == BestLoQuad) {
5831         MaskV[i] = idx & 3;
5832         InOrder.set(i);
5833       }
5834     }
5835     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5836                                 &MaskV[0]);
5837
5838     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5839       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5840       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5841                                   NewV.getOperand(0),
5842                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5843     }
5844   }
5845
5846   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5847   // and update MaskVals with the new element order.
5848   if (BestHiQuad >= 0) {
5849     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5850     for (unsigned i = 4; i != 8; ++i) {
5851       int idx = MaskVals[i];
5852       if (idx < 0) {
5853         InOrder.set(i);
5854       } else if ((idx / 4) == BestHiQuad) {
5855         MaskV[i] = (idx & 3) + 4;
5856         InOrder.set(i);
5857       }
5858     }
5859     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5860                                 &MaskV[0]);
5861
5862     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5863       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5864       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5865                                   NewV.getOperand(0),
5866                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5867     }
5868   }
5869
5870   // In case BestHi & BestLo were both -1, which means each quadword has a word
5871   // from each of the four input quadwords, calculate the InOrder bitvector now
5872   // before falling through to the insert/extract cleanup.
5873   if (BestLoQuad == -1 && BestHiQuad == -1) {
5874     NewV = V1;
5875     for (int i = 0; i != 8; ++i)
5876       if (MaskVals[i] < 0 || MaskVals[i] == i)
5877         InOrder.set(i);
5878   }
5879
5880   // The other elements are put in the right place using pextrw and pinsrw.
5881   for (unsigned i = 0; i != 8; ++i) {
5882     if (InOrder[i])
5883       continue;
5884     int EltIdx = MaskVals[i];
5885     if (EltIdx < 0)
5886       continue;
5887     SDValue ExtOp = (EltIdx < 8) ?
5888       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5889                   DAG.getIntPtrConstant(EltIdx)) :
5890       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5891                   DAG.getIntPtrConstant(EltIdx - 8));
5892     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5893                        DAG.getIntPtrConstant(i));
5894   }
5895   return NewV;
5896 }
5897
5898 // v16i8 shuffles - Prefer shuffles in the following order:
5899 // 1. [ssse3] 1 x pshufb
5900 // 2. [ssse3] 2 x pshufb + 1 x por
5901 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5902 static
5903 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5904                                  SelectionDAG &DAG,
5905                                  const X86TargetLowering &TLI) {
5906   SDValue V1 = SVOp->getOperand(0);
5907   SDValue V2 = SVOp->getOperand(1);
5908   DebugLoc dl = SVOp->getDebugLoc();
5909   ArrayRef<int> MaskVals = SVOp->getMask();
5910
5911   // If we have SSSE3, case 1 is generated when all result bytes come from
5912   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5913   // present, fall back to case 3.
5914
5915   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5916   if (TLI.getSubtarget()->hasSSSE3()) {
5917     SmallVector<SDValue,16> pshufbMask;
5918
5919     // If all result elements are from one input vector, then only translate
5920     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5921     //
5922     // Otherwise, we have elements from both input vectors, and must zero out
5923     // elements that come from V2 in the first mask, and V1 in the second mask
5924     // so that we can OR them together.
5925     for (unsigned i = 0; i != 16; ++i) {
5926       int EltIdx = MaskVals[i];
5927       if (EltIdx < 0 || EltIdx >= 16)
5928         EltIdx = 0x80;
5929       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5930     }
5931     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5932                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5933                                  MVT::v16i8, &pshufbMask[0], 16));
5934
5935     // As PSHUFB will zero elements with negative indices, it's safe to ignore
5936     // the 2nd operand if it's undefined or zero.
5937     if (V2.getOpcode() == ISD::UNDEF ||
5938         ISD::isBuildVectorAllZeros(V2.getNode()))
5939       return V1;
5940
5941     // Calculate the shuffle mask for the second input, shuffle it, and
5942     // OR it with the first shuffled input.
5943     pshufbMask.clear();
5944     for (unsigned i = 0; i != 16; ++i) {
5945       int EltIdx = MaskVals[i];
5946       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5947       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5948     }
5949     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5950                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5951                                  MVT::v16i8, &pshufbMask[0], 16));
5952     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5953   }
5954
5955   // No SSSE3 - Calculate in place words and then fix all out of place words
5956   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5957   // the 16 different words that comprise the two doublequadword input vectors.
5958   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5959   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5960   SDValue NewV = V1;
5961   for (int i = 0; i != 8; ++i) {
5962     int Elt0 = MaskVals[i*2];
5963     int Elt1 = MaskVals[i*2+1];
5964
5965     // This word of the result is all undef, skip it.
5966     if (Elt0 < 0 && Elt1 < 0)
5967       continue;
5968
5969     // This word of the result is already in the correct place, skip it.
5970     if ((Elt0 == i*2) && (Elt1 == i*2+1))
5971       continue;
5972
5973     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5974     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5975     SDValue InsElt;
5976
5977     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5978     // using a single extract together, load it and store it.
5979     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5980       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5981                            DAG.getIntPtrConstant(Elt1 / 2));
5982       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5983                         DAG.getIntPtrConstant(i));
5984       continue;
5985     }
5986
5987     // If Elt1 is defined, extract it from the appropriate source.  If the
5988     // source byte is not also odd, shift the extracted word left 8 bits
5989     // otherwise clear the bottom 8 bits if we need to do an or.
5990     if (Elt1 >= 0) {
5991       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5992                            DAG.getIntPtrConstant(Elt1 / 2));
5993       if ((Elt1 & 1) == 0)
5994         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5995                              DAG.getConstant(8,
5996                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5997       else if (Elt0 >= 0)
5998         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5999                              DAG.getConstant(0xFF00, MVT::i16));
6000     }
6001     // If Elt0 is defined, extract it from the appropriate source.  If the
6002     // source byte is not also even, shift the extracted word right 8 bits. If
6003     // Elt1 was also defined, OR the extracted values together before
6004     // inserting them in the result.
6005     if (Elt0 >= 0) {
6006       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6007                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6008       if ((Elt0 & 1) != 0)
6009         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6010                               DAG.getConstant(8,
6011                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6012       else if (Elt1 >= 0)
6013         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6014                              DAG.getConstant(0x00FF, MVT::i16));
6015       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6016                          : InsElt0;
6017     }
6018     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6019                        DAG.getIntPtrConstant(i));
6020   }
6021   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6022 }
6023
6024 // v32i8 shuffles - Translate to VPSHUFB if possible.
6025 static
6026 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6027                                  SelectionDAG &DAG,
6028                                  const X86TargetLowering &TLI) {
6029   EVT VT = SVOp->getValueType(0);
6030   SDValue V1 = SVOp->getOperand(0);
6031   SDValue V2 = SVOp->getOperand(1);
6032   DebugLoc dl = SVOp->getDebugLoc();
6033   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6034
6035   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6036   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6037   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6038
6039   // VPSHUFB may be generated if 
6040   // (1) one of input vector is undefined or zeroinitializer.
6041   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6042   // And (2) the mask indexes don't cross the 128-bit lane.
6043   if (VT != MVT::v32i8 || !TLI.getSubtarget()->hasAVX2() ||
6044       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6045     return SDValue();
6046
6047   if (V1IsAllZero && !V2IsAllZero) {
6048     CommuteVectorShuffleMask(MaskVals, 32);
6049     V1 = V2;
6050   }
6051   SmallVector<SDValue, 32> pshufbMask;
6052   for (unsigned i = 0; i != 32; i++) {
6053     int EltIdx = MaskVals[i];
6054     if (EltIdx < 0 || EltIdx >= 32)
6055       EltIdx = 0x80;
6056     else {
6057       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6058         // Cross lane is not allowed.
6059         return SDValue();
6060       EltIdx &= 0xf;
6061     }
6062     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6063   }
6064   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6065                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6066                                   MVT::v32i8, &pshufbMask[0], 32));
6067 }
6068
6069 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6070 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6071 /// done when every pair / quad of shuffle mask elements point to elements in
6072 /// the right sequence. e.g.
6073 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6074 static
6075 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6076                                  SelectionDAG &DAG, DebugLoc dl) {
6077   MVT VT = SVOp->getValueType(0).getSimpleVT();
6078   unsigned NumElems = VT.getVectorNumElements();
6079   MVT NewVT;
6080   unsigned Scale;
6081   switch (VT.SimpleTy) {
6082   default: llvm_unreachable("Unexpected!");
6083   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6084   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6085   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6086   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6087   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6088   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6089   }
6090
6091   SmallVector<int, 8> MaskVec;
6092   for (unsigned i = 0; i != NumElems; i += Scale) {
6093     int StartIdx = -1;
6094     for (unsigned j = 0; j != Scale; ++j) {
6095       int EltIdx = SVOp->getMaskElt(i+j);
6096       if (EltIdx < 0)
6097         continue;
6098       if (StartIdx < 0)
6099         StartIdx = (EltIdx / Scale);
6100       if (EltIdx != (int)(StartIdx*Scale + j))
6101         return SDValue();
6102     }
6103     MaskVec.push_back(StartIdx);
6104   }
6105
6106   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6107   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6108   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6109 }
6110
6111 /// getVZextMovL - Return a zero-extending vector move low node.
6112 ///
6113 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6114                             SDValue SrcOp, SelectionDAG &DAG,
6115                             const X86Subtarget *Subtarget, DebugLoc dl) {
6116   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6117     LoadSDNode *LD = NULL;
6118     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6119       LD = dyn_cast<LoadSDNode>(SrcOp);
6120     if (!LD) {
6121       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6122       // instead.
6123       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6124       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6125           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6126           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6127           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6128         // PR2108
6129         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6130         return DAG.getNode(ISD::BITCAST, dl, VT,
6131                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6132                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6133                                                    OpVT,
6134                                                    SrcOp.getOperand(0)
6135                                                           .getOperand(0))));
6136       }
6137     }
6138   }
6139
6140   return DAG.getNode(ISD::BITCAST, dl, VT,
6141                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6142                                  DAG.getNode(ISD::BITCAST, dl,
6143                                              OpVT, SrcOp)));
6144 }
6145
6146 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6147 /// which could not be matched by any known target speficic shuffle
6148 static SDValue
6149 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6150
6151   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6152   if (NewOp.getNode())
6153     return NewOp;
6154
6155   EVT VT = SVOp->getValueType(0);
6156
6157   unsigned NumElems = VT.getVectorNumElements();
6158   unsigned NumLaneElems = NumElems / 2;
6159
6160   DebugLoc dl = SVOp->getDebugLoc();
6161   MVT EltVT = VT.getVectorElementType().getSimpleVT();
6162   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6163   SDValue Output[2];
6164
6165   SmallVector<int, 16> Mask;
6166   for (unsigned l = 0; l < 2; ++l) {
6167     // Build a shuffle mask for the output, discovering on the fly which
6168     // input vectors to use as shuffle operands (recorded in InputUsed).
6169     // If building a suitable shuffle vector proves too hard, then bail
6170     // out with UseBuildVector set.
6171     bool UseBuildVector = false;
6172     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6173     unsigned LaneStart = l * NumLaneElems;
6174     for (unsigned i = 0; i != NumLaneElems; ++i) {
6175       // The mask element.  This indexes into the input.
6176       int Idx = SVOp->getMaskElt(i+LaneStart);
6177       if (Idx < 0) {
6178         // the mask element does not index into any input vector.
6179         Mask.push_back(-1);
6180         continue;
6181       }
6182
6183       // The input vector this mask element indexes into.
6184       int Input = Idx / NumLaneElems;
6185
6186       // Turn the index into an offset from the start of the input vector.
6187       Idx -= Input * NumLaneElems;
6188
6189       // Find or create a shuffle vector operand to hold this input.
6190       unsigned OpNo;
6191       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6192         if (InputUsed[OpNo] == Input)
6193           // This input vector is already an operand.
6194           break;
6195         if (InputUsed[OpNo] < 0) {
6196           // Create a new operand for this input vector.
6197           InputUsed[OpNo] = Input;
6198           break;
6199         }
6200       }
6201
6202       if (OpNo >= array_lengthof(InputUsed)) {
6203         // More than two input vectors used!  Give up on trying to create a
6204         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6205         UseBuildVector = true;
6206         break;
6207       }
6208
6209       // Add the mask index for the new shuffle vector.
6210       Mask.push_back(Idx + OpNo * NumLaneElems);
6211     }
6212
6213     if (UseBuildVector) {
6214       SmallVector<SDValue, 16> SVOps;
6215       for (unsigned i = 0; i != NumLaneElems; ++i) {
6216         // The mask element.  This indexes into the input.
6217         int Idx = SVOp->getMaskElt(i+LaneStart);
6218         if (Idx < 0) {
6219           SVOps.push_back(DAG.getUNDEF(EltVT));
6220           continue;
6221         }
6222
6223         // The input vector this mask element indexes into.
6224         int Input = Idx / NumElems;
6225
6226         // Turn the index into an offset from the start of the input vector.
6227         Idx -= Input * NumElems;
6228
6229         // Extract the vector element by hand.
6230         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6231                                     SVOp->getOperand(Input),
6232                                     DAG.getIntPtrConstant(Idx)));
6233       }
6234
6235       // Construct the output using a BUILD_VECTOR.
6236       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6237                               SVOps.size());
6238     } else if (InputUsed[0] < 0) {
6239       // No input vectors were used! The result is undefined.
6240       Output[l] = DAG.getUNDEF(NVT);
6241     } else {
6242       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6243                                         (InputUsed[0] % 2) * NumLaneElems,
6244                                         DAG, dl);
6245       // If only one input was used, use an undefined vector for the other.
6246       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6247         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6248                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6249       // At least one input vector was used. Create a new shuffle vector.
6250       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6251     }
6252
6253     Mask.clear();
6254   }
6255
6256   // Concatenate the result back
6257   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6258 }
6259
6260 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6261 /// 4 elements, and match them with several different shuffle types.
6262 static SDValue
6263 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6264   SDValue V1 = SVOp->getOperand(0);
6265   SDValue V2 = SVOp->getOperand(1);
6266   DebugLoc dl = SVOp->getDebugLoc();
6267   EVT VT = SVOp->getValueType(0);
6268
6269   assert(VT.is128BitVector() && "Unsupported vector size");
6270
6271   std::pair<int, int> Locs[4];
6272   int Mask1[] = { -1, -1, -1, -1 };
6273   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6274
6275   unsigned NumHi = 0;
6276   unsigned NumLo = 0;
6277   for (unsigned i = 0; i != 4; ++i) {
6278     int Idx = PermMask[i];
6279     if (Idx < 0) {
6280       Locs[i] = std::make_pair(-1, -1);
6281     } else {
6282       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6283       if (Idx < 4) {
6284         Locs[i] = std::make_pair(0, NumLo);
6285         Mask1[NumLo] = Idx;
6286         NumLo++;
6287       } else {
6288         Locs[i] = std::make_pair(1, NumHi);
6289         if (2+NumHi < 4)
6290           Mask1[2+NumHi] = Idx;
6291         NumHi++;
6292       }
6293     }
6294   }
6295
6296   if (NumLo <= 2 && NumHi <= 2) {
6297     // If no more than two elements come from either vector. This can be
6298     // implemented with two shuffles. First shuffle gather the elements.
6299     // The second shuffle, which takes the first shuffle as both of its
6300     // vector operands, put the elements into the right order.
6301     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6302
6303     int Mask2[] = { -1, -1, -1, -1 };
6304
6305     for (unsigned i = 0; i != 4; ++i)
6306       if (Locs[i].first != -1) {
6307         unsigned Idx = (i < 2) ? 0 : 4;
6308         Idx += Locs[i].first * 2 + Locs[i].second;
6309         Mask2[i] = Idx;
6310       }
6311
6312     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6313   }
6314
6315   if (NumLo == 3 || NumHi == 3) {
6316     // Otherwise, we must have three elements from one vector, call it X, and
6317     // one element from the other, call it Y.  First, use a shufps to build an
6318     // intermediate vector with the one element from Y and the element from X
6319     // that will be in the same half in the final destination (the indexes don't
6320     // matter). Then, use a shufps to build the final vector, taking the half
6321     // containing the element from Y from the intermediate, and the other half
6322     // from X.
6323     if (NumHi == 3) {
6324       // Normalize it so the 3 elements come from V1.
6325       CommuteVectorShuffleMask(PermMask, 4);
6326       std::swap(V1, V2);
6327     }
6328
6329     // Find the element from V2.
6330     unsigned HiIndex;
6331     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6332       int Val = PermMask[HiIndex];
6333       if (Val < 0)
6334         continue;
6335       if (Val >= 4)
6336         break;
6337     }
6338
6339     Mask1[0] = PermMask[HiIndex];
6340     Mask1[1] = -1;
6341     Mask1[2] = PermMask[HiIndex^1];
6342     Mask1[3] = -1;
6343     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6344
6345     if (HiIndex >= 2) {
6346       Mask1[0] = PermMask[0];
6347       Mask1[1] = PermMask[1];
6348       Mask1[2] = HiIndex & 1 ? 6 : 4;
6349       Mask1[3] = HiIndex & 1 ? 4 : 6;
6350       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6351     }
6352
6353     Mask1[0] = HiIndex & 1 ? 2 : 0;
6354     Mask1[1] = HiIndex & 1 ? 0 : 2;
6355     Mask1[2] = PermMask[2];
6356     Mask1[3] = PermMask[3];
6357     if (Mask1[2] >= 0)
6358       Mask1[2] += 4;
6359     if (Mask1[3] >= 0)
6360       Mask1[3] += 4;
6361     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6362   }
6363
6364   // Break it into (shuffle shuffle_hi, shuffle_lo).
6365   int LoMask[] = { -1, -1, -1, -1 };
6366   int HiMask[] = { -1, -1, -1, -1 };
6367
6368   int *MaskPtr = LoMask;
6369   unsigned MaskIdx = 0;
6370   unsigned LoIdx = 0;
6371   unsigned HiIdx = 2;
6372   for (unsigned i = 0; i != 4; ++i) {
6373     if (i == 2) {
6374       MaskPtr = HiMask;
6375       MaskIdx = 1;
6376       LoIdx = 0;
6377       HiIdx = 2;
6378     }
6379     int Idx = PermMask[i];
6380     if (Idx < 0) {
6381       Locs[i] = std::make_pair(-1, -1);
6382     } else if (Idx < 4) {
6383       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6384       MaskPtr[LoIdx] = Idx;
6385       LoIdx++;
6386     } else {
6387       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6388       MaskPtr[HiIdx] = Idx;
6389       HiIdx++;
6390     }
6391   }
6392
6393   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6394   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6395   int MaskOps[] = { -1, -1, -1, -1 };
6396   for (unsigned i = 0; i != 4; ++i)
6397     if (Locs[i].first != -1)
6398       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6399   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6400 }
6401
6402 static bool MayFoldVectorLoad(SDValue V) {
6403   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6404     V = V.getOperand(0);
6405   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6406     V = V.getOperand(0);
6407   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6408       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6409     // BUILD_VECTOR (load), undef
6410     V = V.getOperand(0);
6411   if (MayFoldLoad(V))
6412     return true;
6413   return false;
6414 }
6415
6416 // FIXME: the version above should always be used. Since there's
6417 // a bug where several vector shuffles can't be folded because the
6418 // DAG is not updated during lowering and a node claims to have two
6419 // uses while it only has one, use this version, and let isel match
6420 // another instruction if the load really happens to have more than
6421 // one use. Remove this version after this bug get fixed.
6422 // rdar://8434668, PR8156
6423 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6424   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6425     V = V.getOperand(0);
6426   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6427     V = V.getOperand(0);
6428   if (ISD::isNormalLoad(V.getNode()))
6429     return true;
6430   return false;
6431 }
6432
6433 static
6434 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6435   EVT VT = Op.getValueType();
6436
6437   // Canonizalize to v2f64.
6438   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6439   return DAG.getNode(ISD::BITCAST, dl, VT,
6440                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6441                                           V1, DAG));
6442 }
6443
6444 static
6445 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6446                         bool HasSSE2) {
6447   SDValue V1 = Op.getOperand(0);
6448   SDValue V2 = Op.getOperand(1);
6449   EVT VT = Op.getValueType();
6450
6451   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6452
6453   if (HasSSE2 && VT == MVT::v2f64)
6454     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6455
6456   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6457   return DAG.getNode(ISD::BITCAST, dl, VT,
6458                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6459                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6460                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6461 }
6462
6463 static
6464 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6465   SDValue V1 = Op.getOperand(0);
6466   SDValue V2 = Op.getOperand(1);
6467   EVT VT = Op.getValueType();
6468
6469   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6470          "unsupported shuffle type");
6471
6472   if (V2.getOpcode() == ISD::UNDEF)
6473     V2 = V1;
6474
6475   // v4i32 or v4f32
6476   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6477 }
6478
6479 static
6480 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6481   SDValue V1 = Op.getOperand(0);
6482   SDValue V2 = Op.getOperand(1);
6483   EVT VT = Op.getValueType();
6484   unsigned NumElems = VT.getVectorNumElements();
6485
6486   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6487   // operand of these instructions is only memory, so check if there's a
6488   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6489   // same masks.
6490   bool CanFoldLoad = false;
6491
6492   // Trivial case, when V2 comes from a load.
6493   if (MayFoldVectorLoad(V2))
6494     CanFoldLoad = true;
6495
6496   // When V1 is a load, it can be folded later into a store in isel, example:
6497   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6498   //    turns into:
6499   //  (MOVLPSmr addr:$src1, VR128:$src2)
6500   // So, recognize this potential and also use MOVLPS or MOVLPD
6501   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6502     CanFoldLoad = true;
6503
6504   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6505   if (CanFoldLoad) {
6506     if (HasSSE2 && NumElems == 2)
6507       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6508
6509     if (NumElems == 4)
6510       // If we don't care about the second element, proceed to use movss.
6511       if (SVOp->getMaskElt(1) != -1)
6512         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6513   }
6514
6515   // movl and movlp will both match v2i64, but v2i64 is never matched by
6516   // movl earlier because we make it strict to avoid messing with the movlp load
6517   // folding logic (see the code above getMOVLP call). Match it here then,
6518   // this is horrible, but will stay like this until we move all shuffle
6519   // matching to x86 specific nodes. Note that for the 1st condition all
6520   // types are matched with movsd.
6521   if (HasSSE2) {
6522     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6523     // as to remove this logic from here, as much as possible
6524     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6525       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6526     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6527   }
6528
6529   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6530
6531   // Invert the operand order and use SHUFPS to match it.
6532   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6533                               getShuffleSHUFImmediate(SVOp), DAG);
6534 }
6535
6536 SDValue
6537 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6538   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6539   EVT VT = Op.getValueType();
6540   DebugLoc dl = Op.getDebugLoc();
6541   SDValue V1 = Op.getOperand(0);
6542   SDValue V2 = Op.getOperand(1);
6543
6544   if (isZeroShuffle(SVOp))
6545     return getZeroVector(VT, Subtarget, DAG, dl);
6546
6547   // Handle splat operations
6548   if (SVOp->isSplat()) {
6549     unsigned NumElem = VT.getVectorNumElements();
6550     int Size = VT.getSizeInBits();
6551
6552     // Use vbroadcast whenever the splat comes from a foldable load
6553     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6554     if (Broadcast.getNode())
6555       return Broadcast;
6556
6557     // Handle splats by matching through known shuffle masks
6558     if ((Size == 128 && NumElem <= 4) ||
6559         (Size == 256 && NumElem < 8))
6560       return SDValue();
6561
6562     // All remaning splats are promoted to target supported vector shuffles.
6563     return PromoteSplat(SVOp, DAG);
6564   }
6565
6566   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6567   // do it!
6568   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6569       VT == MVT::v16i16 || VT == MVT::v32i8) {
6570     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6571     if (NewOp.getNode())
6572       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6573   } else if ((VT == MVT::v4i32 ||
6574              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6575     // FIXME: Figure out a cleaner way to do this.
6576     // Try to make use of movq to zero out the top part.
6577     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6578       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6579       if (NewOp.getNode()) {
6580         EVT NewVT = NewOp.getValueType();
6581         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6582                                NewVT, true, false))
6583           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6584                               DAG, Subtarget, dl);
6585       }
6586     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6587       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6588       if (NewOp.getNode()) {
6589         EVT NewVT = NewOp.getValueType();
6590         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6591           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6592                               DAG, Subtarget, dl);
6593       }
6594     }
6595   }
6596   return SDValue();
6597 }
6598
6599 SDValue
6600 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6601   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6602   SDValue V1 = Op.getOperand(0);
6603   SDValue V2 = Op.getOperand(1);
6604   EVT VT = Op.getValueType();
6605   DebugLoc dl = Op.getDebugLoc();
6606   unsigned NumElems = VT.getVectorNumElements();
6607   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6608   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6609   bool V1IsSplat = false;
6610   bool V2IsSplat = false;
6611   bool HasSSE2 = Subtarget->hasSSE2();
6612   bool HasAVX    = Subtarget->hasAVX();
6613   bool HasAVX2   = Subtarget->hasAVX2();
6614   MachineFunction &MF = DAG.getMachineFunction();
6615   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6616
6617   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6618
6619   if (V1IsUndef && V2IsUndef)
6620     return DAG.getUNDEF(VT);
6621
6622   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6623
6624   // Vector shuffle lowering takes 3 steps:
6625   //
6626   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6627   //    narrowing and commutation of operands should be handled.
6628   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6629   //    shuffle nodes.
6630   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6631   //    so the shuffle can be broken into other shuffles and the legalizer can
6632   //    try the lowering again.
6633   //
6634   // The general idea is that no vector_shuffle operation should be left to
6635   // be matched during isel, all of them must be converted to a target specific
6636   // node here.
6637
6638   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6639   // narrowing and commutation of operands should be handled. The actual code
6640   // doesn't include all of those, work in progress...
6641   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6642   if (NewOp.getNode())
6643     return NewOp;
6644
6645   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6646
6647   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6648   // unpckh_undef). Only use pshufd if speed is more important than size.
6649   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6650     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6651   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6652     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6653
6654   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6655       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6656     return getMOVDDup(Op, dl, V1, DAG);
6657
6658   if (isMOVHLPS_v_undef_Mask(M, VT))
6659     return getMOVHighToLow(Op, dl, DAG);
6660
6661   // Use to match splats
6662   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6663       (VT == MVT::v2f64 || VT == MVT::v2i64))
6664     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6665
6666   if (isPSHUFDMask(M, VT)) {
6667     // The actual implementation will match the mask in the if above and then
6668     // during isel it can match several different instructions, not only pshufd
6669     // as its name says, sad but true, emulate the behavior for now...
6670     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6671       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6672
6673     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6674
6675     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6676       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6677
6678     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6679       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6680
6681     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6682                                 TargetMask, DAG);
6683   }
6684
6685   // Check if this can be converted into a logical shift.
6686   bool isLeft = false;
6687   unsigned ShAmt = 0;
6688   SDValue ShVal;
6689   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6690   if (isShift && ShVal.hasOneUse()) {
6691     // If the shifted value has multiple uses, it may be cheaper to use
6692     // v_set0 + movlhps or movhlps, etc.
6693     EVT EltVT = VT.getVectorElementType();
6694     ShAmt *= EltVT.getSizeInBits();
6695     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6696   }
6697
6698   if (isMOVLMask(M, VT)) {
6699     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6700       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6701     if (!isMOVLPMask(M, VT)) {
6702       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6703         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6704
6705       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6706         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6707     }
6708   }
6709
6710   // FIXME: fold these into legal mask.
6711   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6712     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6713
6714   if (isMOVHLPSMask(M, VT))
6715     return getMOVHighToLow(Op, dl, DAG);
6716
6717   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6718     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6719
6720   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6721     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6722
6723   if (isMOVLPMask(M, VT))
6724     return getMOVLP(Op, dl, DAG, HasSSE2);
6725
6726   if (ShouldXformToMOVHLPS(M, VT) ||
6727       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6728     return CommuteVectorShuffle(SVOp, DAG);
6729
6730   if (isShift) {
6731     // No better options. Use a vshldq / vsrldq.
6732     EVT EltVT = VT.getVectorElementType();
6733     ShAmt *= EltVT.getSizeInBits();
6734     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6735   }
6736
6737   bool Commuted = false;
6738   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6739   // 1,1,1,1 -> v8i16 though.
6740   V1IsSplat = isSplatVector(V1.getNode());
6741   V2IsSplat = isSplatVector(V2.getNode());
6742
6743   // Canonicalize the splat or undef, if present, to be on the RHS.
6744   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6745     CommuteVectorShuffleMask(M, NumElems);
6746     std::swap(V1, V2);
6747     std::swap(V1IsSplat, V2IsSplat);
6748     Commuted = true;
6749   }
6750
6751   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6752     // Shuffling low element of v1 into undef, just return v1.
6753     if (V2IsUndef)
6754       return V1;
6755     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6756     // the instruction selector will not match, so get a canonical MOVL with
6757     // swapped operands to undo the commute.
6758     return getMOVL(DAG, dl, VT, V2, V1);
6759   }
6760
6761   if (isUNPCKLMask(M, VT, HasAVX2))
6762     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6763
6764   if (isUNPCKHMask(M, VT, HasAVX2))
6765     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6766
6767   if (V2IsSplat) {
6768     // Normalize mask so all entries that point to V2 points to its first
6769     // element then try to match unpck{h|l} again. If match, return a
6770     // new vector_shuffle with the corrected mask.p
6771     SmallVector<int, 8> NewMask(M.begin(), M.end());
6772     NormalizeMask(NewMask, NumElems);
6773     if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6774       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6775     if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6776       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6777   }
6778
6779   if (Commuted) {
6780     // Commute is back and try unpck* again.
6781     // FIXME: this seems wrong.
6782     CommuteVectorShuffleMask(M, NumElems);
6783     std::swap(V1, V2);
6784     std::swap(V1IsSplat, V2IsSplat);
6785     Commuted = false;
6786
6787     if (isUNPCKLMask(M, VT, HasAVX2))
6788       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6789
6790     if (isUNPCKHMask(M, VT, HasAVX2))
6791       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6792   }
6793
6794   // Normalize the node to match x86 shuffle ops if needed
6795   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6796     return CommuteVectorShuffle(SVOp, DAG);
6797
6798   // The checks below are all present in isShuffleMaskLegal, but they are
6799   // inlined here right now to enable us to directly emit target specific
6800   // nodes, and remove one by one until they don't return Op anymore.
6801
6802   if (isPALIGNRMask(M, VT, Subtarget))
6803     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6804                                 getShufflePALIGNRImmediate(SVOp),
6805                                 DAG);
6806
6807   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6808       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6809     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6810       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6811   }
6812
6813   if (isPSHUFHWMask(M, VT, HasAVX2))
6814     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6815                                 getShufflePSHUFHWImmediate(SVOp),
6816                                 DAG);
6817
6818   if (isPSHUFLWMask(M, VT, HasAVX2))
6819     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6820                                 getShufflePSHUFLWImmediate(SVOp),
6821                                 DAG);
6822
6823   if (isSHUFPMask(M, VT, HasAVX))
6824     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6825                                 getShuffleSHUFImmediate(SVOp), DAG);
6826
6827   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6828     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6829   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6830     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6831
6832   //===--------------------------------------------------------------------===//
6833   // Generate target specific nodes for 128 or 256-bit shuffles only
6834   // supported in the AVX instruction set.
6835   //
6836
6837   // Handle VMOVDDUPY permutations
6838   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6839     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6840
6841   // Handle VPERMILPS/D* permutations
6842   if (isVPERMILPMask(M, VT, HasAVX)) {
6843     if (HasAVX2 && VT == MVT::v8i32)
6844       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6845                                   getShuffleSHUFImmediate(SVOp), DAG);
6846     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6847                                 getShuffleSHUFImmediate(SVOp), DAG);
6848   }
6849
6850   // Handle VPERM2F128/VPERM2I128 permutations
6851   if (isVPERM2X128Mask(M, VT, HasAVX))
6852     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6853                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6854
6855   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6856   if (BlendOp.getNode())
6857     return BlendOp;
6858
6859   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6860     SmallVector<SDValue, 8> permclMask;
6861     for (unsigned i = 0; i != 8; ++i) {
6862       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6863     }
6864     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6865                                &permclMask[0], 8);
6866     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6867     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6868                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6869   }
6870
6871   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6872     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6873                                 getShuffleCLImmediate(SVOp), DAG);
6874
6875
6876   //===--------------------------------------------------------------------===//
6877   // Since no target specific shuffle was selected for this generic one,
6878   // lower it into other known shuffles. FIXME: this isn't true yet, but
6879   // this is the plan.
6880   //
6881
6882   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6883   if (VT == MVT::v8i16) {
6884     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6885     if (NewOp.getNode())
6886       return NewOp;
6887   }
6888
6889   if (VT == MVT::v16i8) {
6890     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6891     if (NewOp.getNode())
6892       return NewOp;
6893   }
6894
6895   if (VT == MVT::v32i8) {
6896     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, DAG, *this);
6897     if (NewOp.getNode())
6898       return NewOp;
6899   }
6900
6901   // Handle all 128-bit wide vectors with 4 elements, and match them with
6902   // several different shuffle types.
6903   if (NumElems == 4 && VT.is128BitVector())
6904     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6905
6906   // Handle general 256-bit shuffles
6907   if (VT.is256BitVector())
6908     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6909
6910   return SDValue();
6911 }
6912
6913 SDValue
6914 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6915                                                 SelectionDAG &DAG) const {
6916   EVT VT = Op.getValueType();
6917   DebugLoc dl = Op.getDebugLoc();
6918
6919   if (!Op.getOperand(0).getValueType().is128BitVector())
6920     return SDValue();
6921
6922   if (VT.getSizeInBits() == 8) {
6923     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6924                                     Op.getOperand(0), Op.getOperand(1));
6925     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6926                                     DAG.getValueType(VT));
6927     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6928   }
6929
6930   if (VT.getSizeInBits() == 16) {
6931     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6932     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6933     if (Idx == 0)
6934       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6935                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6936                                      DAG.getNode(ISD::BITCAST, dl,
6937                                                  MVT::v4i32,
6938                                                  Op.getOperand(0)),
6939                                      Op.getOperand(1)));
6940     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6941                                     Op.getOperand(0), Op.getOperand(1));
6942     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6943                                     DAG.getValueType(VT));
6944     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6945   }
6946
6947   if (VT == MVT::f32) {
6948     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6949     // the result back to FR32 register. It's only worth matching if the
6950     // result has a single use which is a store or a bitcast to i32.  And in
6951     // the case of a store, it's not worth it if the index is a constant 0,
6952     // because a MOVSSmr can be used instead, which is smaller and faster.
6953     if (!Op.hasOneUse())
6954       return SDValue();
6955     SDNode *User = *Op.getNode()->use_begin();
6956     if ((User->getOpcode() != ISD::STORE ||
6957          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6958           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6959         (User->getOpcode() != ISD::BITCAST ||
6960          User->getValueType(0) != MVT::i32))
6961       return SDValue();
6962     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6963                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6964                                               Op.getOperand(0)),
6965                                               Op.getOperand(1));
6966     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6967   }
6968
6969   if (VT == MVT::i32 || VT == MVT::i64) {
6970     // ExtractPS/pextrq works with constant index.
6971     if (isa<ConstantSDNode>(Op.getOperand(1)))
6972       return Op;
6973   }
6974   return SDValue();
6975 }
6976
6977
6978 SDValue
6979 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6980                                            SelectionDAG &DAG) const {
6981   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6982     return SDValue();
6983
6984   SDValue Vec = Op.getOperand(0);
6985   EVT VecVT = Vec.getValueType();
6986
6987   // If this is a 256-bit vector result, first extract the 128-bit vector and
6988   // then extract the element from the 128-bit vector.
6989   if (VecVT.is256BitVector()) {
6990     DebugLoc dl = Op.getNode()->getDebugLoc();
6991     unsigned NumElems = VecVT.getVectorNumElements();
6992     SDValue Idx = Op.getOperand(1);
6993     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6994
6995     // Get the 128-bit vector.
6996     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6997
6998     if (IdxVal >= NumElems/2)
6999       IdxVal -= NumElems/2;
7000     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7001                        DAG.getConstant(IdxVal, MVT::i32));
7002   }
7003
7004   assert(VecVT.is128BitVector() && "Unexpected vector length");
7005
7006   if (Subtarget->hasSSE41()) {
7007     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7008     if (Res.getNode())
7009       return Res;
7010   }
7011
7012   EVT VT = Op.getValueType();
7013   DebugLoc dl = Op.getDebugLoc();
7014   // TODO: handle v16i8.
7015   if (VT.getSizeInBits() == 16) {
7016     SDValue Vec = Op.getOperand(0);
7017     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7018     if (Idx == 0)
7019       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7020                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7021                                      DAG.getNode(ISD::BITCAST, dl,
7022                                                  MVT::v4i32, Vec),
7023                                      Op.getOperand(1)));
7024     // Transform it so it match pextrw which produces a 32-bit result.
7025     EVT EltVT = MVT::i32;
7026     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7027                                     Op.getOperand(0), Op.getOperand(1));
7028     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7029                                     DAG.getValueType(VT));
7030     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7031   }
7032
7033   if (VT.getSizeInBits() == 32) {
7034     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7035     if (Idx == 0)
7036       return Op;
7037
7038     // SHUFPS the element to the lowest double word, then movss.
7039     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7040     EVT VVT = Op.getOperand(0).getValueType();
7041     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7042                                        DAG.getUNDEF(VVT), Mask);
7043     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7044                        DAG.getIntPtrConstant(0));
7045   }
7046
7047   if (VT.getSizeInBits() == 64) {
7048     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7049     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7050     //        to match extract_elt for f64.
7051     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7052     if (Idx == 0)
7053       return Op;
7054
7055     // UNPCKHPD the element to the lowest double word, then movsd.
7056     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7057     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7058     int Mask[2] = { 1, -1 };
7059     EVT VVT = Op.getOperand(0).getValueType();
7060     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7061                                        DAG.getUNDEF(VVT), Mask);
7062     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7063                        DAG.getIntPtrConstant(0));
7064   }
7065
7066   return SDValue();
7067 }
7068
7069 SDValue
7070 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7071                                                SelectionDAG &DAG) const {
7072   EVT VT = Op.getValueType();
7073   EVT EltVT = VT.getVectorElementType();
7074   DebugLoc dl = Op.getDebugLoc();
7075
7076   SDValue N0 = Op.getOperand(0);
7077   SDValue N1 = Op.getOperand(1);
7078   SDValue N2 = Op.getOperand(2);
7079
7080   if (!VT.is128BitVector())
7081     return SDValue();
7082
7083   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7084       isa<ConstantSDNode>(N2)) {
7085     unsigned Opc;
7086     if (VT == MVT::v8i16)
7087       Opc = X86ISD::PINSRW;
7088     else if (VT == MVT::v16i8)
7089       Opc = X86ISD::PINSRB;
7090     else
7091       Opc = X86ISD::PINSRB;
7092
7093     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7094     // argument.
7095     if (N1.getValueType() != MVT::i32)
7096       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7097     if (N2.getValueType() != MVT::i32)
7098       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7099     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7100   }
7101
7102   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7103     // Bits [7:6] of the constant are the source select.  This will always be
7104     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7105     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7106     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7107     // Bits [5:4] of the constant are the destination select.  This is the
7108     //  value of the incoming immediate.
7109     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7110     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7111     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7112     // Create this as a scalar to vector..
7113     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7114     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7115   }
7116
7117   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7118     // PINSR* works with constant index.
7119     return Op;
7120   }
7121   return SDValue();
7122 }
7123
7124 SDValue
7125 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7126   EVT VT = Op.getValueType();
7127   EVT EltVT = VT.getVectorElementType();
7128
7129   DebugLoc dl = Op.getDebugLoc();
7130   SDValue N0 = Op.getOperand(0);
7131   SDValue N1 = Op.getOperand(1);
7132   SDValue N2 = Op.getOperand(2);
7133
7134   // If this is a 256-bit vector result, first extract the 128-bit vector,
7135   // insert the element into the extracted half and then place it back.
7136   if (VT.is256BitVector()) {
7137     if (!isa<ConstantSDNode>(N2))
7138       return SDValue();
7139
7140     // Get the desired 128-bit vector half.
7141     unsigned NumElems = VT.getVectorNumElements();
7142     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7143     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7144
7145     // Insert the element into the desired half.
7146     bool Upper = IdxVal >= NumElems/2;
7147     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7148                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7149
7150     // Insert the changed part back to the 256-bit vector
7151     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7152   }
7153
7154   if (Subtarget->hasSSE41())
7155     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7156
7157   if (EltVT == MVT::i8)
7158     return SDValue();
7159
7160   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7161     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7162     // as its second argument.
7163     if (N1.getValueType() != MVT::i32)
7164       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7165     if (N2.getValueType() != MVT::i32)
7166       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7167     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7168   }
7169   return SDValue();
7170 }
7171
7172 SDValue
7173 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7174   LLVMContext *Context = DAG.getContext();
7175   DebugLoc dl = Op.getDebugLoc();
7176   EVT OpVT = Op.getValueType();
7177
7178   // If this is a 256-bit vector result, first insert into a 128-bit
7179   // vector and then insert into the 256-bit vector.
7180   if (!OpVT.is128BitVector()) {
7181     // Insert into a 128-bit vector.
7182     EVT VT128 = EVT::getVectorVT(*Context,
7183                                  OpVT.getVectorElementType(),
7184                                  OpVT.getVectorNumElements() / 2);
7185
7186     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7187
7188     // Insert the 128-bit vector.
7189     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7190   }
7191
7192   if (OpVT == MVT::v1i64 &&
7193       Op.getOperand(0).getValueType() == MVT::i64)
7194     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7195
7196   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7197   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7198   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7199                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7200 }
7201
7202 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7203 // a simple subregister reference or explicit instructions to grab
7204 // upper bits of a vector.
7205 SDValue
7206 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7207   if (Subtarget->hasAVX()) {
7208     DebugLoc dl = Op.getNode()->getDebugLoc();
7209     SDValue Vec = Op.getNode()->getOperand(0);
7210     SDValue Idx = Op.getNode()->getOperand(1);
7211
7212     if (Op.getNode()->getValueType(0).is128BitVector() &&
7213         Vec.getNode()->getValueType(0).is256BitVector() &&
7214         isa<ConstantSDNode>(Idx)) {
7215       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7216       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7217     }
7218   }
7219   return SDValue();
7220 }
7221
7222 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7223 // simple superregister reference or explicit instructions to insert
7224 // the upper bits of a vector.
7225 SDValue
7226 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7227   if (Subtarget->hasAVX()) {
7228     DebugLoc dl = Op.getNode()->getDebugLoc();
7229     SDValue Vec = Op.getNode()->getOperand(0);
7230     SDValue SubVec = Op.getNode()->getOperand(1);
7231     SDValue Idx = Op.getNode()->getOperand(2);
7232
7233     if (Op.getNode()->getValueType(0).is256BitVector() &&
7234         SubVec.getNode()->getValueType(0).is128BitVector() &&
7235         isa<ConstantSDNode>(Idx)) {
7236       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7237       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7238     }
7239   }
7240   return SDValue();
7241 }
7242
7243 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7244 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7245 // one of the above mentioned nodes. It has to be wrapped because otherwise
7246 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7247 // be used to form addressing mode. These wrapped nodes will be selected
7248 // into MOV32ri.
7249 SDValue
7250 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7251   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7252
7253   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7254   // global base reg.
7255   unsigned char OpFlag = 0;
7256   unsigned WrapperKind = X86ISD::Wrapper;
7257   CodeModel::Model M = getTargetMachine().getCodeModel();
7258
7259   if (Subtarget->isPICStyleRIPRel() &&
7260       (M == CodeModel::Small || M == CodeModel::Kernel))
7261     WrapperKind = X86ISD::WrapperRIP;
7262   else if (Subtarget->isPICStyleGOT())
7263     OpFlag = X86II::MO_GOTOFF;
7264   else if (Subtarget->isPICStyleStubPIC())
7265     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7266
7267   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7268                                              CP->getAlignment(),
7269                                              CP->getOffset(), OpFlag);
7270   DebugLoc DL = CP->getDebugLoc();
7271   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7272   // With PIC, the address is actually $g + Offset.
7273   if (OpFlag) {
7274     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7275                          DAG.getNode(X86ISD::GlobalBaseReg,
7276                                      DebugLoc(), getPointerTy()),
7277                          Result);
7278   }
7279
7280   return Result;
7281 }
7282
7283 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7284   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7285
7286   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7287   // global base reg.
7288   unsigned char OpFlag = 0;
7289   unsigned WrapperKind = X86ISD::Wrapper;
7290   CodeModel::Model M = getTargetMachine().getCodeModel();
7291
7292   if (Subtarget->isPICStyleRIPRel() &&
7293       (M == CodeModel::Small || M == CodeModel::Kernel))
7294     WrapperKind = X86ISD::WrapperRIP;
7295   else if (Subtarget->isPICStyleGOT())
7296     OpFlag = X86II::MO_GOTOFF;
7297   else if (Subtarget->isPICStyleStubPIC())
7298     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7299
7300   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7301                                           OpFlag);
7302   DebugLoc DL = JT->getDebugLoc();
7303   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7304
7305   // With PIC, the address is actually $g + Offset.
7306   if (OpFlag)
7307     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7308                          DAG.getNode(X86ISD::GlobalBaseReg,
7309                                      DebugLoc(), getPointerTy()),
7310                          Result);
7311
7312   return Result;
7313 }
7314
7315 SDValue
7316 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7317   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7318
7319   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7320   // global base reg.
7321   unsigned char OpFlag = 0;
7322   unsigned WrapperKind = X86ISD::Wrapper;
7323   CodeModel::Model M = getTargetMachine().getCodeModel();
7324
7325   if (Subtarget->isPICStyleRIPRel() &&
7326       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7327     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7328       OpFlag = X86II::MO_GOTPCREL;
7329     WrapperKind = X86ISD::WrapperRIP;
7330   } else if (Subtarget->isPICStyleGOT()) {
7331     OpFlag = X86II::MO_GOT;
7332   } else if (Subtarget->isPICStyleStubPIC()) {
7333     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7334   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7335     OpFlag = X86II::MO_DARWIN_NONLAZY;
7336   }
7337
7338   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7339
7340   DebugLoc DL = Op.getDebugLoc();
7341   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7342
7343
7344   // With PIC, the address is actually $g + Offset.
7345   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7346       !Subtarget->is64Bit()) {
7347     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7348                          DAG.getNode(X86ISD::GlobalBaseReg,
7349                                      DebugLoc(), getPointerTy()),
7350                          Result);
7351   }
7352
7353   // For symbols that require a load from a stub to get the address, emit the
7354   // load.
7355   if (isGlobalStubReference(OpFlag))
7356     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7357                          MachinePointerInfo::getGOT(), false, false, false, 0);
7358
7359   return Result;
7360 }
7361
7362 SDValue
7363 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7364   // Create the TargetBlockAddressAddress node.
7365   unsigned char OpFlags =
7366     Subtarget->ClassifyBlockAddressReference();
7367   CodeModel::Model M = getTargetMachine().getCodeModel();
7368   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7369   DebugLoc dl = Op.getDebugLoc();
7370   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7371                                        /*isTarget=*/true, OpFlags);
7372
7373   if (Subtarget->isPICStyleRIPRel() &&
7374       (M == CodeModel::Small || M == CodeModel::Kernel))
7375     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7376   else
7377     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7378
7379   // With PIC, the address is actually $g + Offset.
7380   if (isGlobalRelativeToPICBase(OpFlags)) {
7381     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7382                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7383                          Result);
7384   }
7385
7386   return Result;
7387 }
7388
7389 SDValue
7390 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7391                                       int64_t Offset,
7392                                       SelectionDAG &DAG) const {
7393   // Create the TargetGlobalAddress node, folding in the constant
7394   // offset if it is legal.
7395   unsigned char OpFlags =
7396     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7397   CodeModel::Model M = getTargetMachine().getCodeModel();
7398   SDValue Result;
7399   if (OpFlags == X86II::MO_NO_FLAG &&
7400       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7401     // A direct static reference to a global.
7402     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7403     Offset = 0;
7404   } else {
7405     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7406   }
7407
7408   if (Subtarget->isPICStyleRIPRel() &&
7409       (M == CodeModel::Small || M == CodeModel::Kernel))
7410     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7411   else
7412     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7413
7414   // With PIC, the address is actually $g + Offset.
7415   if (isGlobalRelativeToPICBase(OpFlags)) {
7416     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7417                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7418                          Result);
7419   }
7420
7421   // For globals that require a load from a stub to get the address, emit the
7422   // load.
7423   if (isGlobalStubReference(OpFlags))
7424     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7425                          MachinePointerInfo::getGOT(), false, false, false, 0);
7426
7427   // If there was a non-zero offset that we didn't fold, create an explicit
7428   // addition for it.
7429   if (Offset != 0)
7430     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7431                          DAG.getConstant(Offset, getPointerTy()));
7432
7433   return Result;
7434 }
7435
7436 SDValue
7437 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7438   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7439   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7440   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7441 }
7442
7443 static SDValue
7444 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7445            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7446            unsigned char OperandFlags, bool LocalDynamic = false) {
7447   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7448   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7449   DebugLoc dl = GA->getDebugLoc();
7450   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7451                                            GA->getValueType(0),
7452                                            GA->getOffset(),
7453                                            OperandFlags);
7454
7455   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7456                                            : X86ISD::TLSADDR;
7457
7458   if (InFlag) {
7459     SDValue Ops[] = { Chain,  TGA, *InFlag };
7460     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7461   } else {
7462     SDValue Ops[]  = { Chain, TGA };
7463     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7464   }
7465
7466   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7467   MFI->setAdjustsStack(true);
7468
7469   SDValue Flag = Chain.getValue(1);
7470   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7471 }
7472
7473 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7474 static SDValue
7475 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7476                                 const EVT PtrVT) {
7477   SDValue InFlag;
7478   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7479   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7480                                      DAG.getNode(X86ISD::GlobalBaseReg,
7481                                                  DebugLoc(), PtrVT), InFlag);
7482   InFlag = Chain.getValue(1);
7483
7484   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7485 }
7486
7487 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7488 static SDValue
7489 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7490                                 const EVT PtrVT) {
7491   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7492                     X86::RAX, X86II::MO_TLSGD);
7493 }
7494
7495 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7496                                            SelectionDAG &DAG,
7497                                            const EVT PtrVT,
7498                                            bool is64Bit) {
7499   DebugLoc dl = GA->getDebugLoc();
7500
7501   // Get the start address of the TLS block for this module.
7502   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7503       .getInfo<X86MachineFunctionInfo>();
7504   MFI->incNumLocalDynamicTLSAccesses();
7505
7506   SDValue Base;
7507   if (is64Bit) {
7508     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7509                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7510   } else {
7511     SDValue InFlag;
7512     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7513         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7514     InFlag = Chain.getValue(1);
7515     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7516                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7517   }
7518
7519   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7520   // of Base.
7521
7522   // Build x@dtpoff.
7523   unsigned char OperandFlags = X86II::MO_DTPOFF;
7524   unsigned WrapperKind = X86ISD::Wrapper;
7525   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7526                                            GA->getValueType(0),
7527                                            GA->getOffset(), OperandFlags);
7528   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7529
7530   // Add x@dtpoff with the base.
7531   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7532 }
7533
7534 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7535 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7536                                    const EVT PtrVT, TLSModel::Model model,
7537                                    bool is64Bit, bool isPIC) {
7538   DebugLoc dl = GA->getDebugLoc();
7539
7540   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7541   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7542                                                          is64Bit ? 257 : 256));
7543
7544   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7545                                       DAG.getIntPtrConstant(0),
7546                                       MachinePointerInfo(Ptr),
7547                                       false, false, false, 0);
7548
7549   unsigned char OperandFlags = 0;
7550   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7551   // initialexec.
7552   unsigned WrapperKind = X86ISD::Wrapper;
7553   if (model == TLSModel::LocalExec) {
7554     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7555   } else if (model == TLSModel::InitialExec) {
7556     if (is64Bit) {
7557       OperandFlags = X86II::MO_GOTTPOFF;
7558       WrapperKind = X86ISD::WrapperRIP;
7559     } else {
7560       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7561     }
7562   } else {
7563     llvm_unreachable("Unexpected model");
7564   }
7565
7566   // emit "addl x@ntpoff,%eax" (local exec)
7567   // or "addl x@indntpoff,%eax" (initial exec)
7568   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7569   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7570                                            GA->getValueType(0),
7571                                            GA->getOffset(), OperandFlags);
7572   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7573
7574   if (model == TLSModel::InitialExec) {
7575     if (isPIC && !is64Bit) {
7576       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7577                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7578                            Offset);
7579     }
7580
7581     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7582                          MachinePointerInfo::getGOT(), false, false, false,
7583                          0);
7584   }
7585
7586   // The address of the thread local variable is the add of the thread
7587   // pointer with the offset of the variable.
7588   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7589 }
7590
7591 SDValue
7592 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7593
7594   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7595   const GlobalValue *GV = GA->getGlobal();
7596
7597   if (Subtarget->isTargetELF()) {
7598     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7599
7600     switch (model) {
7601       case TLSModel::GeneralDynamic:
7602         if (Subtarget->is64Bit())
7603           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7604         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7605       case TLSModel::LocalDynamic:
7606         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7607                                            Subtarget->is64Bit());
7608       case TLSModel::InitialExec:
7609       case TLSModel::LocalExec:
7610         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7611                                    Subtarget->is64Bit(),
7612                          getTargetMachine().getRelocationModel() == Reloc::PIC_);
7613     }
7614     llvm_unreachable("Unknown TLS model.");
7615   }
7616
7617   if (Subtarget->isTargetDarwin()) {
7618     // Darwin only has one model of TLS.  Lower to that.
7619     unsigned char OpFlag = 0;
7620     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7621                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7622
7623     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7624     // global base reg.
7625     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7626                   !Subtarget->is64Bit();
7627     if (PIC32)
7628       OpFlag = X86II::MO_TLVP_PIC_BASE;
7629     else
7630       OpFlag = X86II::MO_TLVP;
7631     DebugLoc DL = Op.getDebugLoc();
7632     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7633                                                 GA->getValueType(0),
7634                                                 GA->getOffset(), OpFlag);
7635     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7636
7637     // With PIC32, the address is actually $g + Offset.
7638     if (PIC32)
7639       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7640                            DAG.getNode(X86ISD::GlobalBaseReg,
7641                                        DebugLoc(), getPointerTy()),
7642                            Offset);
7643
7644     // Lowering the machine isd will make sure everything is in the right
7645     // location.
7646     SDValue Chain = DAG.getEntryNode();
7647     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7648     SDValue Args[] = { Chain, Offset };
7649     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7650
7651     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7652     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7653     MFI->setAdjustsStack(true);
7654
7655     // And our return value (tls address) is in the standard call return value
7656     // location.
7657     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7658     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7659                               Chain.getValue(1));
7660   }
7661
7662   if (Subtarget->isTargetWindows()) {
7663     // Just use the implicit TLS architecture
7664     // Need to generate someting similar to:
7665     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7666     //                                  ; from TEB
7667     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7668     //   mov     rcx, qword [rdx+rcx*8]
7669     //   mov     eax, .tls$:tlsvar
7670     //   [rax+rcx] contains the address
7671     // Windows 64bit: gs:0x58
7672     // Windows 32bit: fs:__tls_array
7673
7674     // If GV is an alias then use the aliasee for determining
7675     // thread-localness.
7676     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7677       GV = GA->resolveAliasedGlobal(false);
7678     DebugLoc dl = GA->getDebugLoc();
7679     SDValue Chain = DAG.getEntryNode();
7680
7681     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7682     // %gs:0x58 (64-bit).
7683     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7684                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7685                                                              256)
7686                                         : Type::getInt32PtrTy(*DAG.getContext(),
7687                                                               257));
7688
7689     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7690                                         Subtarget->is64Bit()
7691                                         ? DAG.getIntPtrConstant(0x58)
7692                                         : DAG.getExternalSymbol("_tls_array",
7693                                                                 getPointerTy()),
7694                                         MachinePointerInfo(Ptr),
7695                                         false, false, false, 0);
7696
7697     // Load the _tls_index variable
7698     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7699     if (Subtarget->is64Bit())
7700       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7701                            IDX, MachinePointerInfo(), MVT::i32,
7702                            false, false, 0);
7703     else
7704       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7705                         false, false, false, 0);
7706
7707     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7708                                     getPointerTy());
7709     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7710
7711     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7712     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7713                       false, false, false, 0);
7714
7715     // Get the offset of start of .tls section
7716     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7717                                              GA->getValueType(0),
7718                                              GA->getOffset(), X86II::MO_SECREL);
7719     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7720
7721     // The address of the thread local variable is the add of the thread
7722     // pointer with the offset of the variable.
7723     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7724   }
7725
7726   llvm_unreachable("TLS not implemented for this target.");
7727 }
7728
7729
7730 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7731 /// and take a 2 x i32 value to shift plus a shift amount.
7732 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7733   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7734   EVT VT = Op.getValueType();
7735   unsigned VTBits = VT.getSizeInBits();
7736   DebugLoc dl = Op.getDebugLoc();
7737   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7738   SDValue ShOpLo = Op.getOperand(0);
7739   SDValue ShOpHi = Op.getOperand(1);
7740   SDValue ShAmt  = Op.getOperand(2);
7741   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7742                                      DAG.getConstant(VTBits - 1, MVT::i8))
7743                        : DAG.getConstant(0, VT);
7744
7745   SDValue Tmp2, Tmp3;
7746   if (Op.getOpcode() == ISD::SHL_PARTS) {
7747     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7748     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7749   } else {
7750     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7751     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7752   }
7753
7754   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7755                                 DAG.getConstant(VTBits, MVT::i8));
7756   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7757                              AndNode, DAG.getConstant(0, MVT::i8));
7758
7759   SDValue Hi, Lo;
7760   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7761   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7762   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7763
7764   if (Op.getOpcode() == ISD::SHL_PARTS) {
7765     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7766     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7767   } else {
7768     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7769     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7770   }
7771
7772   SDValue Ops[2] = { Lo, Hi };
7773   return DAG.getMergeValues(Ops, 2, dl);
7774 }
7775
7776 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7777                                            SelectionDAG &DAG) const {
7778   EVT SrcVT = Op.getOperand(0).getValueType();
7779
7780   if (SrcVT.isVector())
7781     return SDValue();
7782
7783   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7784          "Unknown SINT_TO_FP to lower!");
7785
7786   // These are really Legal; return the operand so the caller accepts it as
7787   // Legal.
7788   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7789     return Op;
7790   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7791       Subtarget->is64Bit()) {
7792     return Op;
7793   }
7794
7795   DebugLoc dl = Op.getDebugLoc();
7796   unsigned Size = SrcVT.getSizeInBits()/8;
7797   MachineFunction &MF = DAG.getMachineFunction();
7798   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7799   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7800   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7801                                StackSlot,
7802                                MachinePointerInfo::getFixedStack(SSFI),
7803                                false, false, 0);
7804   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7805 }
7806
7807 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7808                                      SDValue StackSlot,
7809                                      SelectionDAG &DAG) const {
7810   // Build the FILD
7811   DebugLoc DL = Op.getDebugLoc();
7812   SDVTList Tys;
7813   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7814   if (useSSE)
7815     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7816   else
7817     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7818
7819   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7820
7821   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7822   MachineMemOperand *MMO;
7823   if (FI) {
7824     int SSFI = FI->getIndex();
7825     MMO =
7826       DAG.getMachineFunction()
7827       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7828                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7829   } else {
7830     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7831     StackSlot = StackSlot.getOperand(1);
7832   }
7833   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7834   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7835                                            X86ISD::FILD, DL,
7836                                            Tys, Ops, array_lengthof(Ops),
7837                                            SrcVT, MMO);
7838
7839   if (useSSE) {
7840     Chain = Result.getValue(1);
7841     SDValue InFlag = Result.getValue(2);
7842
7843     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7844     // shouldn't be necessary except that RFP cannot be live across
7845     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7846     MachineFunction &MF = DAG.getMachineFunction();
7847     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7848     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7849     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7850     Tys = DAG.getVTList(MVT::Other);
7851     SDValue Ops[] = {
7852       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7853     };
7854     MachineMemOperand *MMO =
7855       DAG.getMachineFunction()
7856       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7857                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7858
7859     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7860                                     Ops, array_lengthof(Ops),
7861                                     Op.getValueType(), MMO);
7862     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7863                          MachinePointerInfo::getFixedStack(SSFI),
7864                          false, false, false, 0);
7865   }
7866
7867   return Result;
7868 }
7869
7870 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7871 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7872                                                SelectionDAG &DAG) const {
7873   // This algorithm is not obvious. Here it is what we're trying to output:
7874   /*
7875      movq       %rax,  %xmm0
7876      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7877      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7878      #ifdef __SSE3__
7879        haddpd   %xmm0, %xmm0
7880      #else
7881        pshufd   $0x4e, %xmm0, %xmm1
7882        addpd    %xmm1, %xmm0
7883      #endif
7884   */
7885
7886   DebugLoc dl = Op.getDebugLoc();
7887   LLVMContext *Context = DAG.getContext();
7888
7889   // Build some magic constants.
7890   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7891   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7892   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7893
7894   SmallVector<Constant*,2> CV1;
7895   CV1.push_back(
7896         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7897   CV1.push_back(
7898         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7899   Constant *C1 = ConstantVector::get(CV1);
7900   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7901
7902   // Load the 64-bit value into an XMM register.
7903   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7904                             Op.getOperand(0));
7905   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7906                               MachinePointerInfo::getConstantPool(),
7907                               false, false, false, 16);
7908   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7909                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7910                               CLod0);
7911
7912   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7913                               MachinePointerInfo::getConstantPool(),
7914                               false, false, false, 16);
7915   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7916   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7917   SDValue Result;
7918
7919   if (Subtarget->hasSSE3()) {
7920     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7921     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7922   } else {
7923     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7924     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7925                                            S2F, 0x4E, DAG);
7926     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7927                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7928                          Sub);
7929   }
7930
7931   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7932                      DAG.getIntPtrConstant(0));
7933 }
7934
7935 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7936 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7937                                                SelectionDAG &DAG) const {
7938   DebugLoc dl = Op.getDebugLoc();
7939   // FP constant to bias correct the final result.
7940   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7941                                    MVT::f64);
7942
7943   // Load the 32-bit value into an XMM register.
7944   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7945                              Op.getOperand(0));
7946
7947   // Zero out the upper parts of the register.
7948   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7949
7950   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7951                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7952                      DAG.getIntPtrConstant(0));
7953
7954   // Or the load with the bias.
7955   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7956                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7957                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7958                                                    MVT::v2f64, Load)),
7959                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7960                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7961                                                    MVT::v2f64, Bias)));
7962   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7963                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7964                    DAG.getIntPtrConstant(0));
7965
7966   // Subtract the bias.
7967   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7968
7969   // Handle final rounding.
7970   EVT DestVT = Op.getValueType();
7971
7972   if (DestVT.bitsLT(MVT::f64))
7973     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7974                        DAG.getIntPtrConstant(0));
7975   if (DestVT.bitsGT(MVT::f64))
7976     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7977
7978   // Handle final rounding.
7979   return Sub;
7980 }
7981
7982 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7983                                            SelectionDAG &DAG) const {
7984   SDValue N0 = Op.getOperand(0);
7985   DebugLoc dl = Op.getDebugLoc();
7986
7987   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7988   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7989   // the optimization here.
7990   if (DAG.SignBitIsZero(N0))
7991     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7992
7993   EVT SrcVT = N0.getValueType();
7994   EVT DstVT = Op.getValueType();
7995   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7996     return LowerUINT_TO_FP_i64(Op, DAG);
7997   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7998     return LowerUINT_TO_FP_i32(Op, DAG);
7999   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8000     return SDValue();
8001
8002   // Make a 64-bit buffer, and use it to build an FILD.
8003   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8004   if (SrcVT == MVT::i32) {
8005     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8006     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8007                                      getPointerTy(), StackSlot, WordOff);
8008     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8009                                   StackSlot, MachinePointerInfo(),
8010                                   false, false, 0);
8011     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8012                                   OffsetSlot, MachinePointerInfo(),
8013                                   false, false, 0);
8014     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8015     return Fild;
8016   }
8017
8018   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8019   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8020                                StackSlot, MachinePointerInfo(),
8021                                false, false, 0);
8022   // For i64 source, we need to add the appropriate power of 2 if the input
8023   // was negative.  This is the same as the optimization in
8024   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8025   // we must be careful to do the computation in x87 extended precision, not
8026   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8027   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8028   MachineMemOperand *MMO =
8029     DAG.getMachineFunction()
8030     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8031                           MachineMemOperand::MOLoad, 8, 8);
8032
8033   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8034   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8035   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8036                                          MVT::i64, MMO);
8037
8038   APInt FF(32, 0x5F800000ULL);
8039
8040   // Check whether the sign bit is set.
8041   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8042                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8043                                  ISD::SETLT);
8044
8045   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8046   SDValue FudgePtr = DAG.getConstantPool(
8047                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8048                                          getPointerTy());
8049
8050   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8051   SDValue Zero = DAG.getIntPtrConstant(0);
8052   SDValue Four = DAG.getIntPtrConstant(4);
8053   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8054                                Zero, Four);
8055   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8056
8057   // Load the value out, extending it from f32 to f80.
8058   // FIXME: Avoid the extend by constructing the right constant pool?
8059   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8060                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8061                                  MVT::f32, false, false, 4);
8062   // Extend everything to 80 bits to force it to be done on x87.
8063   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8064   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8065 }
8066
8067 std::pair<SDValue,SDValue> X86TargetLowering::
8068 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8069   DebugLoc DL = Op.getDebugLoc();
8070
8071   EVT DstTy = Op.getValueType();
8072
8073   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8074     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8075     DstTy = MVT::i64;
8076   }
8077
8078   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8079          DstTy.getSimpleVT() >= MVT::i16 &&
8080          "Unknown FP_TO_INT to lower!");
8081
8082   // These are really Legal.
8083   if (DstTy == MVT::i32 &&
8084       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8085     return std::make_pair(SDValue(), SDValue());
8086   if (Subtarget->is64Bit() &&
8087       DstTy == MVT::i64 &&
8088       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8089     return std::make_pair(SDValue(), SDValue());
8090
8091   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8092   // stack slot, or into the FTOL runtime function.
8093   MachineFunction &MF = DAG.getMachineFunction();
8094   unsigned MemSize = DstTy.getSizeInBits()/8;
8095   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8096   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8097
8098   unsigned Opc;
8099   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8100     Opc = X86ISD::WIN_FTOL;
8101   else
8102     switch (DstTy.getSimpleVT().SimpleTy) {
8103     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8104     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8105     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8106     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8107     }
8108
8109   SDValue Chain = DAG.getEntryNode();
8110   SDValue Value = Op.getOperand(0);
8111   EVT TheVT = Op.getOperand(0).getValueType();
8112   // FIXME This causes a redundant load/store if the SSE-class value is already
8113   // in memory, such as if it is on the callstack.
8114   if (isScalarFPTypeInSSEReg(TheVT)) {
8115     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8116     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8117                          MachinePointerInfo::getFixedStack(SSFI),
8118                          false, false, 0);
8119     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8120     SDValue Ops[] = {
8121       Chain, StackSlot, DAG.getValueType(TheVT)
8122     };
8123
8124     MachineMemOperand *MMO =
8125       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8126                               MachineMemOperand::MOLoad, MemSize, MemSize);
8127     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8128                                     DstTy, MMO);
8129     Chain = Value.getValue(1);
8130     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8131     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8132   }
8133
8134   MachineMemOperand *MMO =
8135     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8136                             MachineMemOperand::MOStore, MemSize, MemSize);
8137
8138   if (Opc != X86ISD::WIN_FTOL) {
8139     // Build the FP_TO_INT*_IN_MEM
8140     SDValue Ops[] = { Chain, Value, StackSlot };
8141     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8142                                            Ops, 3, DstTy, MMO);
8143     return std::make_pair(FIST, StackSlot);
8144   } else {
8145     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8146       DAG.getVTList(MVT::Other, MVT::Glue),
8147       Chain, Value);
8148     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8149       MVT::i32, ftol.getValue(1));
8150     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8151       MVT::i32, eax.getValue(2));
8152     SDValue Ops[] = { eax, edx };
8153     SDValue pair = IsReplace
8154       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8155       : DAG.getMergeValues(Ops, 2, DL);
8156     return std::make_pair(pair, SDValue());
8157   }
8158 }
8159
8160 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8161                                            SelectionDAG &DAG) const {
8162   if (Op.getValueType().isVector())
8163     return SDValue();
8164
8165   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8166     /*IsSigned=*/ true, /*IsReplace=*/ false);
8167   SDValue FIST = Vals.first, StackSlot = Vals.second;
8168   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8169   if (FIST.getNode() == 0) return Op;
8170
8171   if (StackSlot.getNode())
8172     // Load the result.
8173     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8174                        FIST, StackSlot, MachinePointerInfo(),
8175                        false, false, false, 0);
8176
8177   // The node is the result.
8178   return FIST;
8179 }
8180
8181 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8182                                            SelectionDAG &DAG) const {
8183   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8184     /*IsSigned=*/ false, /*IsReplace=*/ false);
8185   SDValue FIST = Vals.first, StackSlot = Vals.second;
8186   assert(FIST.getNode() && "Unexpected failure");
8187
8188   if (StackSlot.getNode())
8189     // Load the result.
8190     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8191                        FIST, StackSlot, MachinePointerInfo(),
8192                        false, false, false, 0);
8193
8194   // The node is the result.
8195   return FIST;
8196 }
8197
8198 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8199   LLVMContext *Context = DAG.getContext();
8200   DebugLoc dl = Op.getDebugLoc();
8201   EVT VT = Op.getValueType();
8202   EVT EltVT = VT;
8203   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8204   if (VT.isVector()) {
8205     EltVT = VT.getVectorElementType();
8206     NumElts = VT.getVectorNumElements();
8207   }
8208   Constant *C;
8209   if (EltVT == MVT::f64)
8210     C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8211   else
8212     C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8213   C = ConstantVector::getSplat(NumElts, C);
8214   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8215   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8216   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8217                              MachinePointerInfo::getConstantPool(),
8218                              false, false, false, Alignment);
8219   if (VT.isVector()) {
8220     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8221     return DAG.getNode(ISD::BITCAST, dl, VT,
8222                        DAG.getNode(ISD::AND, dl, ANDVT,
8223                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8224                                                Op.getOperand(0)),
8225                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8226   }
8227   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8228 }
8229
8230 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8231   LLVMContext *Context = DAG.getContext();
8232   DebugLoc dl = Op.getDebugLoc();
8233   EVT VT = Op.getValueType();
8234   EVT EltVT = VT;
8235   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8236   if (VT.isVector()) {
8237     EltVT = VT.getVectorElementType();
8238     NumElts = VT.getVectorNumElements();
8239   }
8240   Constant *C;
8241   if (EltVT == MVT::f64)
8242     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8243   else
8244     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8245   C = ConstantVector::getSplat(NumElts, C);
8246   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8247   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8248   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8249                              MachinePointerInfo::getConstantPool(),
8250                              false, false, false, Alignment);
8251   if (VT.isVector()) {
8252     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8253     return DAG.getNode(ISD::BITCAST, dl, VT,
8254                        DAG.getNode(ISD::XOR, dl, XORVT,
8255                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8256                                                Op.getOperand(0)),
8257                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8258   }
8259
8260   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8261 }
8262
8263 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8264   LLVMContext *Context = DAG.getContext();
8265   SDValue Op0 = Op.getOperand(0);
8266   SDValue Op1 = Op.getOperand(1);
8267   DebugLoc dl = Op.getDebugLoc();
8268   EVT VT = Op.getValueType();
8269   EVT SrcVT = Op1.getValueType();
8270
8271   // If second operand is smaller, extend it first.
8272   if (SrcVT.bitsLT(VT)) {
8273     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8274     SrcVT = VT;
8275   }
8276   // And if it is bigger, shrink it first.
8277   if (SrcVT.bitsGT(VT)) {
8278     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8279     SrcVT = VT;
8280   }
8281
8282   // At this point the operands and the result should have the same
8283   // type, and that won't be f80 since that is not custom lowered.
8284
8285   // First get the sign bit of second operand.
8286   SmallVector<Constant*,4> CV;
8287   if (SrcVT == MVT::f64) {
8288     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8289     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8290   } else {
8291     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8292     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8293     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8294     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8295   }
8296   Constant *C = ConstantVector::get(CV);
8297   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8298   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8299                               MachinePointerInfo::getConstantPool(),
8300                               false, false, false, 16);
8301   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8302
8303   // Shift sign bit right or left if the two operands have different types.
8304   if (SrcVT.bitsGT(VT)) {
8305     // Op0 is MVT::f32, Op1 is MVT::f64.
8306     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8307     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8308                           DAG.getConstant(32, MVT::i32));
8309     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8310     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8311                           DAG.getIntPtrConstant(0));
8312   }
8313
8314   // Clear first operand sign bit.
8315   CV.clear();
8316   if (VT == MVT::f64) {
8317     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8318     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8319   } else {
8320     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8321     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8322     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8323     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8324   }
8325   C = ConstantVector::get(CV);
8326   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8327   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8328                               MachinePointerInfo::getConstantPool(),
8329                               false, false, false, 16);
8330   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8331
8332   // Or the value with the sign bit.
8333   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8334 }
8335
8336 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8337   SDValue N0 = Op.getOperand(0);
8338   DebugLoc dl = Op.getDebugLoc();
8339   EVT VT = Op.getValueType();
8340
8341   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8342   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8343                                   DAG.getConstant(1, VT));
8344   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8345 }
8346
8347 /// Emit nodes that will be selected as "test Op0,Op0", or something
8348 /// equivalent.
8349 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8350                                     SelectionDAG &DAG) const {
8351   DebugLoc dl = Op.getDebugLoc();
8352
8353   // CF and OF aren't always set the way we want. Determine which
8354   // of these we need.
8355   bool NeedCF = false;
8356   bool NeedOF = false;
8357   switch (X86CC) {
8358   default: break;
8359   case X86::COND_A: case X86::COND_AE:
8360   case X86::COND_B: case X86::COND_BE:
8361     NeedCF = true;
8362     break;
8363   case X86::COND_G: case X86::COND_GE:
8364   case X86::COND_L: case X86::COND_LE:
8365   case X86::COND_O: case X86::COND_NO:
8366     NeedOF = true;
8367     break;
8368   }
8369
8370   // See if we can use the EFLAGS value from the operand instead of
8371   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8372   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8373   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8374     // Emit a CMP with 0, which is the TEST pattern.
8375     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8376                        DAG.getConstant(0, Op.getValueType()));
8377
8378   unsigned Opcode = 0;
8379   unsigned NumOperands = 0;
8380
8381   // Truncate operations may prevent the merge of the SETCC instruction
8382   // and the arithmetic intruction before it. Attempt to truncate the operands
8383   // of the arithmetic instruction and use a reduced bit-width instruction.
8384   bool NeedTruncation = false;
8385   SDValue ArithOp = Op;
8386   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8387     SDValue Arith = Op->getOperand(0);
8388     // Both the trunc and the arithmetic op need to have one user each.
8389     if (Arith->hasOneUse())
8390       switch (Arith.getOpcode()) {
8391         default: break;
8392         case ISD::ADD:
8393         case ISD::SUB:
8394         case ISD::AND:
8395         case ISD::OR:
8396         case ISD::XOR: {
8397           NeedTruncation = true;
8398           ArithOp = Arith;
8399         }
8400       }
8401   }
8402
8403   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8404   // which may be the result of a CAST.  We use the variable 'Op', which is the
8405   // non-casted variable when we check for possible users.
8406   switch (ArithOp.getOpcode()) {
8407   case ISD::ADD:
8408     // Due to an isel shortcoming, be conservative if this add is likely to be
8409     // selected as part of a load-modify-store instruction. When the root node
8410     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8411     // uses of other nodes in the match, such as the ADD in this case. This
8412     // leads to the ADD being left around and reselected, with the result being
8413     // two adds in the output.  Alas, even if none our users are stores, that
8414     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8415     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8416     // climbing the DAG back to the root, and it doesn't seem to be worth the
8417     // effort.
8418     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8419          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8420       if (UI->getOpcode() != ISD::CopyToReg &&
8421           UI->getOpcode() != ISD::SETCC &&
8422           UI->getOpcode() != ISD::STORE)
8423         goto default_case;
8424
8425     if (ConstantSDNode *C =
8426         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8427       // An add of one will be selected as an INC.
8428       if (C->getAPIntValue() == 1) {
8429         Opcode = X86ISD::INC;
8430         NumOperands = 1;
8431         break;
8432       }
8433
8434       // An add of negative one (subtract of one) will be selected as a DEC.
8435       if (C->getAPIntValue().isAllOnesValue()) {
8436         Opcode = X86ISD::DEC;
8437         NumOperands = 1;
8438         break;
8439       }
8440     }
8441
8442     // Otherwise use a regular EFLAGS-setting add.
8443     Opcode = X86ISD::ADD;
8444     NumOperands = 2;
8445     break;
8446   case ISD::AND: {
8447     // If the primary and result isn't used, don't bother using X86ISD::AND,
8448     // because a TEST instruction will be better.
8449     bool NonFlagUse = false;
8450     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8451            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8452       SDNode *User = *UI;
8453       unsigned UOpNo = UI.getOperandNo();
8454       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8455         // Look pass truncate.
8456         UOpNo = User->use_begin().getOperandNo();
8457         User = *User->use_begin();
8458       }
8459
8460       if (User->getOpcode() != ISD::BRCOND &&
8461           User->getOpcode() != ISD::SETCC &&
8462           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8463         NonFlagUse = true;
8464         break;
8465       }
8466     }
8467
8468     if (!NonFlagUse)
8469       break;
8470   }
8471     // FALL THROUGH
8472   case ISD::SUB:
8473   case ISD::OR:
8474   case ISD::XOR:
8475     // Due to the ISEL shortcoming noted above, be conservative if this op is
8476     // likely to be selected as part of a load-modify-store instruction.
8477     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8478            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8479       if (UI->getOpcode() == ISD::STORE)
8480         goto default_case;
8481
8482     // Otherwise use a regular EFLAGS-setting instruction.
8483     switch (ArithOp.getOpcode()) {
8484     default: llvm_unreachable("unexpected operator!");
8485     case ISD::SUB: Opcode = X86ISD::SUB; break;
8486     case ISD::OR:  Opcode = X86ISD::OR;  break;
8487     case ISD::XOR: Opcode = X86ISD::XOR; break;
8488     case ISD::AND: Opcode = X86ISD::AND; break;
8489     }
8490
8491     NumOperands = 2;
8492     break;
8493   case X86ISD::ADD:
8494   case X86ISD::SUB:
8495   case X86ISD::INC:
8496   case X86ISD::DEC:
8497   case X86ISD::OR:
8498   case X86ISD::XOR:
8499   case X86ISD::AND:
8500     return SDValue(Op.getNode(), 1);
8501   default:
8502   default_case:
8503     break;
8504   }
8505
8506   // If we found that truncation is beneficial, perform the truncation and
8507   // update 'Op'.
8508   if (NeedTruncation) {
8509     EVT VT = Op.getValueType();
8510     SDValue WideVal = Op->getOperand(0);
8511     EVT WideVT = WideVal.getValueType();
8512     unsigned ConvertedOp = 0;
8513     // Use a target machine opcode to prevent further DAGCombine
8514     // optimizations that may separate the arithmetic operations
8515     // from the setcc node.
8516     switch (WideVal.getOpcode()) {
8517       default: break;
8518       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8519       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8520       case ISD::AND: ConvertedOp = X86ISD::AND; break;
8521       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
8522       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8523     }
8524
8525     if (ConvertedOp) {
8526       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8527       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8528         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8529         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8530         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8531       }
8532     }
8533   }
8534
8535   if (Opcode == 0)
8536     // Emit a CMP with 0, which is the TEST pattern.
8537     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8538                        DAG.getConstant(0, Op.getValueType()));
8539
8540   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8541   SmallVector<SDValue, 4> Ops;
8542   for (unsigned i = 0; i != NumOperands; ++i)
8543     Ops.push_back(Op.getOperand(i));
8544
8545   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8546   DAG.ReplaceAllUsesWith(Op, New);
8547   return SDValue(New.getNode(), 1);
8548 }
8549
8550 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8551 /// equivalent.
8552 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8553                                    SelectionDAG &DAG) const {
8554   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8555     if (C->getAPIntValue() == 0)
8556       return EmitTest(Op0, X86CC, DAG);
8557
8558   DebugLoc dl = Op0.getDebugLoc();
8559   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8560        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8561     // Use SUB instead of CMP to enable CSE between SUB and CMP.
8562     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8563     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8564                               Op0, Op1);
8565     return SDValue(Sub.getNode(), 1);
8566   }
8567   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8568 }
8569
8570 /// Convert a comparison if required by the subtarget.
8571 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8572                                                  SelectionDAG &DAG) const {
8573   // If the subtarget does not support the FUCOMI instruction, floating-point
8574   // comparisons have to be converted.
8575   if (Subtarget->hasCMov() ||
8576       Cmp.getOpcode() != X86ISD::CMP ||
8577       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8578       !Cmp.getOperand(1).getValueType().isFloatingPoint())
8579     return Cmp;
8580
8581   // The instruction selector will select an FUCOM instruction instead of
8582   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8583   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8584   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8585   DebugLoc dl = Cmp.getDebugLoc();
8586   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8587   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8588   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8589                             DAG.getConstant(8, MVT::i8));
8590   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8591   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8592 }
8593
8594 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8595 /// if it's possible.
8596 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8597                                      DebugLoc dl, SelectionDAG &DAG) const {
8598   SDValue Op0 = And.getOperand(0);
8599   SDValue Op1 = And.getOperand(1);
8600   if (Op0.getOpcode() == ISD::TRUNCATE)
8601     Op0 = Op0.getOperand(0);
8602   if (Op1.getOpcode() == ISD::TRUNCATE)
8603     Op1 = Op1.getOperand(0);
8604
8605   SDValue LHS, RHS;
8606   if (Op1.getOpcode() == ISD::SHL)
8607     std::swap(Op0, Op1);
8608   if (Op0.getOpcode() == ISD::SHL) {
8609     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8610       if (And00C->getZExtValue() == 1) {
8611         // If we looked past a truncate, check that it's only truncating away
8612         // known zeros.
8613         unsigned BitWidth = Op0.getValueSizeInBits();
8614         unsigned AndBitWidth = And.getValueSizeInBits();
8615         if (BitWidth > AndBitWidth) {
8616           APInt Zeros, Ones;
8617           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8618           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8619             return SDValue();
8620         }
8621         LHS = Op1;
8622         RHS = Op0.getOperand(1);
8623       }
8624   } else if (Op1.getOpcode() == ISD::Constant) {
8625     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8626     uint64_t AndRHSVal = AndRHS->getZExtValue();
8627     SDValue AndLHS = Op0;
8628
8629     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8630       LHS = AndLHS.getOperand(0);
8631       RHS = AndLHS.getOperand(1);
8632     }
8633
8634     // Use BT if the immediate can't be encoded in a TEST instruction.
8635     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8636       LHS = AndLHS;
8637       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8638     }
8639   }
8640
8641   if (LHS.getNode()) {
8642     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8643     // instruction.  Since the shift amount is in-range-or-undefined, we know
8644     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8645     // the encoding for the i16 version is larger than the i32 version.
8646     // Also promote i16 to i32 for performance / code size reason.
8647     if (LHS.getValueType() == MVT::i8 ||
8648         LHS.getValueType() == MVT::i16)
8649       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8650
8651     // If the operand types disagree, extend the shift amount to match.  Since
8652     // BT ignores high bits (like shifts) we can use anyextend.
8653     if (LHS.getValueType() != RHS.getValueType())
8654       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8655
8656     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8657     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8658     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8659                        DAG.getConstant(Cond, MVT::i8), BT);
8660   }
8661
8662   return SDValue();
8663 }
8664
8665 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8666
8667   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8668
8669   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8670   SDValue Op0 = Op.getOperand(0);
8671   SDValue Op1 = Op.getOperand(1);
8672   DebugLoc dl = Op.getDebugLoc();
8673   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8674
8675   // Optimize to BT if possible.
8676   // Lower (X & (1 << N)) == 0 to BT(X, N).
8677   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8678   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8679   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8680       Op1.getOpcode() == ISD::Constant &&
8681       cast<ConstantSDNode>(Op1)->isNullValue() &&
8682       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8683     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8684     if (NewSetCC.getNode())
8685       return NewSetCC;
8686   }
8687
8688   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8689   // these.
8690   if (Op1.getOpcode() == ISD::Constant &&
8691       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8692        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8693       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8694
8695     // If the input is a setcc, then reuse the input setcc or use a new one with
8696     // the inverted condition.
8697     if (Op0.getOpcode() == X86ISD::SETCC) {
8698       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8699       bool Invert = (CC == ISD::SETNE) ^
8700         cast<ConstantSDNode>(Op1)->isNullValue();
8701       if (!Invert) return Op0;
8702
8703       CCode = X86::GetOppositeBranchCondition(CCode);
8704       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8705                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8706     }
8707   }
8708
8709   bool isFP = Op1.getValueType().isFloatingPoint();
8710   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8711   if (X86CC == X86::COND_INVALID)
8712     return SDValue();
8713
8714   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8715   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8716   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8717                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8718 }
8719
8720 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8721 // ones, and then concatenate the result back.
8722 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8723   EVT VT = Op.getValueType();
8724
8725   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8726          "Unsupported value type for operation");
8727
8728   unsigned NumElems = VT.getVectorNumElements();
8729   DebugLoc dl = Op.getDebugLoc();
8730   SDValue CC = Op.getOperand(2);
8731
8732   // Extract the LHS vectors
8733   SDValue LHS = Op.getOperand(0);
8734   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8735   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8736
8737   // Extract the RHS vectors
8738   SDValue RHS = Op.getOperand(1);
8739   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8740   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8741
8742   // Issue the operation on the smaller types and concatenate the result back
8743   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8744   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8745   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8746                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8747                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8748 }
8749
8750
8751 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8752   SDValue Cond;
8753   SDValue Op0 = Op.getOperand(0);
8754   SDValue Op1 = Op.getOperand(1);
8755   SDValue CC = Op.getOperand(2);
8756   EVT VT = Op.getValueType();
8757   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8758   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8759   DebugLoc dl = Op.getDebugLoc();
8760
8761   if (isFP) {
8762 #ifndef NDEBUG
8763     EVT EltVT = Op0.getValueType().getVectorElementType();
8764     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8765 #endif
8766
8767     unsigned SSECC;
8768     bool Swap = false;
8769
8770     // SSE Condition code mapping:
8771     //  0 - EQ
8772     //  1 - LT
8773     //  2 - LE
8774     //  3 - UNORD
8775     //  4 - NEQ
8776     //  5 - NLT
8777     //  6 - NLE
8778     //  7 - ORD
8779     switch (SetCCOpcode) {
8780     default: llvm_unreachable("Unexpected SETCC condition");
8781     case ISD::SETOEQ:
8782     case ISD::SETEQ:  SSECC = 0; break;
8783     case ISD::SETOGT:
8784     case ISD::SETGT: Swap = true; // Fallthrough
8785     case ISD::SETLT:
8786     case ISD::SETOLT: SSECC = 1; break;
8787     case ISD::SETOGE:
8788     case ISD::SETGE: Swap = true; // Fallthrough
8789     case ISD::SETLE:
8790     case ISD::SETOLE: SSECC = 2; break;
8791     case ISD::SETUO:  SSECC = 3; break;
8792     case ISD::SETUNE:
8793     case ISD::SETNE:  SSECC = 4; break;
8794     case ISD::SETULE: Swap = true; // Fallthrough
8795     case ISD::SETUGE: SSECC = 5; break;
8796     case ISD::SETULT: Swap = true; // Fallthrough
8797     case ISD::SETUGT: SSECC = 6; break;
8798     case ISD::SETO:   SSECC = 7; break;
8799     case ISD::SETUEQ:
8800     case ISD::SETONE: SSECC = 8; break;
8801     }
8802     if (Swap)
8803       std::swap(Op0, Op1);
8804
8805     // In the two special cases we can't handle, emit two comparisons.
8806     if (SSECC == 8) {
8807       unsigned CC0, CC1;
8808       unsigned CombineOpc;
8809       if (SetCCOpcode == ISD::SETUEQ) {
8810         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8811       } else {
8812         assert(SetCCOpcode == ISD::SETONE);
8813         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8814       }
8815
8816       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8817                                  DAG.getConstant(CC0, MVT::i8));
8818       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8819                                  DAG.getConstant(CC1, MVT::i8));
8820       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8821     }
8822     // Handle all other FP comparisons here.
8823     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8824                        DAG.getConstant(SSECC, MVT::i8));
8825   }
8826
8827   // Break 256-bit integer vector compare into smaller ones.
8828   if (VT.is256BitVector() && !Subtarget->hasAVX2())
8829     return Lower256IntVSETCC(Op, DAG);
8830
8831   // We are handling one of the integer comparisons here.  Since SSE only has
8832   // GT and EQ comparisons for integer, swapping operands and multiple
8833   // operations may be required for some comparisons.
8834   unsigned Opc;
8835   bool Swap = false, Invert = false, FlipSigns = false;
8836
8837   switch (SetCCOpcode) {
8838   default: llvm_unreachable("Unexpected SETCC condition");
8839   case ISD::SETNE:  Invert = true;
8840   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8841   case ISD::SETLT:  Swap = true;
8842   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8843   case ISD::SETGE:  Swap = true;
8844   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8845   case ISD::SETULT: Swap = true;
8846   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8847   case ISD::SETUGE: Swap = true;
8848   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8849   }
8850   if (Swap)
8851     std::swap(Op0, Op1);
8852
8853   // Check that the operation in question is available (most are plain SSE2,
8854   // but PCMPGTQ and PCMPEQQ have different requirements).
8855   if (VT == MVT::v2i64) {
8856     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8857       return SDValue();
8858     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8859       return SDValue();
8860   }
8861
8862   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8863   // bits of the inputs before performing those operations.
8864   if (FlipSigns) {
8865     EVT EltVT = VT.getVectorElementType();
8866     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8867                                       EltVT);
8868     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8869     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8870                                     SignBits.size());
8871     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8872     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8873   }
8874
8875   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8876
8877   // If the logical-not of the result is required, perform that now.
8878   if (Invert)
8879     Result = DAG.getNOT(dl, Result, VT);
8880
8881   return Result;
8882 }
8883
8884 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8885 static bool isX86LogicalCmp(SDValue Op) {
8886   unsigned Opc = Op.getNode()->getOpcode();
8887   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8888       Opc == X86ISD::SAHF)
8889     return true;
8890   if (Op.getResNo() == 1 &&
8891       (Opc == X86ISD::ADD ||
8892        Opc == X86ISD::SUB ||
8893        Opc == X86ISD::ADC ||
8894        Opc == X86ISD::SBB ||
8895        Opc == X86ISD::SMUL ||
8896        Opc == X86ISD::UMUL ||
8897        Opc == X86ISD::INC ||
8898        Opc == X86ISD::DEC ||
8899        Opc == X86ISD::OR ||
8900        Opc == X86ISD::XOR ||
8901        Opc == X86ISD::AND))
8902     return true;
8903
8904   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8905     return true;
8906
8907   return false;
8908 }
8909
8910 static bool isZero(SDValue V) {
8911   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8912   return C && C->isNullValue();
8913 }
8914
8915 static bool isAllOnes(SDValue V) {
8916   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8917   return C && C->isAllOnesValue();
8918 }
8919
8920 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8921   if (V.getOpcode() != ISD::TRUNCATE)
8922     return false;
8923
8924   SDValue VOp0 = V.getOperand(0);
8925   unsigned InBits = VOp0.getValueSizeInBits();
8926   unsigned Bits = V.getValueSizeInBits();
8927   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8928 }
8929
8930 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8931   bool addTest = true;
8932   SDValue Cond  = Op.getOperand(0);
8933   SDValue Op1 = Op.getOperand(1);
8934   SDValue Op2 = Op.getOperand(2);
8935   DebugLoc DL = Op.getDebugLoc();
8936   SDValue CC;
8937
8938   if (Cond.getOpcode() == ISD::SETCC) {
8939     SDValue NewCond = LowerSETCC(Cond, DAG);
8940     if (NewCond.getNode())
8941       Cond = NewCond;
8942   }
8943
8944   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8945   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8946   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8947   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8948   if (Cond.getOpcode() == X86ISD::SETCC &&
8949       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8950       isZero(Cond.getOperand(1).getOperand(1))) {
8951     SDValue Cmp = Cond.getOperand(1);
8952
8953     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8954
8955     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8956         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8957       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8958
8959       SDValue CmpOp0 = Cmp.getOperand(0);
8960       // Apply further optimizations for special cases
8961       // (select (x != 0), -1, 0) -> neg & sbb
8962       // (select (x == 0), 0, -1) -> neg & sbb
8963       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8964         if (YC->isNullValue() &&
8965             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8966           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8967           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8968                                     DAG.getConstant(0, CmpOp0.getValueType()),
8969                                     CmpOp0);
8970           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8971                                     DAG.getConstant(X86::COND_B, MVT::i8),
8972                                     SDValue(Neg.getNode(), 1));
8973           return Res;
8974         }
8975
8976       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8977                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8978       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8979
8980       SDValue Res =   // Res = 0 or -1.
8981         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8982                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8983
8984       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8985         Res = DAG.getNOT(DL, Res, Res.getValueType());
8986
8987       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8988       if (N2C == 0 || !N2C->isNullValue())
8989         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8990       return Res;
8991     }
8992   }
8993
8994   // Look past (and (setcc_carry (cmp ...)), 1).
8995   if (Cond.getOpcode() == ISD::AND &&
8996       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8997     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8998     if (C && C->getAPIntValue() == 1)
8999       Cond = Cond.getOperand(0);
9000   }
9001
9002   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9003   // setting operand in place of the X86ISD::SETCC.
9004   unsigned CondOpcode = Cond.getOpcode();
9005   if (CondOpcode == X86ISD::SETCC ||
9006       CondOpcode == X86ISD::SETCC_CARRY) {
9007     CC = Cond.getOperand(0);
9008
9009     SDValue Cmp = Cond.getOperand(1);
9010     unsigned Opc = Cmp.getOpcode();
9011     EVT VT = Op.getValueType();
9012
9013     bool IllegalFPCMov = false;
9014     if (VT.isFloatingPoint() && !VT.isVector() &&
9015         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9016       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9017
9018     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9019         Opc == X86ISD::BT) { // FIXME
9020       Cond = Cmp;
9021       addTest = false;
9022     }
9023   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9024              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9025              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9026               Cond.getOperand(0).getValueType() != MVT::i8)) {
9027     SDValue LHS = Cond.getOperand(0);
9028     SDValue RHS = Cond.getOperand(1);
9029     unsigned X86Opcode;
9030     unsigned X86Cond;
9031     SDVTList VTs;
9032     switch (CondOpcode) {
9033     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9034     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9035     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9036     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9037     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9038     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9039     default: llvm_unreachable("unexpected overflowing operator");
9040     }
9041     if (CondOpcode == ISD::UMULO)
9042       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9043                           MVT::i32);
9044     else
9045       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9046
9047     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9048
9049     if (CondOpcode == ISD::UMULO)
9050       Cond = X86Op.getValue(2);
9051     else
9052       Cond = X86Op.getValue(1);
9053
9054     CC = DAG.getConstant(X86Cond, MVT::i8);
9055     addTest = false;
9056   }
9057
9058   if (addTest) {
9059     // Look pass the truncate if the high bits are known zero.
9060     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9061         Cond = Cond.getOperand(0);
9062
9063     // We know the result of AND is compared against zero. Try to match
9064     // it to BT.
9065     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9066       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9067       if (NewSetCC.getNode()) {
9068         CC = NewSetCC.getOperand(0);
9069         Cond = NewSetCC.getOperand(1);
9070         addTest = false;
9071       }
9072     }
9073   }
9074
9075   if (addTest) {
9076     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9077     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9078   }
9079
9080   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9081   // a <  b ?  0 : -1 -> RES = setcc_carry
9082   // a >= b ? -1 :  0 -> RES = setcc_carry
9083   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9084   if (Cond.getOpcode() == X86ISD::SUB) {
9085     Cond = ConvertCmpIfNecessary(Cond, DAG);
9086     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9087
9088     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9089         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9090       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9091                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9092       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9093         return DAG.getNOT(DL, Res, Res.getValueType());
9094       return Res;
9095     }
9096   }
9097
9098   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9099   // condition is true.
9100   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9101   SDValue Ops[] = { Op2, Op1, CC, Cond };
9102   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9103 }
9104
9105 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9106 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9107 // from the AND / OR.
9108 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9109   Opc = Op.getOpcode();
9110   if (Opc != ISD::OR && Opc != ISD::AND)
9111     return false;
9112   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9113           Op.getOperand(0).hasOneUse() &&
9114           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9115           Op.getOperand(1).hasOneUse());
9116 }
9117
9118 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9119 // 1 and that the SETCC node has a single use.
9120 static bool isXor1OfSetCC(SDValue Op) {
9121   if (Op.getOpcode() != ISD::XOR)
9122     return false;
9123   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9124   if (N1C && N1C->getAPIntValue() == 1) {
9125     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9126       Op.getOperand(0).hasOneUse();
9127   }
9128   return false;
9129 }
9130
9131 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9132   bool addTest = true;
9133   SDValue Chain = Op.getOperand(0);
9134   SDValue Cond  = Op.getOperand(1);
9135   SDValue Dest  = Op.getOperand(2);
9136   DebugLoc dl = Op.getDebugLoc();
9137   SDValue CC;
9138   bool Inverted = false;
9139
9140   if (Cond.getOpcode() == ISD::SETCC) {
9141     // Check for setcc([su]{add,sub,mul}o == 0).
9142     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9143         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9144         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9145         Cond.getOperand(0).getResNo() == 1 &&
9146         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9147          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9148          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9149          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9150          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9151          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9152       Inverted = true;
9153       Cond = Cond.getOperand(0);
9154     } else {
9155       SDValue NewCond = LowerSETCC(Cond, DAG);
9156       if (NewCond.getNode())
9157         Cond = NewCond;
9158     }
9159   }
9160 #if 0
9161   // FIXME: LowerXALUO doesn't handle these!!
9162   else if (Cond.getOpcode() == X86ISD::ADD  ||
9163            Cond.getOpcode() == X86ISD::SUB  ||
9164            Cond.getOpcode() == X86ISD::SMUL ||
9165            Cond.getOpcode() == X86ISD::UMUL)
9166     Cond = LowerXALUO(Cond, DAG);
9167 #endif
9168
9169   // Look pass (and (setcc_carry (cmp ...)), 1).
9170   if (Cond.getOpcode() == ISD::AND &&
9171       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9172     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9173     if (C && C->getAPIntValue() == 1)
9174       Cond = Cond.getOperand(0);
9175   }
9176
9177   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9178   // setting operand in place of the X86ISD::SETCC.
9179   unsigned CondOpcode = Cond.getOpcode();
9180   if (CondOpcode == X86ISD::SETCC ||
9181       CondOpcode == X86ISD::SETCC_CARRY) {
9182     CC = Cond.getOperand(0);
9183
9184     SDValue Cmp = Cond.getOperand(1);
9185     unsigned Opc = Cmp.getOpcode();
9186     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9187     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9188       Cond = Cmp;
9189       addTest = false;
9190     } else {
9191       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9192       default: break;
9193       case X86::COND_O:
9194       case X86::COND_B:
9195         // These can only come from an arithmetic instruction with overflow,
9196         // e.g. SADDO, UADDO.
9197         Cond = Cond.getNode()->getOperand(1);
9198         addTest = false;
9199         break;
9200       }
9201     }
9202   }
9203   CondOpcode = Cond.getOpcode();
9204   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9205       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9206       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9207        Cond.getOperand(0).getValueType() != MVT::i8)) {
9208     SDValue LHS = Cond.getOperand(0);
9209     SDValue RHS = Cond.getOperand(1);
9210     unsigned X86Opcode;
9211     unsigned X86Cond;
9212     SDVTList VTs;
9213     switch (CondOpcode) {
9214     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9215     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9216     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9217     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9218     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9219     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9220     default: llvm_unreachable("unexpected overflowing operator");
9221     }
9222     if (Inverted)
9223       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9224     if (CondOpcode == ISD::UMULO)
9225       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9226                           MVT::i32);
9227     else
9228       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9229
9230     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9231
9232     if (CondOpcode == ISD::UMULO)
9233       Cond = X86Op.getValue(2);
9234     else
9235       Cond = X86Op.getValue(1);
9236
9237     CC = DAG.getConstant(X86Cond, MVT::i8);
9238     addTest = false;
9239   } else {
9240     unsigned CondOpc;
9241     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9242       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9243       if (CondOpc == ISD::OR) {
9244         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9245         // two branches instead of an explicit OR instruction with a
9246         // separate test.
9247         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9248             isX86LogicalCmp(Cmp)) {
9249           CC = Cond.getOperand(0).getOperand(0);
9250           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9251                               Chain, Dest, CC, Cmp);
9252           CC = Cond.getOperand(1).getOperand(0);
9253           Cond = Cmp;
9254           addTest = false;
9255         }
9256       } else { // ISD::AND
9257         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9258         // two branches instead of an explicit AND instruction with a
9259         // separate test. However, we only do this if this block doesn't
9260         // have a fall-through edge, because this requires an explicit
9261         // jmp when the condition is false.
9262         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9263             isX86LogicalCmp(Cmp) &&
9264             Op.getNode()->hasOneUse()) {
9265           X86::CondCode CCode =
9266             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9267           CCode = X86::GetOppositeBranchCondition(CCode);
9268           CC = DAG.getConstant(CCode, MVT::i8);
9269           SDNode *User = *Op.getNode()->use_begin();
9270           // Look for an unconditional branch following this conditional branch.
9271           // We need this because we need to reverse the successors in order
9272           // to implement FCMP_OEQ.
9273           if (User->getOpcode() == ISD::BR) {
9274             SDValue FalseBB = User->getOperand(1);
9275             SDNode *NewBR =
9276               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9277             assert(NewBR == User);
9278             (void)NewBR;
9279             Dest = FalseBB;
9280
9281             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9282                                 Chain, Dest, CC, Cmp);
9283             X86::CondCode CCode =
9284               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9285             CCode = X86::GetOppositeBranchCondition(CCode);
9286             CC = DAG.getConstant(CCode, MVT::i8);
9287             Cond = Cmp;
9288             addTest = false;
9289           }
9290         }
9291       }
9292     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9293       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9294       // It should be transformed during dag combiner except when the condition
9295       // is set by a arithmetics with overflow node.
9296       X86::CondCode CCode =
9297         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9298       CCode = X86::GetOppositeBranchCondition(CCode);
9299       CC = DAG.getConstant(CCode, MVT::i8);
9300       Cond = Cond.getOperand(0).getOperand(1);
9301       addTest = false;
9302     } else if (Cond.getOpcode() == ISD::SETCC &&
9303                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9304       // For FCMP_OEQ, we can emit
9305       // two branches instead of an explicit AND instruction with a
9306       // separate test. However, we only do this if this block doesn't
9307       // have a fall-through edge, because this requires an explicit
9308       // jmp when the condition is false.
9309       if (Op.getNode()->hasOneUse()) {
9310         SDNode *User = *Op.getNode()->use_begin();
9311         // Look for an unconditional branch following this conditional branch.
9312         // We need this because we need to reverse the successors in order
9313         // to implement FCMP_OEQ.
9314         if (User->getOpcode() == ISD::BR) {
9315           SDValue FalseBB = User->getOperand(1);
9316           SDNode *NewBR =
9317             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9318           assert(NewBR == User);
9319           (void)NewBR;
9320           Dest = FalseBB;
9321
9322           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9323                                     Cond.getOperand(0), Cond.getOperand(1));
9324           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9325           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9326           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9327                               Chain, Dest, CC, Cmp);
9328           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9329           Cond = Cmp;
9330           addTest = false;
9331         }
9332       }
9333     } else if (Cond.getOpcode() == ISD::SETCC &&
9334                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9335       // For FCMP_UNE, we can emit
9336       // two branches instead of an explicit AND instruction with a
9337       // separate test. However, we only do this if this block doesn't
9338       // have a fall-through edge, because this requires an explicit
9339       // jmp when the condition is false.
9340       if (Op.getNode()->hasOneUse()) {
9341         SDNode *User = *Op.getNode()->use_begin();
9342         // Look for an unconditional branch following this conditional branch.
9343         // We need this because we need to reverse the successors in order
9344         // to implement FCMP_UNE.
9345         if (User->getOpcode() == ISD::BR) {
9346           SDValue FalseBB = User->getOperand(1);
9347           SDNode *NewBR =
9348             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9349           assert(NewBR == User);
9350           (void)NewBR;
9351
9352           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9353                                     Cond.getOperand(0), Cond.getOperand(1));
9354           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9355           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9356           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9357                               Chain, Dest, CC, Cmp);
9358           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9359           Cond = Cmp;
9360           addTest = false;
9361           Dest = FalseBB;
9362         }
9363       }
9364     }
9365   }
9366
9367   if (addTest) {
9368     // Look pass the truncate if the high bits are known zero.
9369     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9370         Cond = Cond.getOperand(0);
9371
9372     // We know the result of AND is compared against zero. Try to match
9373     // it to BT.
9374     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9375       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9376       if (NewSetCC.getNode()) {
9377         CC = NewSetCC.getOperand(0);
9378         Cond = NewSetCC.getOperand(1);
9379         addTest = false;
9380       }
9381     }
9382   }
9383
9384   if (addTest) {
9385     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9386     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9387   }
9388   Cond = ConvertCmpIfNecessary(Cond, DAG);
9389   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9390                      Chain, Dest, CC, Cond);
9391 }
9392
9393
9394 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9395 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9396 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9397 // that the guard pages used by the OS virtual memory manager are allocated in
9398 // correct sequence.
9399 SDValue
9400 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9401                                            SelectionDAG &DAG) const {
9402   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9403           getTargetMachine().Options.EnableSegmentedStacks) &&
9404          "This should be used only on Windows targets or when segmented stacks "
9405          "are being used");
9406   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9407   DebugLoc dl = Op.getDebugLoc();
9408
9409   // Get the inputs.
9410   SDValue Chain = Op.getOperand(0);
9411   SDValue Size  = Op.getOperand(1);
9412   // FIXME: Ensure alignment here
9413
9414   bool Is64Bit = Subtarget->is64Bit();
9415   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9416
9417   if (getTargetMachine().Options.EnableSegmentedStacks) {
9418     MachineFunction &MF = DAG.getMachineFunction();
9419     MachineRegisterInfo &MRI = MF.getRegInfo();
9420
9421     if (Is64Bit) {
9422       // The 64 bit implementation of segmented stacks needs to clobber both r10
9423       // r11. This makes it impossible to use it along with nested parameters.
9424       const Function *F = MF.getFunction();
9425
9426       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9427            I != E; ++I)
9428         if (I->hasNestAttr())
9429           report_fatal_error("Cannot use segmented stacks with functions that "
9430                              "have nested arguments.");
9431     }
9432
9433     const TargetRegisterClass *AddrRegClass =
9434       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9435     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9436     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9437     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9438                                 DAG.getRegister(Vreg, SPTy));
9439     SDValue Ops1[2] = { Value, Chain };
9440     return DAG.getMergeValues(Ops1, 2, dl);
9441   } else {
9442     SDValue Flag;
9443     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9444
9445     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9446     Flag = Chain.getValue(1);
9447     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9448
9449     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9450     Flag = Chain.getValue(1);
9451
9452     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9453
9454     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9455     return DAG.getMergeValues(Ops1, 2, dl);
9456   }
9457 }
9458
9459 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9460   MachineFunction &MF = DAG.getMachineFunction();
9461   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9462
9463   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9464   DebugLoc DL = Op.getDebugLoc();
9465
9466   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9467     // vastart just stores the address of the VarArgsFrameIndex slot into the
9468     // memory location argument.
9469     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9470                                    getPointerTy());
9471     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9472                         MachinePointerInfo(SV), false, false, 0);
9473   }
9474
9475   // __va_list_tag:
9476   //   gp_offset         (0 - 6 * 8)
9477   //   fp_offset         (48 - 48 + 8 * 16)
9478   //   overflow_arg_area (point to parameters coming in memory).
9479   //   reg_save_area
9480   SmallVector<SDValue, 8> MemOps;
9481   SDValue FIN = Op.getOperand(1);
9482   // Store gp_offset
9483   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9484                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9485                                                MVT::i32),
9486                                FIN, MachinePointerInfo(SV), false, false, 0);
9487   MemOps.push_back(Store);
9488
9489   // Store fp_offset
9490   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9491                     FIN, DAG.getIntPtrConstant(4));
9492   Store = DAG.getStore(Op.getOperand(0), DL,
9493                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9494                                        MVT::i32),
9495                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9496   MemOps.push_back(Store);
9497
9498   // Store ptr to overflow_arg_area
9499   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9500                     FIN, DAG.getIntPtrConstant(4));
9501   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9502                                     getPointerTy());
9503   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9504                        MachinePointerInfo(SV, 8),
9505                        false, false, 0);
9506   MemOps.push_back(Store);
9507
9508   // Store ptr to reg_save_area.
9509   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9510                     FIN, DAG.getIntPtrConstant(8));
9511   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9512                                     getPointerTy());
9513   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9514                        MachinePointerInfo(SV, 16), false, false, 0);
9515   MemOps.push_back(Store);
9516   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9517                      &MemOps[0], MemOps.size());
9518 }
9519
9520 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9521   assert(Subtarget->is64Bit() &&
9522          "LowerVAARG only handles 64-bit va_arg!");
9523   assert((Subtarget->isTargetLinux() ||
9524           Subtarget->isTargetDarwin()) &&
9525           "Unhandled target in LowerVAARG");
9526   assert(Op.getNode()->getNumOperands() == 4);
9527   SDValue Chain = Op.getOperand(0);
9528   SDValue SrcPtr = Op.getOperand(1);
9529   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9530   unsigned Align = Op.getConstantOperandVal(3);
9531   DebugLoc dl = Op.getDebugLoc();
9532
9533   EVT ArgVT = Op.getNode()->getValueType(0);
9534   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9535   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9536   uint8_t ArgMode;
9537
9538   // Decide which area this value should be read from.
9539   // TODO: Implement the AMD64 ABI in its entirety. This simple
9540   // selection mechanism works only for the basic types.
9541   if (ArgVT == MVT::f80) {
9542     llvm_unreachable("va_arg for f80 not yet implemented");
9543   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9544     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9545   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9546     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9547   } else {
9548     llvm_unreachable("Unhandled argument type in LowerVAARG");
9549   }
9550
9551   if (ArgMode == 2) {
9552     // Sanity Check: Make sure using fp_offset makes sense.
9553     assert(!getTargetMachine().Options.UseSoftFloat &&
9554            !(DAG.getMachineFunction()
9555                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9556            Subtarget->hasSSE1());
9557   }
9558
9559   // Insert VAARG_64 node into the DAG
9560   // VAARG_64 returns two values: Variable Argument Address, Chain
9561   SmallVector<SDValue, 11> InstOps;
9562   InstOps.push_back(Chain);
9563   InstOps.push_back(SrcPtr);
9564   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9565   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9566   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9567   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9568   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9569                                           VTs, &InstOps[0], InstOps.size(),
9570                                           MVT::i64,
9571                                           MachinePointerInfo(SV),
9572                                           /*Align=*/0,
9573                                           /*Volatile=*/false,
9574                                           /*ReadMem=*/true,
9575                                           /*WriteMem=*/true);
9576   Chain = VAARG.getValue(1);
9577
9578   // Load the next argument and return it
9579   return DAG.getLoad(ArgVT, dl,
9580                      Chain,
9581                      VAARG,
9582                      MachinePointerInfo(),
9583                      false, false, false, 0);
9584 }
9585
9586 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9587   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9588   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9589   SDValue Chain = Op.getOperand(0);
9590   SDValue DstPtr = Op.getOperand(1);
9591   SDValue SrcPtr = Op.getOperand(2);
9592   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9593   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9594   DebugLoc DL = Op.getDebugLoc();
9595
9596   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9597                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9598                        false,
9599                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9600 }
9601
9602 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9603 // may or may not be a constant. Takes immediate version of shift as input.
9604 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9605                                    SDValue SrcOp, SDValue ShAmt,
9606                                    SelectionDAG &DAG) {
9607   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9608
9609   if (isa<ConstantSDNode>(ShAmt)) {
9610     // Constant may be a TargetConstant. Use a regular constant.
9611     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9612     switch (Opc) {
9613       default: llvm_unreachable("Unknown target vector shift node");
9614       case X86ISD::VSHLI:
9615       case X86ISD::VSRLI:
9616       case X86ISD::VSRAI:
9617         return DAG.getNode(Opc, dl, VT, SrcOp,
9618                            DAG.getConstant(ShiftAmt, MVT::i32));
9619     }
9620   }
9621
9622   // Change opcode to non-immediate version
9623   switch (Opc) {
9624     default: llvm_unreachable("Unknown target vector shift node");
9625     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9626     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9627     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9628   }
9629
9630   // Need to build a vector containing shift amount
9631   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9632   SDValue ShOps[4];
9633   ShOps[0] = ShAmt;
9634   ShOps[1] = DAG.getConstant(0, MVT::i32);
9635   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9636   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9637
9638   // The return type has to be a 128-bit type with the same element
9639   // type as the input type.
9640   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9641   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9642
9643   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9644   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9645 }
9646
9647 SDValue
9648 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9649   DebugLoc dl = Op.getDebugLoc();
9650   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9651   switch (IntNo) {
9652   default: return SDValue();    // Don't custom lower most intrinsics.
9653   // Comparison intrinsics.
9654   case Intrinsic::x86_sse_comieq_ss:
9655   case Intrinsic::x86_sse_comilt_ss:
9656   case Intrinsic::x86_sse_comile_ss:
9657   case Intrinsic::x86_sse_comigt_ss:
9658   case Intrinsic::x86_sse_comige_ss:
9659   case Intrinsic::x86_sse_comineq_ss:
9660   case Intrinsic::x86_sse_ucomieq_ss:
9661   case Intrinsic::x86_sse_ucomilt_ss:
9662   case Intrinsic::x86_sse_ucomile_ss:
9663   case Intrinsic::x86_sse_ucomigt_ss:
9664   case Intrinsic::x86_sse_ucomige_ss:
9665   case Intrinsic::x86_sse_ucomineq_ss:
9666   case Intrinsic::x86_sse2_comieq_sd:
9667   case Intrinsic::x86_sse2_comilt_sd:
9668   case Intrinsic::x86_sse2_comile_sd:
9669   case Intrinsic::x86_sse2_comigt_sd:
9670   case Intrinsic::x86_sse2_comige_sd:
9671   case Intrinsic::x86_sse2_comineq_sd:
9672   case Intrinsic::x86_sse2_ucomieq_sd:
9673   case Intrinsic::x86_sse2_ucomilt_sd:
9674   case Intrinsic::x86_sse2_ucomile_sd:
9675   case Intrinsic::x86_sse2_ucomigt_sd:
9676   case Intrinsic::x86_sse2_ucomige_sd:
9677   case Intrinsic::x86_sse2_ucomineq_sd: {
9678     unsigned Opc;
9679     ISD::CondCode CC;
9680     switch (IntNo) {
9681     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9682     case Intrinsic::x86_sse_comieq_ss:
9683     case Intrinsic::x86_sse2_comieq_sd:
9684       Opc = X86ISD::COMI;
9685       CC = ISD::SETEQ;
9686       break;
9687     case Intrinsic::x86_sse_comilt_ss:
9688     case Intrinsic::x86_sse2_comilt_sd:
9689       Opc = X86ISD::COMI;
9690       CC = ISD::SETLT;
9691       break;
9692     case Intrinsic::x86_sse_comile_ss:
9693     case Intrinsic::x86_sse2_comile_sd:
9694       Opc = X86ISD::COMI;
9695       CC = ISD::SETLE;
9696       break;
9697     case Intrinsic::x86_sse_comigt_ss:
9698     case Intrinsic::x86_sse2_comigt_sd:
9699       Opc = X86ISD::COMI;
9700       CC = ISD::SETGT;
9701       break;
9702     case Intrinsic::x86_sse_comige_ss:
9703     case Intrinsic::x86_sse2_comige_sd:
9704       Opc = X86ISD::COMI;
9705       CC = ISD::SETGE;
9706       break;
9707     case Intrinsic::x86_sse_comineq_ss:
9708     case Intrinsic::x86_sse2_comineq_sd:
9709       Opc = X86ISD::COMI;
9710       CC = ISD::SETNE;
9711       break;
9712     case Intrinsic::x86_sse_ucomieq_ss:
9713     case Intrinsic::x86_sse2_ucomieq_sd:
9714       Opc = X86ISD::UCOMI;
9715       CC = ISD::SETEQ;
9716       break;
9717     case Intrinsic::x86_sse_ucomilt_ss:
9718     case Intrinsic::x86_sse2_ucomilt_sd:
9719       Opc = X86ISD::UCOMI;
9720       CC = ISD::SETLT;
9721       break;
9722     case Intrinsic::x86_sse_ucomile_ss:
9723     case Intrinsic::x86_sse2_ucomile_sd:
9724       Opc = X86ISD::UCOMI;
9725       CC = ISD::SETLE;
9726       break;
9727     case Intrinsic::x86_sse_ucomigt_ss:
9728     case Intrinsic::x86_sse2_ucomigt_sd:
9729       Opc = X86ISD::UCOMI;
9730       CC = ISD::SETGT;
9731       break;
9732     case Intrinsic::x86_sse_ucomige_ss:
9733     case Intrinsic::x86_sse2_ucomige_sd:
9734       Opc = X86ISD::UCOMI;
9735       CC = ISD::SETGE;
9736       break;
9737     case Intrinsic::x86_sse_ucomineq_ss:
9738     case Intrinsic::x86_sse2_ucomineq_sd:
9739       Opc = X86ISD::UCOMI;
9740       CC = ISD::SETNE;
9741       break;
9742     }
9743
9744     SDValue LHS = Op.getOperand(1);
9745     SDValue RHS = Op.getOperand(2);
9746     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9747     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9748     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9749     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9750                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9751     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9752   }
9753
9754   // Arithmetic intrinsics.
9755   case Intrinsic::x86_sse2_pmulu_dq:
9756   case Intrinsic::x86_avx2_pmulu_dq:
9757     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9758                        Op.getOperand(1), Op.getOperand(2));
9759
9760   // SSE3/AVX horizontal add/sub intrinsics
9761   case Intrinsic::x86_sse3_hadd_ps:
9762   case Intrinsic::x86_sse3_hadd_pd:
9763   case Intrinsic::x86_avx_hadd_ps_256:
9764   case Intrinsic::x86_avx_hadd_pd_256:
9765   case Intrinsic::x86_sse3_hsub_ps:
9766   case Intrinsic::x86_sse3_hsub_pd:
9767   case Intrinsic::x86_avx_hsub_ps_256:
9768   case Intrinsic::x86_avx_hsub_pd_256:
9769   case Intrinsic::x86_ssse3_phadd_w_128:
9770   case Intrinsic::x86_ssse3_phadd_d_128:
9771   case Intrinsic::x86_avx2_phadd_w:
9772   case Intrinsic::x86_avx2_phadd_d:
9773   case Intrinsic::x86_ssse3_phsub_w_128:
9774   case Intrinsic::x86_ssse3_phsub_d_128:
9775   case Intrinsic::x86_avx2_phsub_w:
9776   case Intrinsic::x86_avx2_phsub_d: {
9777     unsigned Opcode;
9778     switch (IntNo) {
9779     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9780     case Intrinsic::x86_sse3_hadd_ps:
9781     case Intrinsic::x86_sse3_hadd_pd:
9782     case Intrinsic::x86_avx_hadd_ps_256:
9783     case Intrinsic::x86_avx_hadd_pd_256:
9784       Opcode = X86ISD::FHADD;
9785       break;
9786     case Intrinsic::x86_sse3_hsub_ps:
9787     case Intrinsic::x86_sse3_hsub_pd:
9788     case Intrinsic::x86_avx_hsub_ps_256:
9789     case Intrinsic::x86_avx_hsub_pd_256:
9790       Opcode = X86ISD::FHSUB;
9791       break;
9792     case Intrinsic::x86_ssse3_phadd_w_128:
9793     case Intrinsic::x86_ssse3_phadd_d_128:
9794     case Intrinsic::x86_avx2_phadd_w:
9795     case Intrinsic::x86_avx2_phadd_d:
9796       Opcode = X86ISD::HADD;
9797       break;
9798     case Intrinsic::x86_ssse3_phsub_w_128:
9799     case Intrinsic::x86_ssse3_phsub_d_128:
9800     case Intrinsic::x86_avx2_phsub_w:
9801     case Intrinsic::x86_avx2_phsub_d:
9802       Opcode = X86ISD::HSUB;
9803       break;
9804     }
9805     return DAG.getNode(Opcode, dl, Op.getValueType(),
9806                        Op.getOperand(1), Op.getOperand(2));
9807   }
9808
9809   // AVX2 variable shift intrinsics
9810   case Intrinsic::x86_avx2_psllv_d:
9811   case Intrinsic::x86_avx2_psllv_q:
9812   case Intrinsic::x86_avx2_psllv_d_256:
9813   case Intrinsic::x86_avx2_psllv_q_256:
9814   case Intrinsic::x86_avx2_psrlv_d:
9815   case Intrinsic::x86_avx2_psrlv_q:
9816   case Intrinsic::x86_avx2_psrlv_d_256:
9817   case Intrinsic::x86_avx2_psrlv_q_256:
9818   case Intrinsic::x86_avx2_psrav_d:
9819   case Intrinsic::x86_avx2_psrav_d_256: {
9820     unsigned Opcode;
9821     switch (IntNo) {
9822     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9823     case Intrinsic::x86_avx2_psllv_d:
9824     case Intrinsic::x86_avx2_psllv_q:
9825     case Intrinsic::x86_avx2_psllv_d_256:
9826     case Intrinsic::x86_avx2_psllv_q_256:
9827       Opcode = ISD::SHL;
9828       break;
9829     case Intrinsic::x86_avx2_psrlv_d:
9830     case Intrinsic::x86_avx2_psrlv_q:
9831     case Intrinsic::x86_avx2_psrlv_d_256:
9832     case Intrinsic::x86_avx2_psrlv_q_256:
9833       Opcode = ISD::SRL;
9834       break;
9835     case Intrinsic::x86_avx2_psrav_d:
9836     case Intrinsic::x86_avx2_psrav_d_256:
9837       Opcode = ISD::SRA;
9838       break;
9839     }
9840     return DAG.getNode(Opcode, dl, Op.getValueType(),
9841                        Op.getOperand(1), Op.getOperand(2));
9842   }
9843
9844   case Intrinsic::x86_ssse3_pshuf_b_128:
9845   case Intrinsic::x86_avx2_pshuf_b:
9846     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9847                        Op.getOperand(1), Op.getOperand(2));
9848
9849   case Intrinsic::x86_ssse3_psign_b_128:
9850   case Intrinsic::x86_ssse3_psign_w_128:
9851   case Intrinsic::x86_ssse3_psign_d_128:
9852   case Intrinsic::x86_avx2_psign_b:
9853   case Intrinsic::x86_avx2_psign_w:
9854   case Intrinsic::x86_avx2_psign_d:
9855     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9856                        Op.getOperand(1), Op.getOperand(2));
9857
9858   case Intrinsic::x86_sse41_insertps:
9859     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9860                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9861
9862   case Intrinsic::x86_avx_vperm2f128_ps_256:
9863   case Intrinsic::x86_avx_vperm2f128_pd_256:
9864   case Intrinsic::x86_avx_vperm2f128_si_256:
9865   case Intrinsic::x86_avx2_vperm2i128:
9866     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9867                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9868
9869   case Intrinsic::x86_avx2_permd:
9870   case Intrinsic::x86_avx2_permps:
9871     // Operands intentionally swapped. Mask is last operand to intrinsic,
9872     // but second operand for node/intruction.
9873     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9874                        Op.getOperand(2), Op.getOperand(1));
9875
9876   // ptest and testp intrinsics. The intrinsic these come from are designed to
9877   // return an integer value, not just an instruction so lower it to the ptest
9878   // or testp pattern and a setcc for the result.
9879   case Intrinsic::x86_sse41_ptestz:
9880   case Intrinsic::x86_sse41_ptestc:
9881   case Intrinsic::x86_sse41_ptestnzc:
9882   case Intrinsic::x86_avx_ptestz_256:
9883   case Intrinsic::x86_avx_ptestc_256:
9884   case Intrinsic::x86_avx_ptestnzc_256:
9885   case Intrinsic::x86_avx_vtestz_ps:
9886   case Intrinsic::x86_avx_vtestc_ps:
9887   case Intrinsic::x86_avx_vtestnzc_ps:
9888   case Intrinsic::x86_avx_vtestz_pd:
9889   case Intrinsic::x86_avx_vtestc_pd:
9890   case Intrinsic::x86_avx_vtestnzc_pd:
9891   case Intrinsic::x86_avx_vtestz_ps_256:
9892   case Intrinsic::x86_avx_vtestc_ps_256:
9893   case Intrinsic::x86_avx_vtestnzc_ps_256:
9894   case Intrinsic::x86_avx_vtestz_pd_256:
9895   case Intrinsic::x86_avx_vtestc_pd_256:
9896   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9897     bool IsTestPacked = false;
9898     unsigned X86CC;
9899     switch (IntNo) {
9900     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9901     case Intrinsic::x86_avx_vtestz_ps:
9902     case Intrinsic::x86_avx_vtestz_pd:
9903     case Intrinsic::x86_avx_vtestz_ps_256:
9904     case Intrinsic::x86_avx_vtestz_pd_256:
9905       IsTestPacked = true; // Fallthrough
9906     case Intrinsic::x86_sse41_ptestz:
9907     case Intrinsic::x86_avx_ptestz_256:
9908       // ZF = 1
9909       X86CC = X86::COND_E;
9910       break;
9911     case Intrinsic::x86_avx_vtestc_ps:
9912     case Intrinsic::x86_avx_vtestc_pd:
9913     case Intrinsic::x86_avx_vtestc_ps_256:
9914     case Intrinsic::x86_avx_vtestc_pd_256:
9915       IsTestPacked = true; // Fallthrough
9916     case Intrinsic::x86_sse41_ptestc:
9917     case Intrinsic::x86_avx_ptestc_256:
9918       // CF = 1
9919       X86CC = X86::COND_B;
9920       break;
9921     case Intrinsic::x86_avx_vtestnzc_ps:
9922     case Intrinsic::x86_avx_vtestnzc_pd:
9923     case Intrinsic::x86_avx_vtestnzc_ps_256:
9924     case Intrinsic::x86_avx_vtestnzc_pd_256:
9925       IsTestPacked = true; // Fallthrough
9926     case Intrinsic::x86_sse41_ptestnzc:
9927     case Intrinsic::x86_avx_ptestnzc_256:
9928       // ZF and CF = 0
9929       X86CC = X86::COND_A;
9930       break;
9931     }
9932
9933     SDValue LHS = Op.getOperand(1);
9934     SDValue RHS = Op.getOperand(2);
9935     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9936     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9937     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9938     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9939     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9940   }
9941
9942   // SSE/AVX shift intrinsics
9943   case Intrinsic::x86_sse2_psll_w:
9944   case Intrinsic::x86_sse2_psll_d:
9945   case Intrinsic::x86_sse2_psll_q:
9946   case Intrinsic::x86_avx2_psll_w:
9947   case Intrinsic::x86_avx2_psll_d:
9948   case Intrinsic::x86_avx2_psll_q:
9949   case Intrinsic::x86_sse2_psrl_w:
9950   case Intrinsic::x86_sse2_psrl_d:
9951   case Intrinsic::x86_sse2_psrl_q:
9952   case Intrinsic::x86_avx2_psrl_w:
9953   case Intrinsic::x86_avx2_psrl_d:
9954   case Intrinsic::x86_avx2_psrl_q:
9955   case Intrinsic::x86_sse2_psra_w:
9956   case Intrinsic::x86_sse2_psra_d:
9957   case Intrinsic::x86_avx2_psra_w:
9958   case Intrinsic::x86_avx2_psra_d: {
9959     unsigned Opcode;
9960     switch (IntNo) {
9961     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9962     case Intrinsic::x86_sse2_psll_w:
9963     case Intrinsic::x86_sse2_psll_d:
9964     case Intrinsic::x86_sse2_psll_q:
9965     case Intrinsic::x86_avx2_psll_w:
9966     case Intrinsic::x86_avx2_psll_d:
9967     case Intrinsic::x86_avx2_psll_q:
9968       Opcode = X86ISD::VSHL;
9969       break;
9970     case Intrinsic::x86_sse2_psrl_w:
9971     case Intrinsic::x86_sse2_psrl_d:
9972     case Intrinsic::x86_sse2_psrl_q:
9973     case Intrinsic::x86_avx2_psrl_w:
9974     case Intrinsic::x86_avx2_psrl_d:
9975     case Intrinsic::x86_avx2_psrl_q:
9976       Opcode = X86ISD::VSRL;
9977       break;
9978     case Intrinsic::x86_sse2_psra_w:
9979     case Intrinsic::x86_sse2_psra_d:
9980     case Intrinsic::x86_avx2_psra_w:
9981     case Intrinsic::x86_avx2_psra_d:
9982       Opcode = X86ISD::VSRA;
9983       break;
9984     }
9985     return DAG.getNode(Opcode, dl, Op.getValueType(),
9986                        Op.getOperand(1), Op.getOperand(2));
9987   }
9988
9989   // SSE/AVX immediate shift intrinsics
9990   case Intrinsic::x86_sse2_pslli_w:
9991   case Intrinsic::x86_sse2_pslli_d:
9992   case Intrinsic::x86_sse2_pslli_q:
9993   case Intrinsic::x86_avx2_pslli_w:
9994   case Intrinsic::x86_avx2_pslli_d:
9995   case Intrinsic::x86_avx2_pslli_q:
9996   case Intrinsic::x86_sse2_psrli_w:
9997   case Intrinsic::x86_sse2_psrli_d:
9998   case Intrinsic::x86_sse2_psrli_q:
9999   case Intrinsic::x86_avx2_psrli_w:
10000   case Intrinsic::x86_avx2_psrli_d:
10001   case Intrinsic::x86_avx2_psrli_q:
10002   case Intrinsic::x86_sse2_psrai_w:
10003   case Intrinsic::x86_sse2_psrai_d:
10004   case Intrinsic::x86_avx2_psrai_w:
10005   case Intrinsic::x86_avx2_psrai_d: {
10006     unsigned Opcode;
10007     switch (IntNo) {
10008     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10009     case Intrinsic::x86_sse2_pslli_w:
10010     case Intrinsic::x86_sse2_pslli_d:
10011     case Intrinsic::x86_sse2_pslli_q:
10012     case Intrinsic::x86_avx2_pslli_w:
10013     case Intrinsic::x86_avx2_pslli_d:
10014     case Intrinsic::x86_avx2_pslli_q:
10015       Opcode = X86ISD::VSHLI;
10016       break;
10017     case Intrinsic::x86_sse2_psrli_w:
10018     case Intrinsic::x86_sse2_psrli_d:
10019     case Intrinsic::x86_sse2_psrli_q:
10020     case Intrinsic::x86_avx2_psrli_w:
10021     case Intrinsic::x86_avx2_psrli_d:
10022     case Intrinsic::x86_avx2_psrli_q:
10023       Opcode = X86ISD::VSRLI;
10024       break;
10025     case Intrinsic::x86_sse2_psrai_w:
10026     case Intrinsic::x86_sse2_psrai_d:
10027     case Intrinsic::x86_avx2_psrai_w:
10028     case Intrinsic::x86_avx2_psrai_d:
10029       Opcode = X86ISD::VSRAI;
10030       break;
10031     }
10032     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10033                                Op.getOperand(1), Op.getOperand(2), DAG);
10034   }
10035
10036   case Intrinsic::x86_sse42_pcmpistria128:
10037   case Intrinsic::x86_sse42_pcmpestria128:
10038   case Intrinsic::x86_sse42_pcmpistric128:
10039   case Intrinsic::x86_sse42_pcmpestric128:
10040   case Intrinsic::x86_sse42_pcmpistrio128:
10041   case Intrinsic::x86_sse42_pcmpestrio128:
10042   case Intrinsic::x86_sse42_pcmpistris128:
10043   case Intrinsic::x86_sse42_pcmpestris128:
10044   case Intrinsic::x86_sse42_pcmpistriz128:
10045   case Intrinsic::x86_sse42_pcmpestriz128: {
10046     unsigned Opcode;
10047     unsigned X86CC;
10048     switch (IntNo) {
10049     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10050     case Intrinsic::x86_sse42_pcmpistria128:
10051       Opcode = X86ISD::PCMPISTRI;
10052       X86CC = X86::COND_A;
10053       break;
10054     case Intrinsic::x86_sse42_pcmpestria128:
10055       Opcode = X86ISD::PCMPESTRI;
10056       X86CC = X86::COND_A;
10057       break;
10058     case Intrinsic::x86_sse42_pcmpistric128:
10059       Opcode = X86ISD::PCMPISTRI;
10060       X86CC = X86::COND_B;
10061       break;
10062     case Intrinsic::x86_sse42_pcmpestric128:
10063       Opcode = X86ISD::PCMPESTRI;
10064       X86CC = X86::COND_B;
10065       break;
10066     case Intrinsic::x86_sse42_pcmpistrio128:
10067       Opcode = X86ISD::PCMPISTRI;
10068       X86CC = X86::COND_O;
10069       break;
10070     case Intrinsic::x86_sse42_pcmpestrio128:
10071       Opcode = X86ISD::PCMPESTRI;
10072       X86CC = X86::COND_O;
10073       break;
10074     case Intrinsic::x86_sse42_pcmpistris128:
10075       Opcode = X86ISD::PCMPISTRI;
10076       X86CC = X86::COND_S;
10077       break;
10078     case Intrinsic::x86_sse42_pcmpestris128:
10079       Opcode = X86ISD::PCMPESTRI;
10080       X86CC = X86::COND_S;
10081       break;
10082     case Intrinsic::x86_sse42_pcmpistriz128:
10083       Opcode = X86ISD::PCMPISTRI;
10084       X86CC = X86::COND_E;
10085       break;
10086     case Intrinsic::x86_sse42_pcmpestriz128:
10087       Opcode = X86ISD::PCMPESTRI;
10088       X86CC = X86::COND_E;
10089       break;
10090     }
10091     SmallVector<SDValue, 5> NewOps;
10092     NewOps.append(Op->op_begin()+1, Op->op_end());
10093     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10094     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10095     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10096                                 DAG.getConstant(X86CC, MVT::i8),
10097                                 SDValue(PCMP.getNode(), 1));
10098     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10099   }
10100
10101   case Intrinsic::x86_sse42_pcmpistri128:
10102   case Intrinsic::x86_sse42_pcmpestri128: {
10103     unsigned Opcode;
10104     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10105       Opcode = X86ISD::PCMPISTRI;
10106     else
10107       Opcode = X86ISD::PCMPESTRI;
10108
10109     SmallVector<SDValue, 5> NewOps;
10110     NewOps.append(Op->op_begin()+1, Op->op_end());
10111     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10112     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10113   }
10114   case Intrinsic::x86_fma_vfmadd_ps:
10115   case Intrinsic::x86_fma_vfmadd_pd:
10116   case Intrinsic::x86_fma_vfmsub_ps:
10117   case Intrinsic::x86_fma_vfmsub_pd:
10118   case Intrinsic::x86_fma_vfnmadd_ps:
10119   case Intrinsic::x86_fma_vfnmadd_pd:
10120   case Intrinsic::x86_fma_vfnmsub_ps:
10121   case Intrinsic::x86_fma_vfnmsub_pd:
10122   case Intrinsic::x86_fma_vfmaddsub_ps:
10123   case Intrinsic::x86_fma_vfmaddsub_pd:
10124   case Intrinsic::x86_fma_vfmsubadd_ps:
10125   case Intrinsic::x86_fma_vfmsubadd_pd:
10126   case Intrinsic::x86_fma_vfmadd_ps_256:
10127   case Intrinsic::x86_fma_vfmadd_pd_256:
10128   case Intrinsic::x86_fma_vfmsub_ps_256:
10129   case Intrinsic::x86_fma_vfmsub_pd_256:
10130   case Intrinsic::x86_fma_vfnmadd_ps_256:
10131   case Intrinsic::x86_fma_vfnmadd_pd_256:
10132   case Intrinsic::x86_fma_vfnmsub_ps_256:
10133   case Intrinsic::x86_fma_vfnmsub_pd_256:
10134   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10135   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10136   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10137   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10138     unsigned Opc;
10139     switch (IntNo) {
10140     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10141     case Intrinsic::x86_fma_vfmadd_ps:
10142     case Intrinsic::x86_fma_vfmadd_pd:
10143     case Intrinsic::x86_fma_vfmadd_ps_256:
10144     case Intrinsic::x86_fma_vfmadd_pd_256:
10145       Opc = X86ISD::FMADD;
10146       break;
10147     case Intrinsic::x86_fma_vfmsub_ps:
10148     case Intrinsic::x86_fma_vfmsub_pd:
10149     case Intrinsic::x86_fma_vfmsub_ps_256:
10150     case Intrinsic::x86_fma_vfmsub_pd_256:
10151       Opc = X86ISD::FMSUB;
10152       break;
10153     case Intrinsic::x86_fma_vfnmadd_ps:
10154     case Intrinsic::x86_fma_vfnmadd_pd:
10155     case Intrinsic::x86_fma_vfnmadd_ps_256:
10156     case Intrinsic::x86_fma_vfnmadd_pd_256:
10157       Opc = X86ISD::FNMADD;
10158       break;
10159     case Intrinsic::x86_fma_vfnmsub_ps:
10160     case Intrinsic::x86_fma_vfnmsub_pd:
10161     case Intrinsic::x86_fma_vfnmsub_ps_256:
10162     case Intrinsic::x86_fma_vfnmsub_pd_256:
10163       Opc = X86ISD::FNMSUB;
10164       break;
10165     case Intrinsic::x86_fma_vfmaddsub_ps:
10166     case Intrinsic::x86_fma_vfmaddsub_pd:
10167     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10168     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10169       Opc = X86ISD::FMADDSUB;
10170       break;
10171     case Intrinsic::x86_fma_vfmsubadd_ps:
10172     case Intrinsic::x86_fma_vfmsubadd_pd:
10173     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10174     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10175       Opc = X86ISD::FMSUBADD;
10176       break;
10177     }
10178
10179     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10180                        Op.getOperand(2), Op.getOperand(3));
10181   }
10182   }
10183 }
10184
10185 SDValue
10186 X86TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) const {
10187   DebugLoc dl = Op.getDebugLoc();
10188   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10189   switch (IntNo) {
10190   default: return SDValue();    // Don't custom lower most intrinsics.
10191
10192   // RDRAND intrinsics.
10193   case Intrinsic::x86_rdrand_16:
10194   case Intrinsic::x86_rdrand_32:
10195   case Intrinsic::x86_rdrand_64: {
10196     // Emit the node with the right value type.
10197     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10198     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10199
10200     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10201     // return the value from Rand, which is always 0, casted to i32.
10202     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10203                       DAG.getConstant(1, Op->getValueType(1)),
10204                       DAG.getConstant(X86::COND_B, MVT::i32),
10205                       SDValue(Result.getNode(), 1) };
10206     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10207                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10208                                   Ops, 4);
10209
10210     // Return { result, isValid, chain }.
10211     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10212                        SDValue(Result.getNode(), 2));
10213   }
10214   }
10215 }
10216
10217 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10218                                            SelectionDAG &DAG) const {
10219   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10220   MFI->setReturnAddressIsTaken(true);
10221
10222   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10223   DebugLoc dl = Op.getDebugLoc();
10224
10225   if (Depth > 0) {
10226     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10227     SDValue Offset =
10228       DAG.getConstant(TD->getPointerSize(),
10229                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10230     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10231                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
10232                                    FrameAddr, Offset),
10233                        MachinePointerInfo(), false, false, false, 0);
10234   }
10235
10236   // Just load the return address.
10237   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10238   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10239                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10240 }
10241
10242 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10243   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10244   MFI->setFrameAddressIsTaken(true);
10245
10246   EVT VT = Op.getValueType();
10247   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10248   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10249   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10250   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10251   while (Depth--)
10252     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10253                             MachinePointerInfo(),
10254                             false, false, false, 0);
10255   return FrameAddr;
10256 }
10257
10258 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10259                                                      SelectionDAG &DAG) const {
10260   return DAG.getIntPtrConstant(2*TD->getPointerSize());
10261 }
10262
10263 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10264   SDValue Chain     = Op.getOperand(0);
10265   SDValue Offset    = Op.getOperand(1);
10266   SDValue Handler   = Op.getOperand(2);
10267   DebugLoc dl       = Op.getDebugLoc();
10268
10269   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10270                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10271                                      getPointerTy());
10272   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10273
10274   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10275                                   DAG.getIntPtrConstant(TD->getPointerSize()));
10276   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10277   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10278                        false, false, 0);
10279   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10280
10281   return DAG.getNode(X86ISD::EH_RETURN, dl,
10282                      MVT::Other,
10283                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10284 }
10285
10286 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
10287                                                   SelectionDAG &DAG) const {
10288   return Op.getOperand(0);
10289 }
10290
10291 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10292                                                 SelectionDAG &DAG) const {
10293   SDValue Root = Op.getOperand(0);
10294   SDValue Trmp = Op.getOperand(1); // trampoline
10295   SDValue FPtr = Op.getOperand(2); // nested function
10296   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10297   DebugLoc dl  = Op.getDebugLoc();
10298
10299   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10300
10301   if (Subtarget->is64Bit()) {
10302     SDValue OutChains[6];
10303
10304     // Large code-model.
10305     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
10306     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10307
10308     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
10309     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10310
10311     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10312
10313     // Load the pointer to the nested function into R11.
10314     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10315     SDValue Addr = Trmp;
10316     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10317                                 Addr, MachinePointerInfo(TrmpAddr),
10318                                 false, false, 0);
10319
10320     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10321                        DAG.getConstant(2, MVT::i64));
10322     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10323                                 MachinePointerInfo(TrmpAddr, 2),
10324                                 false, false, 2);
10325
10326     // Load the 'nest' parameter value into R10.
10327     // R10 is specified in X86CallingConv.td
10328     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10329     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10330                        DAG.getConstant(10, MVT::i64));
10331     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10332                                 Addr, MachinePointerInfo(TrmpAddr, 10),
10333                                 false, false, 0);
10334
10335     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10336                        DAG.getConstant(12, MVT::i64));
10337     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10338                                 MachinePointerInfo(TrmpAddr, 12),
10339                                 false, false, 2);
10340
10341     // Jump to the nested function.
10342     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10343     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10344                        DAG.getConstant(20, MVT::i64));
10345     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10346                                 Addr, MachinePointerInfo(TrmpAddr, 20),
10347                                 false, false, 0);
10348
10349     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10350     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10351                        DAG.getConstant(22, MVT::i64));
10352     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10353                                 MachinePointerInfo(TrmpAddr, 22),
10354                                 false, false, 0);
10355
10356     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10357   } else {
10358     const Function *Func =
10359       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10360     CallingConv::ID CC = Func->getCallingConv();
10361     unsigned NestReg;
10362
10363     switch (CC) {
10364     default:
10365       llvm_unreachable("Unsupported calling convention");
10366     case CallingConv::C:
10367     case CallingConv::X86_StdCall: {
10368       // Pass 'nest' parameter in ECX.
10369       // Must be kept in sync with X86CallingConv.td
10370       NestReg = X86::ECX;
10371
10372       // Check that ECX wasn't needed by an 'inreg' parameter.
10373       FunctionType *FTy = Func->getFunctionType();
10374       const AttrListPtr &Attrs = Func->getAttributes();
10375
10376       if (!Attrs.isEmpty() && !Func->isVarArg()) {
10377         unsigned InRegCount = 0;
10378         unsigned Idx = 1;
10379
10380         for (FunctionType::param_iterator I = FTy->param_begin(),
10381              E = FTy->param_end(); I != E; ++I, ++Idx)
10382           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10383             // FIXME: should only count parameters that are lowered to integers.
10384             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10385
10386         if (InRegCount > 2) {
10387           report_fatal_error("Nest register in use - reduce number of inreg"
10388                              " parameters!");
10389         }
10390       }
10391       break;
10392     }
10393     case CallingConv::X86_FastCall:
10394     case CallingConv::X86_ThisCall:
10395     case CallingConv::Fast:
10396       // Pass 'nest' parameter in EAX.
10397       // Must be kept in sync with X86CallingConv.td
10398       NestReg = X86::EAX;
10399       break;
10400     }
10401
10402     SDValue OutChains[4];
10403     SDValue Addr, Disp;
10404
10405     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10406                        DAG.getConstant(10, MVT::i32));
10407     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10408
10409     // This is storing the opcode for MOV32ri.
10410     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10411     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10412     OutChains[0] = DAG.getStore(Root, dl,
10413                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10414                                 Trmp, MachinePointerInfo(TrmpAddr),
10415                                 false, false, 0);
10416
10417     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10418                        DAG.getConstant(1, MVT::i32));
10419     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10420                                 MachinePointerInfo(TrmpAddr, 1),
10421                                 false, false, 1);
10422
10423     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10424     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10425                        DAG.getConstant(5, MVT::i32));
10426     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10427                                 MachinePointerInfo(TrmpAddr, 5),
10428                                 false, false, 1);
10429
10430     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10431                        DAG.getConstant(6, MVT::i32));
10432     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10433                                 MachinePointerInfo(TrmpAddr, 6),
10434                                 false, false, 1);
10435
10436     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10437   }
10438 }
10439
10440 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10441                                             SelectionDAG &DAG) const {
10442   /*
10443    The rounding mode is in bits 11:10 of FPSR, and has the following
10444    settings:
10445      00 Round to nearest
10446      01 Round to -inf
10447      10 Round to +inf
10448      11 Round to 0
10449
10450   FLT_ROUNDS, on the other hand, expects the following:
10451     -1 Undefined
10452      0 Round to 0
10453      1 Round to nearest
10454      2 Round to +inf
10455      3 Round to -inf
10456
10457   To perform the conversion, we do:
10458     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10459   */
10460
10461   MachineFunction &MF = DAG.getMachineFunction();
10462   const TargetMachine &TM = MF.getTarget();
10463   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10464   unsigned StackAlignment = TFI.getStackAlignment();
10465   EVT VT = Op.getValueType();
10466   DebugLoc DL = Op.getDebugLoc();
10467
10468   // Save FP Control Word to stack slot
10469   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10470   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10471
10472
10473   MachineMemOperand *MMO =
10474    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10475                            MachineMemOperand::MOStore, 2, 2);
10476
10477   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10478   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10479                                           DAG.getVTList(MVT::Other),
10480                                           Ops, 2, MVT::i16, MMO);
10481
10482   // Load FP Control Word from stack slot
10483   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10484                             MachinePointerInfo(), false, false, false, 0);
10485
10486   // Transform as necessary
10487   SDValue CWD1 =
10488     DAG.getNode(ISD::SRL, DL, MVT::i16,
10489                 DAG.getNode(ISD::AND, DL, MVT::i16,
10490                             CWD, DAG.getConstant(0x800, MVT::i16)),
10491                 DAG.getConstant(11, MVT::i8));
10492   SDValue CWD2 =
10493     DAG.getNode(ISD::SRL, DL, MVT::i16,
10494                 DAG.getNode(ISD::AND, DL, MVT::i16,
10495                             CWD, DAG.getConstant(0x400, MVT::i16)),
10496                 DAG.getConstant(9, MVT::i8));
10497
10498   SDValue RetVal =
10499     DAG.getNode(ISD::AND, DL, MVT::i16,
10500                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10501                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10502                             DAG.getConstant(1, MVT::i16)),
10503                 DAG.getConstant(3, MVT::i16));
10504
10505
10506   return DAG.getNode((VT.getSizeInBits() < 16 ?
10507                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10508 }
10509
10510 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10511   EVT VT = Op.getValueType();
10512   EVT OpVT = VT;
10513   unsigned NumBits = VT.getSizeInBits();
10514   DebugLoc dl = Op.getDebugLoc();
10515
10516   Op = Op.getOperand(0);
10517   if (VT == MVT::i8) {
10518     // Zero extend to i32 since there is not an i8 bsr.
10519     OpVT = MVT::i32;
10520     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10521   }
10522
10523   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10524   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10525   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10526
10527   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10528   SDValue Ops[] = {
10529     Op,
10530     DAG.getConstant(NumBits+NumBits-1, OpVT),
10531     DAG.getConstant(X86::COND_E, MVT::i8),
10532     Op.getValue(1)
10533   };
10534   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10535
10536   // Finally xor with NumBits-1.
10537   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10538
10539   if (VT == MVT::i8)
10540     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10541   return Op;
10542 }
10543
10544 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10545                                                 SelectionDAG &DAG) const {
10546   EVT VT = Op.getValueType();
10547   EVT OpVT = VT;
10548   unsigned NumBits = VT.getSizeInBits();
10549   DebugLoc dl = Op.getDebugLoc();
10550
10551   Op = Op.getOperand(0);
10552   if (VT == MVT::i8) {
10553     // Zero extend to i32 since there is not an i8 bsr.
10554     OpVT = MVT::i32;
10555     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10556   }
10557
10558   // Issue a bsr (scan bits in reverse).
10559   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10560   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10561
10562   // And xor with NumBits-1.
10563   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10564
10565   if (VT == MVT::i8)
10566     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10567   return Op;
10568 }
10569
10570 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10571   EVT VT = Op.getValueType();
10572   unsigned NumBits = VT.getSizeInBits();
10573   DebugLoc dl = Op.getDebugLoc();
10574   Op = Op.getOperand(0);
10575
10576   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10577   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10578   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10579
10580   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10581   SDValue Ops[] = {
10582     Op,
10583     DAG.getConstant(NumBits, VT),
10584     DAG.getConstant(X86::COND_E, MVT::i8),
10585     Op.getValue(1)
10586   };
10587   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10588 }
10589
10590 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10591 // ones, and then concatenate the result back.
10592 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10593   EVT VT = Op.getValueType();
10594
10595   assert(VT.is256BitVector() && VT.isInteger() &&
10596          "Unsupported value type for operation");
10597
10598   unsigned NumElems = VT.getVectorNumElements();
10599   DebugLoc dl = Op.getDebugLoc();
10600
10601   // Extract the LHS vectors
10602   SDValue LHS = Op.getOperand(0);
10603   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10604   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10605
10606   // Extract the RHS vectors
10607   SDValue RHS = Op.getOperand(1);
10608   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10609   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10610
10611   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10612   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10613
10614   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10615                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10616                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10617 }
10618
10619 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10620   assert(Op.getValueType().is256BitVector() &&
10621          Op.getValueType().isInteger() &&
10622          "Only handle AVX 256-bit vector integer operation");
10623   return Lower256IntArith(Op, DAG);
10624 }
10625
10626 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10627   assert(Op.getValueType().is256BitVector() &&
10628          Op.getValueType().isInteger() &&
10629          "Only handle AVX 256-bit vector integer operation");
10630   return Lower256IntArith(Op, DAG);
10631 }
10632
10633 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10634   EVT VT = Op.getValueType();
10635
10636   // Decompose 256-bit ops into smaller 128-bit ops.
10637   if (VT.is256BitVector() && !Subtarget->hasAVX2())
10638     return Lower256IntArith(Op, DAG);
10639
10640   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10641          "Only know how to lower V2I64/V4I64 multiply");
10642
10643   DebugLoc dl = Op.getDebugLoc();
10644
10645   //  Ahi = psrlqi(a, 32);
10646   //  Bhi = psrlqi(b, 32);
10647   //
10648   //  AloBlo = pmuludq(a, b);
10649   //  AloBhi = pmuludq(a, Bhi);
10650   //  AhiBlo = pmuludq(Ahi, b);
10651
10652   //  AloBhi = psllqi(AloBhi, 32);
10653   //  AhiBlo = psllqi(AhiBlo, 32);
10654   //  return AloBlo + AloBhi + AhiBlo;
10655
10656   SDValue A = Op.getOperand(0);
10657   SDValue B = Op.getOperand(1);
10658
10659   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10660
10661   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10662   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10663
10664   // Bit cast to 32-bit vectors for MULUDQ
10665   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10666   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10667   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10668   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10669   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10670
10671   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10672   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10673   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10674
10675   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10676   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10677
10678   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10679   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10680 }
10681
10682 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10683
10684   EVT VT = Op.getValueType();
10685   DebugLoc dl = Op.getDebugLoc();
10686   SDValue R = Op.getOperand(0);
10687   SDValue Amt = Op.getOperand(1);
10688   LLVMContext *Context = DAG.getContext();
10689
10690   if (!Subtarget->hasSSE2())
10691     return SDValue();
10692
10693   // Optimize shl/srl/sra with constant shift amount.
10694   if (isSplatVector(Amt.getNode())) {
10695     SDValue SclrAmt = Amt->getOperand(0);
10696     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10697       uint64_t ShiftAmt = C->getZExtValue();
10698
10699       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10700           (Subtarget->hasAVX2() &&
10701            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10702         if (Op.getOpcode() == ISD::SHL)
10703           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10704                              DAG.getConstant(ShiftAmt, MVT::i32));
10705         if (Op.getOpcode() == ISD::SRL)
10706           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10707                              DAG.getConstant(ShiftAmt, MVT::i32));
10708         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10709           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10710                              DAG.getConstant(ShiftAmt, MVT::i32));
10711       }
10712
10713       if (VT == MVT::v16i8) {
10714         if (Op.getOpcode() == ISD::SHL) {
10715           // Make a large shift.
10716           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10717                                     DAG.getConstant(ShiftAmt, MVT::i32));
10718           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10719           // Zero out the rightmost bits.
10720           SmallVector<SDValue, 16> V(16,
10721                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10722                                                      MVT::i8));
10723           return DAG.getNode(ISD::AND, dl, VT, SHL,
10724                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10725         }
10726         if (Op.getOpcode() == ISD::SRL) {
10727           // Make a large shift.
10728           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10729                                     DAG.getConstant(ShiftAmt, MVT::i32));
10730           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10731           // Zero out the leftmost bits.
10732           SmallVector<SDValue, 16> V(16,
10733                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10734                                                      MVT::i8));
10735           return DAG.getNode(ISD::AND, dl, VT, SRL,
10736                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10737         }
10738         if (Op.getOpcode() == ISD::SRA) {
10739           if (ShiftAmt == 7) {
10740             // R s>> 7  ===  R s< 0
10741             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10742             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10743           }
10744
10745           // R s>> a === ((R u>> a) ^ m) - m
10746           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10747           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10748                                                          MVT::i8));
10749           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10750           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10751           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10752           return Res;
10753         }
10754         llvm_unreachable("Unknown shift opcode.");
10755       }
10756
10757       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10758         if (Op.getOpcode() == ISD::SHL) {
10759           // Make a large shift.
10760           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10761                                     DAG.getConstant(ShiftAmt, MVT::i32));
10762           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10763           // Zero out the rightmost bits.
10764           SmallVector<SDValue, 32> V(32,
10765                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10766                                                      MVT::i8));
10767           return DAG.getNode(ISD::AND, dl, VT, SHL,
10768                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10769         }
10770         if (Op.getOpcode() == ISD::SRL) {
10771           // Make a large shift.
10772           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10773                                     DAG.getConstant(ShiftAmt, MVT::i32));
10774           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10775           // Zero out the leftmost bits.
10776           SmallVector<SDValue, 32> V(32,
10777                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10778                                                      MVT::i8));
10779           return DAG.getNode(ISD::AND, dl, VT, SRL,
10780                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10781         }
10782         if (Op.getOpcode() == ISD::SRA) {
10783           if (ShiftAmt == 7) {
10784             // R s>> 7  ===  R s< 0
10785             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10786             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10787           }
10788
10789           // R s>> a === ((R u>> a) ^ m) - m
10790           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10791           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10792                                                          MVT::i8));
10793           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10794           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10795           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10796           return Res;
10797         }
10798         llvm_unreachable("Unknown shift opcode.");
10799       }
10800     }
10801   }
10802
10803   // Lower SHL with variable shift amount.
10804   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10805     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10806                      DAG.getConstant(23, MVT::i32));
10807
10808     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10809     Constant *C = ConstantDataVector::get(*Context, CV);
10810     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10811     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10812                                  MachinePointerInfo::getConstantPool(),
10813                                  false, false, false, 16);
10814
10815     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10816     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10817     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10818     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10819   }
10820   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10821     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10822
10823     // a = a << 5;
10824     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10825                      DAG.getConstant(5, MVT::i32));
10826     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10827
10828     // Turn 'a' into a mask suitable for VSELECT
10829     SDValue VSelM = DAG.getConstant(0x80, VT);
10830     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10831     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10832
10833     SDValue CM1 = DAG.getConstant(0x0f, VT);
10834     SDValue CM2 = DAG.getConstant(0x3f, VT);
10835
10836     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10837     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10838     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10839                             DAG.getConstant(4, MVT::i32), DAG);
10840     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10841     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10842
10843     // a += a
10844     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10845     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10846     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10847
10848     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10849     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10850     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10851                             DAG.getConstant(2, MVT::i32), DAG);
10852     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10853     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10854
10855     // a += a
10856     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10857     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10858     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10859
10860     // return VSELECT(r, r+r, a);
10861     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10862                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10863     return R;
10864   }
10865
10866   // Decompose 256-bit shifts into smaller 128-bit shifts.
10867   if (VT.is256BitVector()) {
10868     unsigned NumElems = VT.getVectorNumElements();
10869     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10870     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10871
10872     // Extract the two vectors
10873     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10874     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10875
10876     // Recreate the shift amount vectors
10877     SDValue Amt1, Amt2;
10878     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10879       // Constant shift amount
10880       SmallVector<SDValue, 4> Amt1Csts;
10881       SmallVector<SDValue, 4> Amt2Csts;
10882       for (unsigned i = 0; i != NumElems/2; ++i)
10883         Amt1Csts.push_back(Amt->getOperand(i));
10884       for (unsigned i = NumElems/2; i != NumElems; ++i)
10885         Amt2Csts.push_back(Amt->getOperand(i));
10886
10887       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10888                                  &Amt1Csts[0], NumElems/2);
10889       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10890                                  &Amt2Csts[0], NumElems/2);
10891     } else {
10892       // Variable shift amount
10893       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10894       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10895     }
10896
10897     // Issue new vector shifts for the smaller types
10898     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10899     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10900
10901     // Concatenate the result back
10902     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10903   }
10904
10905   return SDValue();
10906 }
10907
10908 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10909   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10910   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10911   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10912   // has only one use.
10913   SDNode *N = Op.getNode();
10914   SDValue LHS = N->getOperand(0);
10915   SDValue RHS = N->getOperand(1);
10916   unsigned BaseOp = 0;
10917   unsigned Cond = 0;
10918   DebugLoc DL = Op.getDebugLoc();
10919   switch (Op.getOpcode()) {
10920   default: llvm_unreachable("Unknown ovf instruction!");
10921   case ISD::SADDO:
10922     // A subtract of one will be selected as a INC. Note that INC doesn't
10923     // set CF, so we can't do this for UADDO.
10924     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10925       if (C->isOne()) {
10926         BaseOp = X86ISD::INC;
10927         Cond = X86::COND_O;
10928         break;
10929       }
10930     BaseOp = X86ISD::ADD;
10931     Cond = X86::COND_O;
10932     break;
10933   case ISD::UADDO:
10934     BaseOp = X86ISD::ADD;
10935     Cond = X86::COND_B;
10936     break;
10937   case ISD::SSUBO:
10938     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10939     // set CF, so we can't do this for USUBO.
10940     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10941       if (C->isOne()) {
10942         BaseOp = X86ISD::DEC;
10943         Cond = X86::COND_O;
10944         break;
10945       }
10946     BaseOp = X86ISD::SUB;
10947     Cond = X86::COND_O;
10948     break;
10949   case ISD::USUBO:
10950     BaseOp = X86ISD::SUB;
10951     Cond = X86::COND_B;
10952     break;
10953   case ISD::SMULO:
10954     BaseOp = X86ISD::SMUL;
10955     Cond = X86::COND_O;
10956     break;
10957   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10958     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10959                                  MVT::i32);
10960     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10961
10962     SDValue SetCC =
10963       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10964                   DAG.getConstant(X86::COND_O, MVT::i32),
10965                   SDValue(Sum.getNode(), 2));
10966
10967     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10968   }
10969   }
10970
10971   // Also sets EFLAGS.
10972   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10973   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10974
10975   SDValue SetCC =
10976     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10977                 DAG.getConstant(Cond, MVT::i32),
10978                 SDValue(Sum.getNode(), 1));
10979
10980   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10981 }
10982
10983 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10984                                                   SelectionDAG &DAG) const {
10985   DebugLoc dl = Op.getDebugLoc();
10986   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10987   EVT VT = Op.getValueType();
10988
10989   if (!Subtarget->hasSSE2() || !VT.isVector())
10990     return SDValue();
10991
10992   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10993                       ExtraVT.getScalarType().getSizeInBits();
10994   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10995
10996   switch (VT.getSimpleVT().SimpleTy) {
10997     default: return SDValue();
10998     case MVT::v8i32:
10999     case MVT::v16i16:
11000       if (!Subtarget->hasAVX())
11001         return SDValue();
11002       if (!Subtarget->hasAVX2()) {
11003         // needs to be split
11004         unsigned NumElems = VT.getVectorNumElements();
11005
11006         // Extract the LHS vectors
11007         SDValue LHS = Op.getOperand(0);
11008         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11009         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11010
11011         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11012         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11013
11014         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11015         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11016         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11017                                    ExtraNumElems/2);
11018         SDValue Extra = DAG.getValueType(ExtraVT);
11019
11020         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11021         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11022
11023         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
11024       }
11025       // fall through
11026     case MVT::v4i32:
11027     case MVT::v8i16: {
11028       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11029                                          Op.getOperand(0), ShAmt, DAG);
11030       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11031     }
11032   }
11033 }
11034
11035
11036 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
11037   DebugLoc dl = Op.getDebugLoc();
11038
11039   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11040   // There isn't any reason to disable it if the target processor supports it.
11041   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11042     SDValue Chain = Op.getOperand(0);
11043     SDValue Zero = DAG.getConstant(0, MVT::i32);
11044     SDValue Ops[] = {
11045       DAG.getRegister(X86::ESP, MVT::i32), // Base
11046       DAG.getTargetConstant(1, MVT::i8),   // Scale
11047       DAG.getRegister(0, MVT::i32),        // Index
11048       DAG.getTargetConstant(0, MVT::i32),  // Disp
11049       DAG.getRegister(0, MVT::i32),        // Segment.
11050       Zero,
11051       Chain
11052     };
11053     SDNode *Res =
11054       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11055                           array_lengthof(Ops));
11056     return SDValue(Res, 0);
11057   }
11058
11059   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11060   if (!isDev)
11061     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11062
11063   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11064   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11065   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11066   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11067
11068   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11069   if (!Op1 && !Op2 && !Op3 && Op4)
11070     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11071
11072   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11073   if (Op1 && !Op2 && !Op3 && !Op4)
11074     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11075
11076   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11077   //           (MFENCE)>;
11078   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11079 }
11080
11081 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
11082                                              SelectionDAG &DAG) const {
11083   DebugLoc dl = Op.getDebugLoc();
11084   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11085     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11086   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11087     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11088
11089   // The only fence that needs an instruction is a sequentially-consistent
11090   // cross-thread fence.
11091   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11092     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11093     // no-sse2). There isn't any reason to disable it if the target processor
11094     // supports it.
11095     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11096       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11097
11098     SDValue Chain = Op.getOperand(0);
11099     SDValue Zero = DAG.getConstant(0, MVT::i32);
11100     SDValue Ops[] = {
11101       DAG.getRegister(X86::ESP, MVT::i32), // Base
11102       DAG.getTargetConstant(1, MVT::i8),   // Scale
11103       DAG.getRegister(0, MVT::i32),        // Index
11104       DAG.getTargetConstant(0, MVT::i32),  // Disp
11105       DAG.getRegister(0, MVT::i32),        // Segment.
11106       Zero,
11107       Chain
11108     };
11109     SDNode *Res =
11110       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11111                          array_lengthof(Ops));
11112     return SDValue(Res, 0);
11113   }
11114
11115   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11116   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11117 }
11118
11119
11120 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
11121   EVT T = Op.getValueType();
11122   DebugLoc DL = Op.getDebugLoc();
11123   unsigned Reg = 0;
11124   unsigned size = 0;
11125   switch(T.getSimpleVT().SimpleTy) {
11126   default: llvm_unreachable("Invalid value type!");
11127   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11128   case MVT::i16: Reg = X86::AX;  size = 2; break;
11129   case MVT::i32: Reg = X86::EAX; size = 4; break;
11130   case MVT::i64:
11131     assert(Subtarget->is64Bit() && "Node not type legal!");
11132     Reg = X86::RAX; size = 8;
11133     break;
11134   }
11135   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11136                                     Op.getOperand(2), SDValue());
11137   SDValue Ops[] = { cpIn.getValue(0),
11138                     Op.getOperand(1),
11139                     Op.getOperand(3),
11140                     DAG.getTargetConstant(size, MVT::i8),
11141                     cpIn.getValue(1) };
11142   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11143   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11144   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11145                                            Ops, 5, T, MMO);
11146   SDValue cpOut =
11147     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11148   return cpOut;
11149 }
11150
11151 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
11152                                                  SelectionDAG &DAG) const {
11153   assert(Subtarget->is64Bit() && "Result not type legalized?");
11154   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11155   SDValue TheChain = Op.getOperand(0);
11156   DebugLoc dl = Op.getDebugLoc();
11157   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11158   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11159   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11160                                    rax.getValue(2));
11161   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11162                             DAG.getConstant(32, MVT::i8));
11163   SDValue Ops[] = {
11164     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11165     rdx.getValue(1)
11166   };
11167   return DAG.getMergeValues(Ops, 2, dl);
11168 }
11169
11170 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
11171                                             SelectionDAG &DAG) const {
11172   EVT SrcVT = Op.getOperand(0).getValueType();
11173   EVT DstVT = Op.getValueType();
11174   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11175          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11176   assert((DstVT == MVT::i64 ||
11177           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11178          "Unexpected custom BITCAST");
11179   // i64 <=> MMX conversions are Legal.
11180   if (SrcVT==MVT::i64 && DstVT.isVector())
11181     return Op;
11182   if (DstVT==MVT::i64 && SrcVT.isVector())
11183     return Op;
11184   // MMX <=> MMX conversions are Legal.
11185   if (SrcVT.isVector() && DstVT.isVector())
11186     return Op;
11187   // All other conversions need to be expanded.
11188   return SDValue();
11189 }
11190
11191 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
11192   SDNode *Node = Op.getNode();
11193   DebugLoc dl = Node->getDebugLoc();
11194   EVT T = Node->getValueType(0);
11195   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11196                               DAG.getConstant(0, T), Node->getOperand(2));
11197   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11198                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11199                        Node->getOperand(0),
11200                        Node->getOperand(1), negOp,
11201                        cast<AtomicSDNode>(Node)->getSrcValue(),
11202                        cast<AtomicSDNode>(Node)->getAlignment(),
11203                        cast<AtomicSDNode>(Node)->getOrdering(),
11204                        cast<AtomicSDNode>(Node)->getSynchScope());
11205 }
11206
11207 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11208   SDNode *Node = Op.getNode();
11209   DebugLoc dl = Node->getDebugLoc();
11210   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11211
11212   // Convert seq_cst store -> xchg
11213   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11214   // FIXME: On 32-bit, store -> fist or movq would be more efficient
11215   //        (The only way to get a 16-byte store is cmpxchg16b)
11216   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11217   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11218       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11219     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11220                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
11221                                  Node->getOperand(0),
11222                                  Node->getOperand(1), Node->getOperand(2),
11223                                  cast<AtomicSDNode>(Node)->getMemOperand(),
11224                                  cast<AtomicSDNode>(Node)->getOrdering(),
11225                                  cast<AtomicSDNode>(Node)->getSynchScope());
11226     return Swap.getValue(1);
11227   }
11228   // Other atomic stores have a simple pattern.
11229   return Op;
11230 }
11231
11232 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11233   EVT VT = Op.getNode()->getValueType(0);
11234
11235   // Let legalize expand this if it isn't a legal type yet.
11236   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11237     return SDValue();
11238
11239   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11240
11241   unsigned Opc;
11242   bool ExtraOp = false;
11243   switch (Op.getOpcode()) {
11244   default: llvm_unreachable("Invalid code");
11245   case ISD::ADDC: Opc = X86ISD::ADD; break;
11246   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11247   case ISD::SUBC: Opc = X86ISD::SUB; break;
11248   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11249   }
11250
11251   if (!ExtraOp)
11252     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11253                        Op.getOperand(1));
11254   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11255                      Op.getOperand(1), Op.getOperand(2));
11256 }
11257
11258 /// LowerOperation - Provide custom lowering hooks for some operations.
11259 ///
11260 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11261   switch (Op.getOpcode()) {
11262   default: llvm_unreachable("Should not custom lower this!");
11263   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
11264   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
11265   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
11266   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
11267   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
11268   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
11269   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11270   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
11271   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11272   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11273   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11274   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
11275   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
11276   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11277   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11278   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11279   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11280   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
11281   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11282   case ISD::SHL_PARTS:
11283   case ISD::SRA_PARTS:
11284   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
11285   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
11286   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
11287   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
11288   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
11289   case ISD::FABS:               return LowerFABS(Op, DAG);
11290   case ISD::FNEG:               return LowerFNEG(Op, DAG);
11291   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
11292   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
11293   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11294   case ISD::SELECT:             return LowerSELECT(Op, DAG);
11295   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
11296   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11297   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11298   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11299   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11300   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11301   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
11302   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11303   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11304   case ISD::FRAME_TO_ARGS_OFFSET:
11305                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11306   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11307   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
11308   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11309   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11310   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11311   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
11312   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11313   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
11314   case ISD::MUL:                return LowerMUL(Op, DAG);
11315   case ISD::SRA:
11316   case ISD::SRL:
11317   case ISD::SHL:                return LowerShift(Op, DAG);
11318   case ISD::SADDO:
11319   case ISD::UADDO:
11320   case ISD::SSUBO:
11321   case ISD::USUBO:
11322   case ISD::SMULO:
11323   case ISD::UMULO:              return LowerXALUO(Op, DAG);
11324   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
11325   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11326   case ISD::ADDC:
11327   case ISD::ADDE:
11328   case ISD::SUBC:
11329   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11330   case ISD::ADD:                return LowerADD(Op, DAG);
11331   case ISD::SUB:                return LowerSUB(Op, DAG);
11332   }
11333 }
11334
11335 static void ReplaceATOMIC_LOAD(SDNode *Node,
11336                                   SmallVectorImpl<SDValue> &Results,
11337                                   SelectionDAG &DAG) {
11338   DebugLoc dl = Node->getDebugLoc();
11339   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11340
11341   // Convert wide load -> cmpxchg8b/cmpxchg16b
11342   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11343   //        (The only way to get a 16-byte load is cmpxchg16b)
11344   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11345   SDValue Zero = DAG.getConstant(0, VT);
11346   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11347                                Node->getOperand(0),
11348                                Node->getOperand(1), Zero, Zero,
11349                                cast<AtomicSDNode>(Node)->getMemOperand(),
11350                                cast<AtomicSDNode>(Node)->getOrdering(),
11351                                cast<AtomicSDNode>(Node)->getSynchScope());
11352   Results.push_back(Swap.getValue(0));
11353   Results.push_back(Swap.getValue(1));
11354 }
11355
11356 static void
11357 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11358                         SelectionDAG &DAG, unsigned NewOp) {
11359   DebugLoc dl = Node->getDebugLoc();
11360   assert (Node->getValueType(0) == MVT::i64 &&
11361           "Only know how to expand i64 atomics");
11362
11363   SDValue Chain = Node->getOperand(0);
11364   SDValue In1 = Node->getOperand(1);
11365   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11366                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11367   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11368                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11369   SDValue Ops[] = { Chain, In1, In2L, In2H };
11370   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11371   SDValue Result =
11372     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11373                             cast<MemSDNode>(Node)->getMemOperand());
11374   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11375   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11376   Results.push_back(Result.getValue(2));
11377 }
11378
11379 /// ReplaceNodeResults - Replace a node with an illegal result type
11380 /// with a new node built out of custom code.
11381 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11382                                            SmallVectorImpl<SDValue>&Results,
11383                                            SelectionDAG &DAG) const {
11384   DebugLoc dl = N->getDebugLoc();
11385   switch (N->getOpcode()) {
11386   default:
11387     llvm_unreachable("Do not know how to custom type legalize this operation!");
11388   case ISD::SIGN_EXTEND_INREG:
11389   case ISD::ADDC:
11390   case ISD::ADDE:
11391   case ISD::SUBC:
11392   case ISD::SUBE:
11393     // We don't want to expand or promote these.
11394     return;
11395   case ISD::FP_TO_SINT:
11396   case ISD::FP_TO_UINT: {
11397     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11398
11399     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11400       return;
11401
11402     std::pair<SDValue,SDValue> Vals =
11403         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11404     SDValue FIST = Vals.first, StackSlot = Vals.second;
11405     if (FIST.getNode() != 0) {
11406       EVT VT = N->getValueType(0);
11407       // Return a load from the stack slot.
11408       if (StackSlot.getNode() != 0)
11409         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11410                                       MachinePointerInfo(),
11411                                       false, false, false, 0));
11412       else
11413         Results.push_back(FIST);
11414     }
11415     return;
11416   }
11417   case ISD::READCYCLECOUNTER: {
11418     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11419     SDValue TheChain = N->getOperand(0);
11420     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11421     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11422                                      rd.getValue(1));
11423     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11424                                      eax.getValue(2));
11425     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11426     SDValue Ops[] = { eax, edx };
11427     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11428     Results.push_back(edx.getValue(1));
11429     return;
11430   }
11431   case ISD::ATOMIC_CMP_SWAP: {
11432     EVT T = N->getValueType(0);
11433     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11434     bool Regs64bit = T == MVT::i128;
11435     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11436     SDValue cpInL, cpInH;
11437     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11438                         DAG.getConstant(0, HalfT));
11439     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11440                         DAG.getConstant(1, HalfT));
11441     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11442                              Regs64bit ? X86::RAX : X86::EAX,
11443                              cpInL, SDValue());
11444     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11445                              Regs64bit ? X86::RDX : X86::EDX,
11446                              cpInH, cpInL.getValue(1));
11447     SDValue swapInL, swapInH;
11448     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11449                           DAG.getConstant(0, HalfT));
11450     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11451                           DAG.getConstant(1, HalfT));
11452     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11453                                Regs64bit ? X86::RBX : X86::EBX,
11454                                swapInL, cpInH.getValue(1));
11455     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11456                                Regs64bit ? X86::RCX : X86::ECX,
11457                                swapInH, swapInL.getValue(1));
11458     SDValue Ops[] = { swapInH.getValue(0),
11459                       N->getOperand(1),
11460                       swapInH.getValue(1) };
11461     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11462     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11463     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11464                                   X86ISD::LCMPXCHG8_DAG;
11465     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11466                                              Ops, 3, T, MMO);
11467     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11468                                         Regs64bit ? X86::RAX : X86::EAX,
11469                                         HalfT, Result.getValue(1));
11470     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11471                                         Regs64bit ? X86::RDX : X86::EDX,
11472                                         HalfT, cpOutL.getValue(2));
11473     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11474     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11475     Results.push_back(cpOutH.getValue(1));
11476     return;
11477   }
11478   case ISD::ATOMIC_LOAD_ADD:
11479   case ISD::ATOMIC_LOAD_AND:
11480   case ISD::ATOMIC_LOAD_NAND:
11481   case ISD::ATOMIC_LOAD_OR:
11482   case ISD::ATOMIC_LOAD_SUB:
11483   case ISD::ATOMIC_LOAD_XOR:
11484   case ISD::ATOMIC_SWAP: {
11485     unsigned Opc;
11486     switch (N->getOpcode()) {
11487     default: llvm_unreachable("Unexpected opcode");
11488     case ISD::ATOMIC_LOAD_ADD:
11489       Opc = X86ISD::ATOMADD64_DAG;
11490       break;
11491     case ISD::ATOMIC_LOAD_AND:
11492       Opc = X86ISD::ATOMAND64_DAG;
11493       break;
11494     case ISD::ATOMIC_LOAD_NAND:
11495       Opc = X86ISD::ATOMNAND64_DAG;
11496       break;
11497     case ISD::ATOMIC_LOAD_OR:
11498       Opc = X86ISD::ATOMOR64_DAG;
11499       break;
11500     case ISD::ATOMIC_LOAD_SUB:
11501       Opc = X86ISD::ATOMSUB64_DAG;
11502       break;
11503     case ISD::ATOMIC_LOAD_XOR:
11504       Opc = X86ISD::ATOMXOR64_DAG;
11505       break;
11506     case ISD::ATOMIC_SWAP:
11507       Opc = X86ISD::ATOMSWAP64_DAG;
11508       break;
11509     }
11510     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11511     return;
11512   }
11513   case ISD::ATOMIC_LOAD:
11514     ReplaceATOMIC_LOAD(N, Results, DAG);
11515   }
11516 }
11517
11518 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11519   switch (Opcode) {
11520   default: return NULL;
11521   case X86ISD::BSF:                return "X86ISD::BSF";
11522   case X86ISD::BSR:                return "X86ISD::BSR";
11523   case X86ISD::SHLD:               return "X86ISD::SHLD";
11524   case X86ISD::SHRD:               return "X86ISD::SHRD";
11525   case X86ISD::FAND:               return "X86ISD::FAND";
11526   case X86ISD::FOR:                return "X86ISD::FOR";
11527   case X86ISD::FXOR:               return "X86ISD::FXOR";
11528   case X86ISD::FSRL:               return "X86ISD::FSRL";
11529   case X86ISD::FILD:               return "X86ISD::FILD";
11530   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11531   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11532   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11533   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11534   case X86ISD::FLD:                return "X86ISD::FLD";
11535   case X86ISD::FST:                return "X86ISD::FST";
11536   case X86ISD::CALL:               return "X86ISD::CALL";
11537   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11538   case X86ISD::BT:                 return "X86ISD::BT";
11539   case X86ISD::CMP:                return "X86ISD::CMP";
11540   case X86ISD::COMI:               return "X86ISD::COMI";
11541   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11542   case X86ISD::SETCC:              return "X86ISD::SETCC";
11543   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11544   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11545   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11546   case X86ISD::CMOV:               return "X86ISD::CMOV";
11547   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11548   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11549   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11550   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11551   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11552   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11553   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11554   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11555   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11556   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11557   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11558   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11559   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11560   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11561   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11562   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11563   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11564   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11565   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11566   case X86ISD::HADD:               return "X86ISD::HADD";
11567   case X86ISD::HSUB:               return "X86ISD::HSUB";
11568   case X86ISD::FHADD:              return "X86ISD::FHADD";
11569   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11570   case X86ISD::FMAX:               return "X86ISD::FMAX";
11571   case X86ISD::FMIN:               return "X86ISD::FMIN";
11572   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
11573   case X86ISD::FMINC:              return "X86ISD::FMINC";
11574   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11575   case X86ISD::FRCP:               return "X86ISD::FRCP";
11576   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11577   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
11578   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11579   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11580   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11581   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11582   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
11583   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11584   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11585   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11586   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11587   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11588   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11589   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11590   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11591   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11592   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
11593   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11594   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
11595   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11596   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11597   case X86ISD::VSHL:               return "X86ISD::VSHL";
11598   case X86ISD::VSRL:               return "X86ISD::VSRL";
11599   case X86ISD::VSRA:               return "X86ISD::VSRA";
11600   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11601   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11602   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11603   case X86ISD::CMPP:               return "X86ISD::CMPP";
11604   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11605   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11606   case X86ISD::ADD:                return "X86ISD::ADD";
11607   case X86ISD::SUB:                return "X86ISD::SUB";
11608   case X86ISD::ADC:                return "X86ISD::ADC";
11609   case X86ISD::SBB:                return "X86ISD::SBB";
11610   case X86ISD::SMUL:               return "X86ISD::SMUL";
11611   case X86ISD::UMUL:               return "X86ISD::UMUL";
11612   case X86ISD::INC:                return "X86ISD::INC";
11613   case X86ISD::DEC:                return "X86ISD::DEC";
11614   case X86ISD::OR:                 return "X86ISD::OR";
11615   case X86ISD::XOR:                return "X86ISD::XOR";
11616   case X86ISD::AND:                return "X86ISD::AND";
11617   case X86ISD::ANDN:               return "X86ISD::ANDN";
11618   case X86ISD::BLSI:               return "X86ISD::BLSI";
11619   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11620   case X86ISD::BLSR:               return "X86ISD::BLSR";
11621   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11622   case X86ISD::PTEST:              return "X86ISD::PTEST";
11623   case X86ISD::TESTP:              return "X86ISD::TESTP";
11624   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11625   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11626   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11627   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11628   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11629   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11630   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11631   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11632   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11633   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11634   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11635   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11636   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11637   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11638   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11639   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11640   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11641   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11642   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11643   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11644   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11645   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11646   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11647   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11648   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11649   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11650   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11651   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11652   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11653   case X86ISD::SAHF:               return "X86ISD::SAHF";
11654   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
11655   case X86ISD::FMADD:              return "X86ISD::FMADD";
11656   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
11657   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
11658   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
11659   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
11660   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
11661   }
11662 }
11663
11664 // isLegalAddressingMode - Return true if the addressing mode represented
11665 // by AM is legal for this target, for a load/store of the specified type.
11666 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11667                                               Type *Ty) const {
11668   // X86 supports extremely general addressing modes.
11669   CodeModel::Model M = getTargetMachine().getCodeModel();
11670   Reloc::Model R = getTargetMachine().getRelocationModel();
11671
11672   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11673   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11674     return false;
11675
11676   if (AM.BaseGV) {
11677     unsigned GVFlags =
11678       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11679
11680     // If a reference to this global requires an extra load, we can't fold it.
11681     if (isGlobalStubReference(GVFlags))
11682       return false;
11683
11684     // If BaseGV requires a register for the PIC base, we cannot also have a
11685     // BaseReg specified.
11686     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11687       return false;
11688
11689     // If lower 4G is not available, then we must use rip-relative addressing.
11690     if ((M != CodeModel::Small || R != Reloc::Static) &&
11691         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11692       return false;
11693   }
11694
11695   switch (AM.Scale) {
11696   case 0:
11697   case 1:
11698   case 2:
11699   case 4:
11700   case 8:
11701     // These scales always work.
11702     break;
11703   case 3:
11704   case 5:
11705   case 9:
11706     // These scales are formed with basereg+scalereg.  Only accept if there is
11707     // no basereg yet.
11708     if (AM.HasBaseReg)
11709       return false;
11710     break;
11711   default:  // Other stuff never works.
11712     return false;
11713   }
11714
11715   return true;
11716 }
11717
11718
11719 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11720   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11721     return false;
11722   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11723   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11724   if (NumBits1 <= NumBits2)
11725     return false;
11726   return true;
11727 }
11728
11729 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11730   return Imm == (int32_t)Imm;
11731 }
11732
11733 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11734   // Can also use sub to handle negated immediates.
11735   return Imm == (int32_t)Imm;
11736 }
11737
11738 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11739   if (!VT1.isInteger() || !VT2.isInteger())
11740     return false;
11741   unsigned NumBits1 = VT1.getSizeInBits();
11742   unsigned NumBits2 = VT2.getSizeInBits();
11743   if (NumBits1 <= NumBits2)
11744     return false;
11745   return true;
11746 }
11747
11748 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11749   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11750   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11751 }
11752
11753 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11754   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11755   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11756 }
11757
11758 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11759   // i16 instructions are longer (0x66 prefix) and potentially slower.
11760   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11761 }
11762
11763 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11764 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11765 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11766 /// are assumed to be legal.
11767 bool
11768 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11769                                       EVT VT) const {
11770   // Very little shuffling can be done for 64-bit vectors right now.
11771   if (VT.getSizeInBits() == 64)
11772     return false;
11773
11774   // FIXME: pshufb, blends, shifts.
11775   return (VT.getVectorNumElements() == 2 ||
11776           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11777           isMOVLMask(M, VT) ||
11778           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11779           isPSHUFDMask(M, VT) ||
11780           isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11781           isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11782           isPALIGNRMask(M, VT, Subtarget) ||
11783           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11784           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11785           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11786           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11787 }
11788
11789 bool
11790 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11791                                           EVT VT) const {
11792   unsigned NumElts = VT.getVectorNumElements();
11793   // FIXME: This collection of masks seems suspect.
11794   if (NumElts == 2)
11795     return true;
11796   if (NumElts == 4 && VT.is128BitVector()) {
11797     return (isMOVLMask(Mask, VT)  ||
11798             isCommutedMOVLMask(Mask, VT, true) ||
11799             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11800             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11801   }
11802   return false;
11803 }
11804
11805 //===----------------------------------------------------------------------===//
11806 //                           X86 Scheduler Hooks
11807 //===----------------------------------------------------------------------===//
11808
11809 // private utility function
11810 MachineBasicBlock *
11811 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11812                                                        MachineBasicBlock *MBB,
11813                                                        unsigned regOpc,
11814                                                        unsigned immOpc,
11815                                                        unsigned LoadOpc,
11816                                                        unsigned CXchgOpc,
11817                                                        unsigned notOpc,
11818                                                        unsigned EAXreg,
11819                                                  const TargetRegisterClass *RC,
11820                                                        bool Invert) const {
11821   // For the atomic bitwise operator, we generate
11822   //   thisMBB:
11823   //   newMBB:
11824   //     ld  t1 = [bitinstr.addr]
11825   //     op  t2 = t1, [bitinstr.val]
11826   //     not t3 = t2  (if Invert)
11827   //     mov EAX = t1
11828   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11829   //     bz  newMBB
11830   //     fallthrough -->nextMBB
11831   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11832   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11833   MachineFunction::iterator MBBIter = MBB;
11834   ++MBBIter;
11835
11836   /// First build the CFG
11837   MachineFunction *F = MBB->getParent();
11838   MachineBasicBlock *thisMBB = MBB;
11839   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11840   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11841   F->insert(MBBIter, newMBB);
11842   F->insert(MBBIter, nextMBB);
11843
11844   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11845   nextMBB->splice(nextMBB->begin(), thisMBB,
11846                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11847                   thisMBB->end());
11848   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11849
11850   // Update thisMBB to fall through to newMBB
11851   thisMBB->addSuccessor(newMBB);
11852
11853   // newMBB jumps to itself and fall through to nextMBB
11854   newMBB->addSuccessor(nextMBB);
11855   newMBB->addSuccessor(newMBB);
11856
11857   // Insert instructions into newMBB based on incoming instruction
11858   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11859          "unexpected number of operands");
11860   DebugLoc dl = bInstr->getDebugLoc();
11861   MachineOperand& destOper = bInstr->getOperand(0);
11862   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11863   int numArgs = bInstr->getNumOperands() - 1;
11864   for (int i=0; i < numArgs; ++i)
11865     argOpers[i] = &bInstr->getOperand(i+1);
11866
11867   // x86 address has 4 operands: base, index, scale, and displacement
11868   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11869   int valArgIndx = lastAddrIndx + 1;
11870
11871   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11872   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11873   for (int i=0; i <= lastAddrIndx; ++i)
11874     (*MIB).addOperand(*argOpers[i]);
11875
11876   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11877   assert((argOpers[valArgIndx]->isReg() ||
11878           argOpers[valArgIndx]->isImm()) &&
11879          "invalid operand");
11880   if (argOpers[valArgIndx]->isReg())
11881     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11882   else
11883     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11884   MIB.addReg(t1);
11885   (*MIB).addOperand(*argOpers[valArgIndx]);
11886
11887   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11888   if (Invert) {
11889     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11890   }
11891   else
11892     t3 = t2;
11893
11894   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11895   MIB.addReg(t1);
11896
11897   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11898   for (int i=0; i <= lastAddrIndx; ++i)
11899     (*MIB).addOperand(*argOpers[i]);
11900   MIB.addReg(t3);
11901   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11902   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11903                     bInstr->memoperands_end());
11904
11905   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11906   MIB.addReg(EAXreg);
11907
11908   // insert branch
11909   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11910
11911   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11912   return nextMBB;
11913 }
11914
11915 // private utility function:  64 bit atomics on 32 bit host.
11916 MachineBasicBlock *
11917 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11918                                                        MachineBasicBlock *MBB,
11919                                                        unsigned regOpcL,
11920                                                        unsigned regOpcH,
11921                                                        unsigned immOpcL,
11922                                                        unsigned immOpcH,
11923                                                        bool Invert) const {
11924   // For the atomic bitwise operator, we generate
11925   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11926   //     ld t1,t2 = [bitinstr.addr]
11927   //   newMBB:
11928   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11929   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11930   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11931   //     neg t7, t8 < t5, t6  (if Invert)
11932   //     mov ECX, EBX <- t5, t6
11933   //     mov EAX, EDX <- t1, t2
11934   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11935   //     mov t3, t4 <- EAX, EDX
11936   //     bz  newMBB
11937   //     result in out1, out2
11938   //     fallthrough -->nextMBB
11939
11940   const TargetRegisterClass *RC = &X86::GR32RegClass;
11941   const unsigned LoadOpc = X86::MOV32rm;
11942   const unsigned NotOpc = X86::NOT32r;
11943   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11944   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11945   MachineFunction::iterator MBBIter = MBB;
11946   ++MBBIter;
11947
11948   /// First build the CFG
11949   MachineFunction *F = MBB->getParent();
11950   MachineBasicBlock *thisMBB = MBB;
11951   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11952   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11953   F->insert(MBBIter, newMBB);
11954   F->insert(MBBIter, nextMBB);
11955
11956   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11957   nextMBB->splice(nextMBB->begin(), thisMBB,
11958                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11959                   thisMBB->end());
11960   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11961
11962   // Update thisMBB to fall through to newMBB
11963   thisMBB->addSuccessor(newMBB);
11964
11965   // newMBB jumps to itself and fall through to nextMBB
11966   newMBB->addSuccessor(nextMBB);
11967   newMBB->addSuccessor(newMBB);
11968
11969   DebugLoc dl = bInstr->getDebugLoc();
11970   // Insert instructions into newMBB based on incoming instruction
11971   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11972   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11973          "unexpected number of operands");
11974   MachineOperand& dest1Oper = bInstr->getOperand(0);
11975   MachineOperand& dest2Oper = bInstr->getOperand(1);
11976   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11977   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11978     argOpers[i] = &bInstr->getOperand(i+2);
11979
11980     // We use some of the operands multiple times, so conservatively just
11981     // clear any kill flags that might be present.
11982     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11983       argOpers[i]->setIsKill(false);
11984   }
11985
11986   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11987   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11988
11989   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11990   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11991   for (int i=0; i <= lastAddrIndx; ++i)
11992     (*MIB).addOperand(*argOpers[i]);
11993   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11994   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11995   // add 4 to displacement.
11996   for (int i=0; i <= lastAddrIndx-2; ++i)
11997     (*MIB).addOperand(*argOpers[i]);
11998   MachineOperand newOp3 = *(argOpers[3]);
11999   if (newOp3.isImm())
12000     newOp3.setImm(newOp3.getImm()+4);
12001   else
12002     newOp3.setOffset(newOp3.getOffset()+4);
12003   (*MIB).addOperand(newOp3);
12004   (*MIB).addOperand(*argOpers[lastAddrIndx]);
12005
12006   // t3/4 are defined later, at the bottom of the loop
12007   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
12008   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
12009   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
12010     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
12011   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
12012     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
12013
12014   // The subsequent operations should be using the destination registers of
12015   // the PHI instructions.
12016   t1 = dest1Oper.getReg();
12017   t2 = dest2Oper.getReg();
12018
12019   int valArgIndx = lastAddrIndx + 1;
12020   assert((argOpers[valArgIndx]->isReg() ||
12021           argOpers[valArgIndx]->isImm()) &&
12022          "invalid operand");
12023   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
12024   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
12025   if (argOpers[valArgIndx]->isReg())
12026     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
12027   else
12028     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
12029   if (regOpcL != X86::MOV32rr)
12030     MIB.addReg(t1);
12031   (*MIB).addOperand(*argOpers[valArgIndx]);
12032   assert(argOpers[valArgIndx + 1]->isReg() ==
12033          argOpers[valArgIndx]->isReg());
12034   assert(argOpers[valArgIndx + 1]->isImm() ==
12035          argOpers[valArgIndx]->isImm());
12036   if (argOpers[valArgIndx + 1]->isReg())
12037     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
12038   else
12039     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
12040   if (regOpcH != X86::MOV32rr)
12041     MIB.addReg(t2);
12042   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
12043
12044   unsigned t7, t8;
12045   if (Invert) {
12046     t7 = F->getRegInfo().createVirtualRegister(RC);
12047     t8 = F->getRegInfo().createVirtualRegister(RC);
12048     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
12049     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
12050   } else {
12051     t7 = t5;
12052     t8 = t6;
12053   }
12054
12055   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12056   MIB.addReg(t1);
12057   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
12058   MIB.addReg(t2);
12059
12060   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
12061   MIB.addReg(t7);
12062   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
12063   MIB.addReg(t8);
12064
12065   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
12066   for (int i=0; i <= lastAddrIndx; ++i)
12067     (*MIB).addOperand(*argOpers[i]);
12068
12069   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12070   (*MIB).setMemRefs(bInstr->memoperands_begin(),
12071                     bInstr->memoperands_end());
12072
12073   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
12074   MIB.addReg(X86::EAX);
12075   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
12076   MIB.addReg(X86::EDX);
12077
12078   // insert branch
12079   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12080
12081   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
12082   return nextMBB;
12083 }
12084
12085 // private utility function
12086 MachineBasicBlock *
12087 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
12088                                                       MachineBasicBlock *MBB,
12089                                                       unsigned cmovOpc) const {
12090   // For the atomic min/max operator, we generate
12091   //   thisMBB:
12092   //   newMBB:
12093   //     ld t1 = [min/max.addr]
12094   //     mov t2 = [min/max.val]
12095   //     cmp  t1, t2
12096   //     cmov[cond] t2 = t1
12097   //     mov EAX = t1
12098   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
12099   //     bz   newMBB
12100   //     fallthrough -->nextMBB
12101   //
12102   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12103   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12104   MachineFunction::iterator MBBIter = MBB;
12105   ++MBBIter;
12106
12107   /// First build the CFG
12108   MachineFunction *F = MBB->getParent();
12109   MachineBasicBlock *thisMBB = MBB;
12110   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
12111   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
12112   F->insert(MBBIter, newMBB);
12113   F->insert(MBBIter, nextMBB);
12114
12115   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
12116   nextMBB->splice(nextMBB->begin(), thisMBB,
12117                   llvm::next(MachineBasicBlock::iterator(mInstr)),
12118                   thisMBB->end());
12119   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12120
12121   // Update thisMBB to fall through to newMBB
12122   thisMBB->addSuccessor(newMBB);
12123
12124   // newMBB jumps to newMBB and fall through to nextMBB
12125   newMBB->addSuccessor(nextMBB);
12126   newMBB->addSuccessor(newMBB);
12127
12128   DebugLoc dl = mInstr->getDebugLoc();
12129   // Insert instructions into newMBB based on incoming instruction
12130   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
12131          "unexpected number of operands");
12132   MachineOperand& destOper = mInstr->getOperand(0);
12133   MachineOperand* argOpers[2 + X86::AddrNumOperands];
12134   int numArgs = mInstr->getNumOperands() - 1;
12135   for (int i=0; i < numArgs; ++i)
12136     argOpers[i] = &mInstr->getOperand(i+1);
12137
12138   // x86 address has 4 operands: base, index, scale, and displacement
12139   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
12140   int valArgIndx = lastAddrIndx + 1;
12141
12142   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12143   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
12144   for (int i=0; i <= lastAddrIndx; ++i)
12145     (*MIB).addOperand(*argOpers[i]);
12146
12147   // We only support register and immediate values
12148   assert((argOpers[valArgIndx]->isReg() ||
12149           argOpers[valArgIndx]->isImm()) &&
12150          "invalid operand");
12151
12152   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12153   if (argOpers[valArgIndx]->isReg())
12154     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
12155   else
12156     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
12157   (*MIB).addOperand(*argOpers[valArgIndx]);
12158
12159   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
12160   MIB.addReg(t1);
12161
12162   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
12163   MIB.addReg(t1);
12164   MIB.addReg(t2);
12165
12166   // Generate movc
12167   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
12168   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
12169   MIB.addReg(t2);
12170   MIB.addReg(t1);
12171
12172   // Cmp and exchange if none has modified the memory location
12173   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
12174   for (int i=0; i <= lastAddrIndx; ++i)
12175     (*MIB).addOperand(*argOpers[i]);
12176   MIB.addReg(t3);
12177   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
12178   (*MIB).setMemRefs(mInstr->memoperands_begin(),
12179                     mInstr->memoperands_end());
12180
12181   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
12182   MIB.addReg(X86::EAX);
12183
12184   // insert branch
12185   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
12186
12187   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
12188   return nextMBB;
12189 }
12190
12191 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12192 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12193 // in the .td file.
12194 MachineBasicBlock *
12195 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12196                             unsigned numArgs, bool memArg) const {
12197   assert(Subtarget->hasSSE42() &&
12198          "Target must have SSE4.2 or AVX features enabled");
12199
12200   DebugLoc dl = MI->getDebugLoc();
12201   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12202   unsigned Opc;
12203   if (!Subtarget->hasAVX()) {
12204     if (memArg)
12205       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12206     else
12207       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12208   } else {
12209     if (memArg)
12210       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12211     else
12212       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12213   }
12214
12215   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12216   for (unsigned i = 0; i < numArgs; ++i) {
12217     MachineOperand &Op = MI->getOperand(i+1);
12218     if (!(Op.isReg() && Op.isImplicit()))
12219       MIB.addOperand(Op);
12220   }
12221   BuildMI(*BB, MI, dl,
12222     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12223     .addReg(X86::XMM0);
12224
12225   MI->eraseFromParent();
12226   return BB;
12227 }
12228
12229 MachineBasicBlock *
12230 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12231   DebugLoc dl = MI->getDebugLoc();
12232   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12233
12234   // Address into RAX/EAX, other two args into ECX, EDX.
12235   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12236   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12237   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12238   for (int i = 0; i < X86::AddrNumOperands; ++i)
12239     MIB.addOperand(MI->getOperand(i));
12240
12241   unsigned ValOps = X86::AddrNumOperands;
12242   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12243     .addReg(MI->getOperand(ValOps).getReg());
12244   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12245     .addReg(MI->getOperand(ValOps+1).getReg());
12246
12247   // The instruction doesn't actually take any operands though.
12248   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12249
12250   MI->eraseFromParent(); // The pseudo is gone now.
12251   return BB;
12252 }
12253
12254 MachineBasicBlock *
12255 X86TargetLowering::EmitVAARG64WithCustomInserter(
12256                    MachineInstr *MI,
12257                    MachineBasicBlock *MBB) const {
12258   // Emit va_arg instruction on X86-64.
12259
12260   // Operands to this pseudo-instruction:
12261   // 0  ) Output        : destination address (reg)
12262   // 1-5) Input         : va_list address (addr, i64mem)
12263   // 6  ) ArgSize       : Size (in bytes) of vararg type
12264   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12265   // 8  ) Align         : Alignment of type
12266   // 9  ) EFLAGS (implicit-def)
12267
12268   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12269   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12270
12271   unsigned DestReg = MI->getOperand(0).getReg();
12272   MachineOperand &Base = MI->getOperand(1);
12273   MachineOperand &Scale = MI->getOperand(2);
12274   MachineOperand &Index = MI->getOperand(3);
12275   MachineOperand &Disp = MI->getOperand(4);
12276   MachineOperand &Segment = MI->getOperand(5);
12277   unsigned ArgSize = MI->getOperand(6).getImm();
12278   unsigned ArgMode = MI->getOperand(7).getImm();
12279   unsigned Align = MI->getOperand(8).getImm();
12280
12281   // Memory Reference
12282   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12283   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12284   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12285
12286   // Machine Information
12287   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12288   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12289   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12290   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12291   DebugLoc DL = MI->getDebugLoc();
12292
12293   // struct va_list {
12294   //   i32   gp_offset
12295   //   i32   fp_offset
12296   //   i64   overflow_area (address)
12297   //   i64   reg_save_area (address)
12298   // }
12299   // sizeof(va_list) = 24
12300   // alignment(va_list) = 8
12301
12302   unsigned TotalNumIntRegs = 6;
12303   unsigned TotalNumXMMRegs = 8;
12304   bool UseGPOffset = (ArgMode == 1);
12305   bool UseFPOffset = (ArgMode == 2);
12306   unsigned MaxOffset = TotalNumIntRegs * 8 +
12307                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12308
12309   /* Align ArgSize to a multiple of 8 */
12310   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12311   bool NeedsAlign = (Align > 8);
12312
12313   MachineBasicBlock *thisMBB = MBB;
12314   MachineBasicBlock *overflowMBB;
12315   MachineBasicBlock *offsetMBB;
12316   MachineBasicBlock *endMBB;
12317
12318   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
12319   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
12320   unsigned OffsetReg = 0;
12321
12322   if (!UseGPOffset && !UseFPOffset) {
12323     // If we only pull from the overflow region, we don't create a branch.
12324     // We don't need to alter control flow.
12325     OffsetDestReg = 0; // unused
12326     OverflowDestReg = DestReg;
12327
12328     offsetMBB = NULL;
12329     overflowMBB = thisMBB;
12330     endMBB = thisMBB;
12331   } else {
12332     // First emit code to check if gp_offset (or fp_offset) is below the bound.
12333     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12334     // If not, pull from overflow_area. (branch to overflowMBB)
12335     //
12336     //       thisMBB
12337     //         |     .
12338     //         |        .
12339     //     offsetMBB   overflowMBB
12340     //         |        .
12341     //         |     .
12342     //        endMBB
12343
12344     // Registers for the PHI in endMBB
12345     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12346     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12347
12348     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12349     MachineFunction *MF = MBB->getParent();
12350     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12351     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12352     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12353
12354     MachineFunction::iterator MBBIter = MBB;
12355     ++MBBIter;
12356
12357     // Insert the new basic blocks
12358     MF->insert(MBBIter, offsetMBB);
12359     MF->insert(MBBIter, overflowMBB);
12360     MF->insert(MBBIter, endMBB);
12361
12362     // Transfer the remainder of MBB and its successor edges to endMBB.
12363     endMBB->splice(endMBB->begin(), thisMBB,
12364                     llvm::next(MachineBasicBlock::iterator(MI)),
12365                     thisMBB->end());
12366     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12367
12368     // Make offsetMBB and overflowMBB successors of thisMBB
12369     thisMBB->addSuccessor(offsetMBB);
12370     thisMBB->addSuccessor(overflowMBB);
12371
12372     // endMBB is a successor of both offsetMBB and overflowMBB
12373     offsetMBB->addSuccessor(endMBB);
12374     overflowMBB->addSuccessor(endMBB);
12375
12376     // Load the offset value into a register
12377     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12378     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12379       .addOperand(Base)
12380       .addOperand(Scale)
12381       .addOperand(Index)
12382       .addDisp(Disp, UseFPOffset ? 4 : 0)
12383       .addOperand(Segment)
12384       .setMemRefs(MMOBegin, MMOEnd);
12385
12386     // Check if there is enough room left to pull this argument.
12387     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12388       .addReg(OffsetReg)
12389       .addImm(MaxOffset + 8 - ArgSizeA8);
12390
12391     // Branch to "overflowMBB" if offset >= max
12392     // Fall through to "offsetMBB" otherwise
12393     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12394       .addMBB(overflowMBB);
12395   }
12396
12397   // In offsetMBB, emit code to use the reg_save_area.
12398   if (offsetMBB) {
12399     assert(OffsetReg != 0);
12400
12401     // Read the reg_save_area address.
12402     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12403     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12404       .addOperand(Base)
12405       .addOperand(Scale)
12406       .addOperand(Index)
12407       .addDisp(Disp, 16)
12408       .addOperand(Segment)
12409       .setMemRefs(MMOBegin, MMOEnd);
12410
12411     // Zero-extend the offset
12412     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12413       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12414         .addImm(0)
12415         .addReg(OffsetReg)
12416         .addImm(X86::sub_32bit);
12417
12418     // Add the offset to the reg_save_area to get the final address.
12419     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12420       .addReg(OffsetReg64)
12421       .addReg(RegSaveReg);
12422
12423     // Compute the offset for the next argument
12424     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12425     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12426       .addReg(OffsetReg)
12427       .addImm(UseFPOffset ? 16 : 8);
12428
12429     // Store it back into the va_list.
12430     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12431       .addOperand(Base)
12432       .addOperand(Scale)
12433       .addOperand(Index)
12434       .addDisp(Disp, UseFPOffset ? 4 : 0)
12435       .addOperand(Segment)
12436       .addReg(NextOffsetReg)
12437       .setMemRefs(MMOBegin, MMOEnd);
12438
12439     // Jump to endMBB
12440     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12441       .addMBB(endMBB);
12442   }
12443
12444   //
12445   // Emit code to use overflow area
12446   //
12447
12448   // Load the overflow_area address into a register.
12449   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12450   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12451     .addOperand(Base)
12452     .addOperand(Scale)
12453     .addOperand(Index)
12454     .addDisp(Disp, 8)
12455     .addOperand(Segment)
12456     .setMemRefs(MMOBegin, MMOEnd);
12457
12458   // If we need to align it, do so. Otherwise, just copy the address
12459   // to OverflowDestReg.
12460   if (NeedsAlign) {
12461     // Align the overflow address
12462     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12463     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12464
12465     // aligned_addr = (addr + (align-1)) & ~(align-1)
12466     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12467       .addReg(OverflowAddrReg)
12468       .addImm(Align-1);
12469
12470     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12471       .addReg(TmpReg)
12472       .addImm(~(uint64_t)(Align-1));
12473   } else {
12474     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12475       .addReg(OverflowAddrReg);
12476   }
12477
12478   // Compute the next overflow address after this argument.
12479   // (the overflow address should be kept 8-byte aligned)
12480   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12481   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12482     .addReg(OverflowDestReg)
12483     .addImm(ArgSizeA8);
12484
12485   // Store the new overflow address.
12486   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12487     .addOperand(Base)
12488     .addOperand(Scale)
12489     .addOperand(Index)
12490     .addDisp(Disp, 8)
12491     .addOperand(Segment)
12492     .addReg(NextAddrReg)
12493     .setMemRefs(MMOBegin, MMOEnd);
12494
12495   // If we branched, emit the PHI to the front of endMBB.
12496   if (offsetMBB) {
12497     BuildMI(*endMBB, endMBB->begin(), DL,
12498             TII->get(X86::PHI), DestReg)
12499       .addReg(OffsetDestReg).addMBB(offsetMBB)
12500       .addReg(OverflowDestReg).addMBB(overflowMBB);
12501   }
12502
12503   // Erase the pseudo instruction
12504   MI->eraseFromParent();
12505
12506   return endMBB;
12507 }
12508
12509 MachineBasicBlock *
12510 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12511                                                  MachineInstr *MI,
12512                                                  MachineBasicBlock *MBB) const {
12513   // Emit code to save XMM registers to the stack. The ABI says that the
12514   // number of registers to save is given in %al, so it's theoretically
12515   // possible to do an indirect jump trick to avoid saving all of them,
12516   // however this code takes a simpler approach and just executes all
12517   // of the stores if %al is non-zero. It's less code, and it's probably
12518   // easier on the hardware branch predictor, and stores aren't all that
12519   // expensive anyway.
12520
12521   // Create the new basic blocks. One block contains all the XMM stores,
12522   // and one block is the final destination regardless of whether any
12523   // stores were performed.
12524   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12525   MachineFunction *F = MBB->getParent();
12526   MachineFunction::iterator MBBIter = MBB;
12527   ++MBBIter;
12528   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12529   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12530   F->insert(MBBIter, XMMSaveMBB);
12531   F->insert(MBBIter, EndMBB);
12532
12533   // Transfer the remainder of MBB and its successor edges to EndMBB.
12534   EndMBB->splice(EndMBB->begin(), MBB,
12535                  llvm::next(MachineBasicBlock::iterator(MI)),
12536                  MBB->end());
12537   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12538
12539   // The original block will now fall through to the XMM save block.
12540   MBB->addSuccessor(XMMSaveMBB);
12541   // The XMMSaveMBB will fall through to the end block.
12542   XMMSaveMBB->addSuccessor(EndMBB);
12543
12544   // Now add the instructions.
12545   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12546   DebugLoc DL = MI->getDebugLoc();
12547
12548   unsigned CountReg = MI->getOperand(0).getReg();
12549   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12550   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12551
12552   if (!Subtarget->isTargetWin64()) {
12553     // If %al is 0, branch around the XMM save block.
12554     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12555     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12556     MBB->addSuccessor(EndMBB);
12557   }
12558
12559   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12560   // In the XMM save block, save all the XMM argument registers.
12561   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12562     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12563     MachineMemOperand *MMO =
12564       F->getMachineMemOperand(
12565           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12566         MachineMemOperand::MOStore,
12567         /*Size=*/16, /*Align=*/16);
12568     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12569       .addFrameIndex(RegSaveFrameIndex)
12570       .addImm(/*Scale=*/1)
12571       .addReg(/*IndexReg=*/0)
12572       .addImm(/*Disp=*/Offset)
12573       .addReg(/*Segment=*/0)
12574       .addReg(MI->getOperand(i).getReg())
12575       .addMemOperand(MMO);
12576   }
12577
12578   MI->eraseFromParent();   // The pseudo instruction is gone now.
12579
12580   return EndMBB;
12581 }
12582
12583 // The EFLAGS operand of SelectItr might be missing a kill marker
12584 // because there were multiple uses of EFLAGS, and ISel didn't know
12585 // which to mark. Figure out whether SelectItr should have had a
12586 // kill marker, and set it if it should. Returns the correct kill
12587 // marker value.
12588 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12589                                      MachineBasicBlock* BB,
12590                                      const TargetRegisterInfo* TRI) {
12591   // Scan forward through BB for a use/def of EFLAGS.
12592   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12593   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12594     const MachineInstr& mi = *miI;
12595     if (mi.readsRegister(X86::EFLAGS))
12596       return false;
12597     if (mi.definesRegister(X86::EFLAGS))
12598       break; // Should have kill-flag - update below.
12599   }
12600
12601   // If we hit the end of the block, check whether EFLAGS is live into a
12602   // successor.
12603   if (miI == BB->end()) {
12604     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12605                                           sEnd = BB->succ_end();
12606          sItr != sEnd; ++sItr) {
12607       MachineBasicBlock* succ = *sItr;
12608       if (succ->isLiveIn(X86::EFLAGS))
12609         return false;
12610     }
12611   }
12612
12613   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12614   // out. SelectMI should have a kill flag on EFLAGS.
12615   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12616   return true;
12617 }
12618
12619 MachineBasicBlock *
12620 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12621                                      MachineBasicBlock *BB) const {
12622   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12623   DebugLoc DL = MI->getDebugLoc();
12624
12625   // To "insert" a SELECT_CC instruction, we actually have to insert the
12626   // diamond control-flow pattern.  The incoming instruction knows the
12627   // destination vreg to set, the condition code register to branch on, the
12628   // true/false values to select between, and a branch opcode to use.
12629   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12630   MachineFunction::iterator It = BB;
12631   ++It;
12632
12633   //  thisMBB:
12634   //  ...
12635   //   TrueVal = ...
12636   //   cmpTY ccX, r1, r2
12637   //   bCC copy1MBB
12638   //   fallthrough --> copy0MBB
12639   MachineBasicBlock *thisMBB = BB;
12640   MachineFunction *F = BB->getParent();
12641   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12642   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12643   F->insert(It, copy0MBB);
12644   F->insert(It, sinkMBB);
12645
12646   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12647   // live into the sink and copy blocks.
12648   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12649   if (!MI->killsRegister(X86::EFLAGS) &&
12650       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12651     copy0MBB->addLiveIn(X86::EFLAGS);
12652     sinkMBB->addLiveIn(X86::EFLAGS);
12653   }
12654
12655   // Transfer the remainder of BB and its successor edges to sinkMBB.
12656   sinkMBB->splice(sinkMBB->begin(), BB,
12657                   llvm::next(MachineBasicBlock::iterator(MI)),
12658                   BB->end());
12659   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12660
12661   // Add the true and fallthrough blocks as its successors.
12662   BB->addSuccessor(copy0MBB);
12663   BB->addSuccessor(sinkMBB);
12664
12665   // Create the conditional branch instruction.
12666   unsigned Opc =
12667     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12668   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12669
12670   //  copy0MBB:
12671   //   %FalseValue = ...
12672   //   # fallthrough to sinkMBB
12673   copy0MBB->addSuccessor(sinkMBB);
12674
12675   //  sinkMBB:
12676   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12677   //  ...
12678   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12679           TII->get(X86::PHI), MI->getOperand(0).getReg())
12680     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12681     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12682
12683   MI->eraseFromParent();   // The pseudo instruction is gone now.
12684   return sinkMBB;
12685 }
12686
12687 MachineBasicBlock *
12688 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12689                                         bool Is64Bit) const {
12690   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12691   DebugLoc DL = MI->getDebugLoc();
12692   MachineFunction *MF = BB->getParent();
12693   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12694
12695   assert(getTargetMachine().Options.EnableSegmentedStacks);
12696
12697   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12698   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12699
12700   // BB:
12701   //  ... [Till the alloca]
12702   // If stacklet is not large enough, jump to mallocMBB
12703   //
12704   // bumpMBB:
12705   //  Allocate by subtracting from RSP
12706   //  Jump to continueMBB
12707   //
12708   // mallocMBB:
12709   //  Allocate by call to runtime
12710   //
12711   // continueMBB:
12712   //  ...
12713   //  [rest of original BB]
12714   //
12715
12716   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12717   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12718   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12719
12720   MachineRegisterInfo &MRI = MF->getRegInfo();
12721   const TargetRegisterClass *AddrRegClass =
12722     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12723
12724   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12725     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12726     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12727     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12728     sizeVReg = MI->getOperand(1).getReg(),
12729     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12730
12731   MachineFunction::iterator MBBIter = BB;
12732   ++MBBIter;
12733
12734   MF->insert(MBBIter, bumpMBB);
12735   MF->insert(MBBIter, mallocMBB);
12736   MF->insert(MBBIter, continueMBB);
12737
12738   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12739                       (MachineBasicBlock::iterator(MI)), BB->end());
12740   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12741
12742   // Add code to the main basic block to check if the stack limit has been hit,
12743   // and if so, jump to mallocMBB otherwise to bumpMBB.
12744   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12745   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12746     .addReg(tmpSPVReg).addReg(sizeVReg);
12747   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12748     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12749     .addReg(SPLimitVReg);
12750   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12751
12752   // bumpMBB simply decreases the stack pointer, since we know the current
12753   // stacklet has enough space.
12754   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12755     .addReg(SPLimitVReg);
12756   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12757     .addReg(SPLimitVReg);
12758   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12759
12760   // Calls into a routine in libgcc to allocate more space from the heap.
12761   const uint32_t *RegMask =
12762     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12763   if (Is64Bit) {
12764     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12765       .addReg(sizeVReg);
12766     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12767       .addExternalSymbol("__morestack_allocate_stack_space")
12768       .addRegMask(RegMask)
12769       .addReg(X86::RDI, RegState::Implicit)
12770       .addReg(X86::RAX, RegState::ImplicitDefine);
12771   } else {
12772     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12773       .addImm(12);
12774     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12775     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12776       .addExternalSymbol("__morestack_allocate_stack_space")
12777       .addRegMask(RegMask)
12778       .addReg(X86::EAX, RegState::ImplicitDefine);
12779   }
12780
12781   if (!Is64Bit)
12782     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12783       .addImm(16);
12784
12785   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12786     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12787   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12788
12789   // Set up the CFG correctly.
12790   BB->addSuccessor(bumpMBB);
12791   BB->addSuccessor(mallocMBB);
12792   mallocMBB->addSuccessor(continueMBB);
12793   bumpMBB->addSuccessor(continueMBB);
12794
12795   // Take care of the PHI nodes.
12796   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12797           MI->getOperand(0).getReg())
12798     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12799     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12800
12801   // Delete the original pseudo instruction.
12802   MI->eraseFromParent();
12803
12804   // And we're done.
12805   return continueMBB;
12806 }
12807
12808 MachineBasicBlock *
12809 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12810                                           MachineBasicBlock *BB) const {
12811   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12812   DebugLoc DL = MI->getDebugLoc();
12813
12814   assert(!Subtarget->isTargetEnvMacho());
12815
12816   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12817   // non-trivial part is impdef of ESP.
12818
12819   if (Subtarget->isTargetWin64()) {
12820     if (Subtarget->isTargetCygMing()) {
12821       // ___chkstk(Mingw64):
12822       // Clobbers R10, R11, RAX and EFLAGS.
12823       // Updates RSP.
12824       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12825         .addExternalSymbol("___chkstk")
12826         .addReg(X86::RAX, RegState::Implicit)
12827         .addReg(X86::RSP, RegState::Implicit)
12828         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12829         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12830         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12831     } else {
12832       // __chkstk(MSVCRT): does not update stack pointer.
12833       // Clobbers R10, R11 and EFLAGS.
12834       // FIXME: RAX(allocated size) might be reused and not killed.
12835       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12836         .addExternalSymbol("__chkstk")
12837         .addReg(X86::RAX, RegState::Implicit)
12838         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12839       // RAX has the offset to subtracted from RSP.
12840       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12841         .addReg(X86::RSP)
12842         .addReg(X86::RAX);
12843     }
12844   } else {
12845     const char *StackProbeSymbol =
12846       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12847
12848     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12849       .addExternalSymbol(StackProbeSymbol)
12850       .addReg(X86::EAX, RegState::Implicit)
12851       .addReg(X86::ESP, RegState::Implicit)
12852       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12853       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12854       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12855   }
12856
12857   MI->eraseFromParent();   // The pseudo instruction is gone now.
12858   return BB;
12859 }
12860
12861 MachineBasicBlock *
12862 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12863                                       MachineBasicBlock *BB) const {
12864   // This is pretty easy.  We're taking the value that we received from
12865   // our load from the relocation, sticking it in either RDI (x86-64)
12866   // or EAX and doing an indirect call.  The return value will then
12867   // be in the normal return register.
12868   const X86InstrInfo *TII
12869     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12870   DebugLoc DL = MI->getDebugLoc();
12871   MachineFunction *F = BB->getParent();
12872
12873   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12874   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12875
12876   // Get a register mask for the lowered call.
12877   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12878   // proper register mask.
12879   const uint32_t *RegMask =
12880     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12881   if (Subtarget->is64Bit()) {
12882     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12883                                       TII->get(X86::MOV64rm), X86::RDI)
12884     .addReg(X86::RIP)
12885     .addImm(0).addReg(0)
12886     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12887                       MI->getOperand(3).getTargetFlags())
12888     .addReg(0);
12889     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12890     addDirectMem(MIB, X86::RDI);
12891     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12892   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12893     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12894                                       TII->get(X86::MOV32rm), X86::EAX)
12895     .addReg(0)
12896     .addImm(0).addReg(0)
12897     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12898                       MI->getOperand(3).getTargetFlags())
12899     .addReg(0);
12900     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12901     addDirectMem(MIB, X86::EAX);
12902     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12903   } else {
12904     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12905                                       TII->get(X86::MOV32rm), X86::EAX)
12906     .addReg(TII->getGlobalBaseReg(F))
12907     .addImm(0).addReg(0)
12908     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12909                       MI->getOperand(3).getTargetFlags())
12910     .addReg(0);
12911     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12912     addDirectMem(MIB, X86::EAX);
12913     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12914   }
12915
12916   MI->eraseFromParent(); // The pseudo instruction is gone now.
12917   return BB;
12918 }
12919
12920 MachineBasicBlock *
12921 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12922                                                MachineBasicBlock *BB) const {
12923   switch (MI->getOpcode()) {
12924   default: llvm_unreachable("Unexpected instr type to insert");
12925   case X86::TAILJMPd64:
12926   case X86::TAILJMPr64:
12927   case X86::TAILJMPm64:
12928     llvm_unreachable("TAILJMP64 would not be touched here.");
12929   case X86::TCRETURNdi64:
12930   case X86::TCRETURNri64:
12931   case X86::TCRETURNmi64:
12932     return BB;
12933   case X86::WIN_ALLOCA:
12934     return EmitLoweredWinAlloca(MI, BB);
12935   case X86::SEG_ALLOCA_32:
12936     return EmitLoweredSegAlloca(MI, BB, false);
12937   case X86::SEG_ALLOCA_64:
12938     return EmitLoweredSegAlloca(MI, BB, true);
12939   case X86::TLSCall_32:
12940   case X86::TLSCall_64:
12941     return EmitLoweredTLSCall(MI, BB);
12942   case X86::CMOV_GR8:
12943   case X86::CMOV_FR32:
12944   case X86::CMOV_FR64:
12945   case X86::CMOV_V4F32:
12946   case X86::CMOV_V2F64:
12947   case X86::CMOV_V2I64:
12948   case X86::CMOV_V8F32:
12949   case X86::CMOV_V4F64:
12950   case X86::CMOV_V4I64:
12951   case X86::CMOV_GR16:
12952   case X86::CMOV_GR32:
12953   case X86::CMOV_RFP32:
12954   case X86::CMOV_RFP64:
12955   case X86::CMOV_RFP80:
12956     return EmitLoweredSelect(MI, BB);
12957
12958   case X86::FP32_TO_INT16_IN_MEM:
12959   case X86::FP32_TO_INT32_IN_MEM:
12960   case X86::FP32_TO_INT64_IN_MEM:
12961   case X86::FP64_TO_INT16_IN_MEM:
12962   case X86::FP64_TO_INT32_IN_MEM:
12963   case X86::FP64_TO_INT64_IN_MEM:
12964   case X86::FP80_TO_INT16_IN_MEM:
12965   case X86::FP80_TO_INT32_IN_MEM:
12966   case X86::FP80_TO_INT64_IN_MEM: {
12967     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12968     DebugLoc DL = MI->getDebugLoc();
12969
12970     // Change the floating point control register to use "round towards zero"
12971     // mode when truncating to an integer value.
12972     MachineFunction *F = BB->getParent();
12973     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12974     addFrameReference(BuildMI(*BB, MI, DL,
12975                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12976
12977     // Load the old value of the high byte of the control word...
12978     unsigned OldCW =
12979       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12980     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12981                       CWFrameIdx);
12982
12983     // Set the high part to be round to zero...
12984     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12985       .addImm(0xC7F);
12986
12987     // Reload the modified control word now...
12988     addFrameReference(BuildMI(*BB, MI, DL,
12989                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12990
12991     // Restore the memory image of control word to original value
12992     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12993       .addReg(OldCW);
12994
12995     // Get the X86 opcode to use.
12996     unsigned Opc;
12997     switch (MI->getOpcode()) {
12998     default: llvm_unreachable("illegal opcode!");
12999     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13000     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13001     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13002     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13003     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13004     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13005     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13006     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13007     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13008     }
13009
13010     X86AddressMode AM;
13011     MachineOperand &Op = MI->getOperand(0);
13012     if (Op.isReg()) {
13013       AM.BaseType = X86AddressMode::RegBase;
13014       AM.Base.Reg = Op.getReg();
13015     } else {
13016       AM.BaseType = X86AddressMode::FrameIndexBase;
13017       AM.Base.FrameIndex = Op.getIndex();
13018     }
13019     Op = MI->getOperand(1);
13020     if (Op.isImm())
13021       AM.Scale = Op.getImm();
13022     Op = MI->getOperand(2);
13023     if (Op.isImm())
13024       AM.IndexReg = Op.getImm();
13025     Op = MI->getOperand(3);
13026     if (Op.isGlobal()) {
13027       AM.GV = Op.getGlobal();
13028     } else {
13029       AM.Disp = Op.getImm();
13030     }
13031     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13032                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13033
13034     // Reload the original control word now.
13035     addFrameReference(BuildMI(*BB, MI, DL,
13036                               TII->get(X86::FLDCW16m)), CWFrameIdx);
13037
13038     MI->eraseFromParent();   // The pseudo instruction is gone now.
13039     return BB;
13040   }
13041     // String/text processing lowering.
13042   case X86::PCMPISTRM128REG:
13043   case X86::VPCMPISTRM128REG:
13044   case X86::PCMPISTRM128MEM:
13045   case X86::VPCMPISTRM128MEM:
13046   case X86::PCMPESTRM128REG:
13047   case X86::VPCMPESTRM128REG:
13048   case X86::PCMPESTRM128MEM:
13049   case X86::VPCMPESTRM128MEM: {
13050     unsigned NumArgs;
13051     bool MemArg;
13052     switch (MI->getOpcode()) {
13053     default: llvm_unreachable("illegal opcode!");
13054     case X86::PCMPISTRM128REG:
13055     case X86::VPCMPISTRM128REG:
13056       NumArgs = 3; MemArg = false; break;
13057     case X86::PCMPISTRM128MEM:
13058     case X86::VPCMPISTRM128MEM:
13059       NumArgs = 3; MemArg = true; break;
13060     case X86::PCMPESTRM128REG:
13061     case X86::VPCMPESTRM128REG:
13062       NumArgs = 5; MemArg = false; break;
13063     case X86::PCMPESTRM128MEM:
13064     case X86::VPCMPESTRM128MEM:
13065       NumArgs = 5; MemArg = true; break;
13066     }
13067     return EmitPCMP(MI, BB, NumArgs, MemArg);
13068   }
13069
13070     // Thread synchronization.
13071   case X86::MONITOR:
13072     return EmitMonitor(MI, BB);
13073
13074     // Atomic Lowering.
13075   case X86::ATOMMIN32:
13076   case X86::ATOMMAX32:
13077   case X86::ATOMUMIN32:
13078   case X86::ATOMUMAX32:
13079   case X86::ATOMMIN16:
13080   case X86::ATOMMAX16:
13081   case X86::ATOMUMIN16:
13082   case X86::ATOMUMAX16:
13083   case X86::ATOMMIN64:
13084   case X86::ATOMMAX64:
13085   case X86::ATOMUMIN64:
13086   case X86::ATOMUMAX64: {
13087     unsigned Opc;
13088     switch (MI->getOpcode()) {
13089     default: llvm_unreachable("illegal opcode!");
13090     case X86::ATOMMIN32:  Opc = X86::CMOVL32rr; break;
13091     case X86::ATOMMAX32:  Opc = X86::CMOVG32rr; break;
13092     case X86::ATOMUMIN32: Opc = X86::CMOVB32rr; break;
13093     case X86::ATOMUMAX32: Opc = X86::CMOVA32rr; break;
13094     case X86::ATOMMIN16:  Opc = X86::CMOVL16rr; break;
13095     case X86::ATOMMAX16:  Opc = X86::CMOVG16rr; break;
13096     case X86::ATOMUMIN16: Opc = X86::CMOVB16rr; break;
13097     case X86::ATOMUMAX16: Opc = X86::CMOVA16rr; break;
13098     case X86::ATOMMIN64:  Opc = X86::CMOVL64rr; break;
13099     case X86::ATOMMAX64:  Opc = X86::CMOVG64rr; break;
13100     case X86::ATOMUMIN64: Opc = X86::CMOVB64rr; break;
13101     case X86::ATOMUMAX64: Opc = X86::CMOVA64rr; break;
13102     // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
13103     }
13104     return EmitAtomicMinMaxWithCustomInserter(MI, BB, Opc);
13105   }
13106
13107   case X86::ATOMAND32:
13108   case X86::ATOMOR32:
13109   case X86::ATOMXOR32:
13110   case X86::ATOMNAND32: {
13111     bool Invert = false;
13112     unsigned RegOpc, ImmOpc;
13113     switch (MI->getOpcode()) {
13114     default: llvm_unreachable("illegal opcode!");
13115     case X86::ATOMAND32:
13116       RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; break;
13117     case X86::ATOMOR32:
13118       RegOpc = X86::OR32rr;  ImmOpc = X86::OR32ri; break;
13119     case X86::ATOMXOR32:
13120       RegOpc = X86::XOR32rr; ImmOpc = X86::XOR32ri; break;
13121     case X86::ATOMNAND32:
13122       RegOpc = X86::AND32rr; ImmOpc = X86::AND32ri; Invert = true; break;
13123     }
13124     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13125                                                X86::MOV32rm, X86::LCMPXCHG32,
13126                                                X86::NOT32r, X86::EAX,
13127                                                &X86::GR32RegClass, Invert);
13128   }
13129
13130   case X86::ATOMAND16:
13131   case X86::ATOMOR16:
13132   case X86::ATOMXOR16:
13133   case X86::ATOMNAND16: {
13134     bool Invert = false;
13135     unsigned RegOpc, ImmOpc;
13136     switch (MI->getOpcode()) {
13137     default: llvm_unreachable("illegal opcode!");
13138     case X86::ATOMAND16:
13139       RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; break;
13140     case X86::ATOMOR16:
13141       RegOpc = X86::OR16rr;  ImmOpc = X86::OR16ri; break;
13142     case X86::ATOMXOR16:
13143       RegOpc = X86::XOR16rr; ImmOpc = X86::XOR16ri; break;
13144     case X86::ATOMNAND16:
13145       RegOpc = X86::AND16rr; ImmOpc = X86::AND16ri; Invert = true; break;
13146     }
13147     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13148                                                X86::MOV16rm, X86::LCMPXCHG16,
13149                                                X86::NOT16r, X86::AX,
13150                                                &X86::GR16RegClass, Invert);
13151   }
13152
13153   case X86::ATOMAND8:
13154   case X86::ATOMOR8:
13155   case X86::ATOMXOR8:
13156   case X86::ATOMNAND8: {
13157     bool Invert = false;
13158     unsigned RegOpc, ImmOpc;
13159     switch (MI->getOpcode()) {
13160     default: llvm_unreachable("illegal opcode!");
13161     case X86::ATOMAND8:
13162       RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; break;
13163     case X86::ATOMOR8:
13164       RegOpc = X86::OR8rr;  ImmOpc = X86::OR8ri; break;
13165     case X86::ATOMXOR8:
13166       RegOpc = X86::XOR8rr; ImmOpc = X86::XOR8ri; break;
13167     case X86::ATOMNAND8:
13168       RegOpc = X86::AND8rr; ImmOpc = X86::AND8ri; Invert = true; break;
13169     }
13170     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13171                                                X86::MOV8rm, X86::LCMPXCHG8,
13172                                                X86::NOT8r, X86::AL,
13173                                                &X86::GR8RegClass, Invert);
13174   }
13175
13176   // This group is for 64-bit host.
13177   case X86::ATOMAND64:
13178   case X86::ATOMOR64:
13179   case X86::ATOMXOR64:
13180   case X86::ATOMNAND64: {
13181     bool Invert = false;
13182     unsigned RegOpc, ImmOpc;
13183     switch (MI->getOpcode()) {
13184     default: llvm_unreachable("illegal opcode!");
13185     case X86::ATOMAND64:
13186       RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; break;
13187     case X86::ATOMOR64:
13188       RegOpc = X86::OR64rr;  ImmOpc = X86::OR64ri32; break;
13189     case X86::ATOMXOR64:
13190       RegOpc = X86::XOR64rr; ImmOpc = X86::XOR64ri32; break;
13191     case X86::ATOMNAND64:
13192       RegOpc = X86::AND64rr; ImmOpc = X86::AND64ri32; Invert = true; break;
13193     }
13194     return EmitAtomicBitwiseWithCustomInserter(MI, BB, RegOpc, ImmOpc,
13195                                                X86::MOV64rm, X86::LCMPXCHG64,
13196                                                X86::NOT64r, X86::RAX,
13197                                                &X86::GR64RegClass, Invert);
13198   }
13199
13200   // This group does 64-bit operations on a 32-bit host.
13201   case X86::ATOMAND6432:
13202   case X86::ATOMOR6432:
13203   case X86::ATOMXOR6432:
13204   case X86::ATOMNAND6432:
13205   case X86::ATOMADD6432:
13206   case X86::ATOMSUB6432:
13207   case X86::ATOMSWAP6432: {
13208     bool Invert = false;
13209     unsigned RegOpcL, RegOpcH, ImmOpcL, ImmOpcH;
13210     switch (MI->getOpcode()) {
13211     default: llvm_unreachable("illegal opcode!");
13212     case X86::ATOMAND6432:
13213       RegOpcL = RegOpcH = X86::AND32rr;
13214       ImmOpcL = ImmOpcH = X86::AND32ri;
13215       break;
13216     case X86::ATOMOR6432:
13217       RegOpcL = RegOpcH = X86::OR32rr;
13218       ImmOpcL = ImmOpcH = X86::OR32ri;
13219       break;
13220     case X86::ATOMXOR6432:
13221       RegOpcL = RegOpcH = X86::XOR32rr;
13222       ImmOpcL = ImmOpcH = X86::XOR32ri;
13223       break;
13224     case X86::ATOMNAND6432:
13225       RegOpcL = RegOpcH = X86::AND32rr;
13226       ImmOpcL = ImmOpcH = X86::AND32ri;
13227       Invert = true;
13228       break;
13229     case X86::ATOMADD6432:
13230       RegOpcL = X86::ADD32rr; RegOpcH = X86::ADC32rr;
13231       ImmOpcL = X86::ADD32ri; ImmOpcH = X86::ADC32ri;
13232       break;
13233     case X86::ATOMSUB6432:
13234       RegOpcL = X86::SUB32rr; RegOpcH = X86::SBB32rr;
13235       ImmOpcL = X86::SUB32ri; ImmOpcH = X86::SBB32ri;
13236       break;
13237     case X86::ATOMSWAP6432:
13238       RegOpcL = RegOpcH = X86::MOV32rr;
13239       ImmOpcL = ImmOpcH = X86::MOV32ri;
13240       break;
13241     }
13242     return EmitAtomicBit6432WithCustomInserter(MI, BB, RegOpcL, RegOpcH,
13243                                                ImmOpcL, ImmOpcH, Invert);
13244   }
13245
13246   case X86::VASTART_SAVE_XMM_REGS:
13247     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13248
13249   case X86::VAARG_64:
13250     return EmitVAARG64WithCustomInserter(MI, BB);
13251   }
13252 }
13253
13254 //===----------------------------------------------------------------------===//
13255 //                           X86 Optimization Hooks
13256 //===----------------------------------------------------------------------===//
13257
13258 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13259                                                        APInt &KnownZero,
13260                                                        APInt &KnownOne,
13261                                                        const SelectionDAG &DAG,
13262                                                        unsigned Depth) const {
13263   unsigned BitWidth = KnownZero.getBitWidth();
13264   unsigned Opc = Op.getOpcode();
13265   assert((Opc >= ISD::BUILTIN_OP_END ||
13266           Opc == ISD::INTRINSIC_WO_CHAIN ||
13267           Opc == ISD::INTRINSIC_W_CHAIN ||
13268           Opc == ISD::INTRINSIC_VOID) &&
13269          "Should use MaskedValueIsZero if you don't know whether Op"
13270          " is a target node!");
13271
13272   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
13273   switch (Opc) {
13274   default: break;
13275   case X86ISD::ADD:
13276   case X86ISD::SUB:
13277   case X86ISD::ADC:
13278   case X86ISD::SBB:
13279   case X86ISD::SMUL:
13280   case X86ISD::UMUL:
13281   case X86ISD::INC:
13282   case X86ISD::DEC:
13283   case X86ISD::OR:
13284   case X86ISD::XOR:
13285   case X86ISD::AND:
13286     // These nodes' second result is a boolean.
13287     if (Op.getResNo() == 0)
13288       break;
13289     // Fallthrough
13290   case X86ISD::SETCC:
13291     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13292     break;
13293   case ISD::INTRINSIC_WO_CHAIN: {
13294     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13295     unsigned NumLoBits = 0;
13296     switch (IntId) {
13297     default: break;
13298     case Intrinsic::x86_sse_movmsk_ps:
13299     case Intrinsic::x86_avx_movmsk_ps_256:
13300     case Intrinsic::x86_sse2_movmsk_pd:
13301     case Intrinsic::x86_avx_movmsk_pd_256:
13302     case Intrinsic::x86_mmx_pmovmskb:
13303     case Intrinsic::x86_sse2_pmovmskb_128:
13304     case Intrinsic::x86_avx2_pmovmskb: {
13305       // High bits of movmskp{s|d}, pmovmskb are known zero.
13306       switch (IntId) {
13307         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13308         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
13309         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
13310         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
13311         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
13312         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
13313         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
13314         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
13315       }
13316       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13317       break;
13318     }
13319     }
13320     break;
13321   }
13322   }
13323 }
13324
13325 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13326                                                          unsigned Depth) const {
13327   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13328   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13329     return Op.getValueType().getScalarType().getSizeInBits();
13330
13331   // Fallback case.
13332   return 1;
13333 }
13334
13335 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13336 /// node is a GlobalAddress + offset.
13337 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13338                                        const GlobalValue* &GA,
13339                                        int64_t &Offset) const {
13340   if (N->getOpcode() == X86ISD::Wrapper) {
13341     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13342       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13343       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13344       return true;
13345     }
13346   }
13347   return TargetLowering::isGAPlusOffset(N, GA, Offset);
13348 }
13349
13350 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13351 /// same as extracting the high 128-bit part of 256-bit vector and then
13352 /// inserting the result into the low part of a new 256-bit vector
13353 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13354   EVT VT = SVOp->getValueType(0);
13355   unsigned NumElems = VT.getVectorNumElements();
13356
13357   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13358   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13359     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13360         SVOp->getMaskElt(j) >= 0)
13361       return false;
13362
13363   return true;
13364 }
13365
13366 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13367 /// same as extracting the low 128-bit part of 256-bit vector and then
13368 /// inserting the result into the high part of a new 256-bit vector
13369 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13370   EVT VT = SVOp->getValueType(0);
13371   unsigned NumElems = VT.getVectorNumElements();
13372
13373   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13374   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13375     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13376         SVOp->getMaskElt(j) >= 0)
13377       return false;
13378
13379   return true;
13380 }
13381
13382 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13383 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13384                                         TargetLowering::DAGCombinerInfo &DCI,
13385                                         const X86Subtarget* Subtarget) {
13386   DebugLoc dl = N->getDebugLoc();
13387   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13388   SDValue V1 = SVOp->getOperand(0);
13389   SDValue V2 = SVOp->getOperand(1);
13390   EVT VT = SVOp->getValueType(0);
13391   unsigned NumElems = VT.getVectorNumElements();
13392
13393   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13394       V2.getOpcode() == ISD::CONCAT_VECTORS) {
13395     //
13396     //                   0,0,0,...
13397     //                      |
13398     //    V      UNDEF    BUILD_VECTOR    UNDEF
13399     //     \      /           \           /
13400     //  CONCAT_VECTOR         CONCAT_VECTOR
13401     //         \                  /
13402     //          \                /
13403     //          RESULT: V + zero extended
13404     //
13405     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13406         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13407         V1.getOperand(1).getOpcode() != ISD::UNDEF)
13408       return SDValue();
13409
13410     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13411       return SDValue();
13412
13413     // To match the shuffle mask, the first half of the mask should
13414     // be exactly the first vector, and all the rest a splat with the
13415     // first element of the second one.
13416     for (unsigned i = 0; i != NumElems/2; ++i)
13417       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13418           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13419         return SDValue();
13420
13421     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13422     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13423       if (Ld->hasNUsesOfValue(1, 0)) {
13424         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13425         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13426         SDValue ResNode =
13427           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13428                                   Ld->getMemoryVT(),
13429                                   Ld->getPointerInfo(),
13430                                   Ld->getAlignment(),
13431                                   false/*isVolatile*/, true/*ReadMem*/,
13432                                   false/*WriteMem*/);
13433         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13434       }
13435     }
13436
13437     // Emit a zeroed vector and insert the desired subvector on its
13438     // first half.
13439     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13440     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13441     return DCI.CombineTo(N, InsV);
13442   }
13443
13444   //===--------------------------------------------------------------------===//
13445   // Combine some shuffles into subvector extracts and inserts:
13446   //
13447
13448   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13449   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13450     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13451     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13452     return DCI.CombineTo(N, InsV);
13453   }
13454
13455   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13456   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13457     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13458     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13459     return DCI.CombineTo(N, InsV);
13460   }
13461
13462   return SDValue();
13463 }
13464
13465 /// PerformShuffleCombine - Performs several different shuffle combines.
13466 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13467                                      TargetLowering::DAGCombinerInfo &DCI,
13468                                      const X86Subtarget *Subtarget) {
13469   DebugLoc dl = N->getDebugLoc();
13470   EVT VT = N->getValueType(0);
13471
13472   // Don't create instructions with illegal types after legalize types has run.
13473   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13474   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13475     return SDValue();
13476
13477   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13478   if (Subtarget->hasAVX() && VT.is256BitVector() &&
13479       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13480     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13481
13482   // Only handle 128 wide vector from here on.
13483   if (!VT.is128BitVector())
13484     return SDValue();
13485
13486   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13487   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13488   // consecutive, non-overlapping, and in the right order.
13489   SmallVector<SDValue, 16> Elts;
13490   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13491     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13492
13493   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13494 }
13495
13496
13497 /// DCI, PerformTruncateCombine - Converts truncate operation to
13498 /// a sequence of vector shuffle operations.
13499 /// It is possible when we truncate 256-bit vector to 128-bit vector
13500
13501 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13502                                                   DAGCombinerInfo &DCI) const {
13503   if (!DCI.isBeforeLegalizeOps())
13504     return SDValue();
13505
13506   if (!Subtarget->hasAVX())
13507     return SDValue();
13508
13509   EVT VT = N->getValueType(0);
13510   SDValue Op = N->getOperand(0);
13511   EVT OpVT = Op.getValueType();
13512   DebugLoc dl = N->getDebugLoc();
13513
13514   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13515
13516     if (Subtarget->hasAVX2()) {
13517       // AVX2: v4i64 -> v4i32
13518
13519       // VPERMD
13520       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13521
13522       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13523       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13524                                 ShufMask);
13525
13526       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13527                          DAG.getIntPtrConstant(0));
13528     }
13529
13530     // AVX: v4i64 -> v4i32
13531     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13532                                DAG.getIntPtrConstant(0));
13533
13534     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13535                                DAG.getIntPtrConstant(2));
13536
13537     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13538     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13539
13540     // PSHUFD
13541     static const int ShufMask1[] = {0, 2, 0, 0};
13542
13543     SDValue Undef = DAG.getUNDEF(VT);
13544     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13545     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13546
13547     // MOVLHPS
13548     static const int ShufMask2[] = {0, 1, 4, 5};
13549
13550     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13551   }
13552
13553   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13554
13555     if (Subtarget->hasAVX2()) {
13556       // AVX2: v8i32 -> v8i16
13557
13558       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13559
13560       // PSHUFB
13561       SmallVector<SDValue,32> pshufbMask;
13562       for (unsigned i = 0; i < 2; ++i) {
13563         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13564         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13565         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13566         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13567         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13568         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13569         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13570         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13571         for (unsigned j = 0; j < 8; ++j)
13572           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13573       }
13574       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13575                                &pshufbMask[0], 32);
13576       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13577
13578       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13579
13580       static const int ShufMask[] = {0,  2,  -1,  -1};
13581       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13582                                 &ShufMask[0]);
13583
13584       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13585                        DAG.getIntPtrConstant(0));
13586
13587       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13588     }
13589
13590     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13591                                DAG.getIntPtrConstant(0));
13592
13593     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13594                                DAG.getIntPtrConstant(4));
13595
13596     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13597     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13598
13599     // PSHUFB
13600     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13601                                    -1, -1, -1, -1, -1, -1, -1, -1};
13602
13603     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13604     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13605     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13606
13607     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13608     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13609
13610     // MOVLHPS
13611     static const int ShufMask2[] = {0, 1, 4, 5};
13612
13613     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13614     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13615   }
13616
13617   return SDValue();
13618 }
13619
13620 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13621 /// specific shuffle of a load can be folded into a single element load.
13622 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13623 /// shuffles have been customed lowered so we need to handle those here.
13624 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13625                                          TargetLowering::DAGCombinerInfo &DCI) {
13626   if (DCI.isBeforeLegalizeOps())
13627     return SDValue();
13628
13629   SDValue InVec = N->getOperand(0);
13630   SDValue EltNo = N->getOperand(1);
13631
13632   if (!isa<ConstantSDNode>(EltNo))
13633     return SDValue();
13634
13635   EVT VT = InVec.getValueType();
13636
13637   bool HasShuffleIntoBitcast = false;
13638   if (InVec.getOpcode() == ISD::BITCAST) {
13639     // Don't duplicate a load with other uses.
13640     if (!InVec.hasOneUse())
13641       return SDValue();
13642     EVT BCVT = InVec.getOperand(0).getValueType();
13643     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13644       return SDValue();
13645     InVec = InVec.getOperand(0);
13646     HasShuffleIntoBitcast = true;
13647   }
13648
13649   if (!isTargetShuffle(InVec.getOpcode()))
13650     return SDValue();
13651
13652   // Don't duplicate a load with other uses.
13653   if (!InVec.hasOneUse())
13654     return SDValue();
13655
13656   SmallVector<int, 16> ShuffleMask;
13657   bool UnaryShuffle;
13658   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13659                             UnaryShuffle))
13660     return SDValue();
13661
13662   // Select the input vector, guarding against out of range extract vector.
13663   unsigned NumElems = VT.getVectorNumElements();
13664   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13665   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13666   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13667                                          : InVec.getOperand(1);
13668
13669   // If inputs to shuffle are the same for both ops, then allow 2 uses
13670   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13671
13672   if (LdNode.getOpcode() == ISD::BITCAST) {
13673     // Don't duplicate a load with other uses.
13674     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13675       return SDValue();
13676
13677     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13678     LdNode = LdNode.getOperand(0);
13679   }
13680
13681   if (!ISD::isNormalLoad(LdNode.getNode()))
13682     return SDValue();
13683
13684   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13685
13686   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13687     return SDValue();
13688
13689   if (HasShuffleIntoBitcast) {
13690     // If there's a bitcast before the shuffle, check if the load type and
13691     // alignment is valid.
13692     unsigned Align = LN0->getAlignment();
13693     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13694     unsigned NewAlign = TLI.getTargetData()->
13695       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13696
13697     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13698       return SDValue();
13699   }
13700
13701   // All checks match so transform back to vector_shuffle so that DAG combiner
13702   // can finish the job
13703   DebugLoc dl = N->getDebugLoc();
13704
13705   // Create shuffle node taking into account the case that its a unary shuffle
13706   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13707   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13708                                  InVec.getOperand(0), Shuffle,
13709                                  &ShuffleMask[0]);
13710   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13711   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13712                      EltNo);
13713 }
13714
13715 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13716 /// generation and convert it from being a bunch of shuffles and extracts
13717 /// to a simple store and scalar loads to extract the elements.
13718 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13719                                          TargetLowering::DAGCombinerInfo &DCI) {
13720   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13721   if (NewOp.getNode())
13722     return NewOp;
13723
13724   SDValue InputVector = N->getOperand(0);
13725
13726   // Only operate on vectors of 4 elements, where the alternative shuffling
13727   // gets to be more expensive.
13728   if (InputVector.getValueType() != MVT::v4i32)
13729     return SDValue();
13730
13731   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13732   // single use which is a sign-extend or zero-extend, and all elements are
13733   // used.
13734   SmallVector<SDNode *, 4> Uses;
13735   unsigned ExtractedElements = 0;
13736   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13737        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13738     if (UI.getUse().getResNo() != InputVector.getResNo())
13739       return SDValue();
13740
13741     SDNode *Extract = *UI;
13742     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13743       return SDValue();
13744
13745     if (Extract->getValueType(0) != MVT::i32)
13746       return SDValue();
13747     if (!Extract->hasOneUse())
13748       return SDValue();
13749     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13750         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13751       return SDValue();
13752     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13753       return SDValue();
13754
13755     // Record which element was extracted.
13756     ExtractedElements |=
13757       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13758
13759     Uses.push_back(Extract);
13760   }
13761
13762   // If not all the elements were used, this may not be worthwhile.
13763   if (ExtractedElements != 15)
13764     return SDValue();
13765
13766   // Ok, we've now decided to do the transformation.
13767   DebugLoc dl = InputVector.getDebugLoc();
13768
13769   // Store the value to a temporary stack slot.
13770   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13771   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13772                             MachinePointerInfo(), false, false, 0);
13773
13774   // Replace each use (extract) with a load of the appropriate element.
13775   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13776        UE = Uses.end(); UI != UE; ++UI) {
13777     SDNode *Extract = *UI;
13778
13779     // cOMpute the element's address.
13780     SDValue Idx = Extract->getOperand(1);
13781     unsigned EltSize =
13782         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13783     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13784     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13785     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13786
13787     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13788                                      StackPtr, OffsetVal);
13789
13790     // Load the scalar.
13791     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13792                                      ScalarAddr, MachinePointerInfo(),
13793                                      false, false, false, 0);
13794
13795     // Replace the exact with the load.
13796     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13797   }
13798
13799   // The replacement was made in place; don't return anything.
13800   return SDValue();
13801 }
13802
13803 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13804 /// nodes.
13805 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13806                                     TargetLowering::DAGCombinerInfo &DCI,
13807                                     const X86Subtarget *Subtarget) {
13808   DebugLoc DL = N->getDebugLoc();
13809   SDValue Cond = N->getOperand(0);
13810   // Get the LHS/RHS of the select.
13811   SDValue LHS = N->getOperand(1);
13812   SDValue RHS = N->getOperand(2);
13813   EVT VT = LHS.getValueType();
13814
13815   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13816   // instructions match the semantics of the common C idiom x<y?x:y but not
13817   // x<=y?x:y, because of how they handle negative zero (which can be
13818   // ignored in unsafe-math mode).
13819   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13820       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13821       (Subtarget->hasSSE2() ||
13822        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13823     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13824
13825     unsigned Opcode = 0;
13826     // Check for x CC y ? x : y.
13827     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13828         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13829       switch (CC) {
13830       default: break;
13831       case ISD::SETULT:
13832         // Converting this to a min would handle NaNs incorrectly, and swapping
13833         // the operands would cause it to handle comparisons between positive
13834         // and negative zero incorrectly.
13835         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13836           if (!DAG.getTarget().Options.UnsafeFPMath &&
13837               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13838             break;
13839           std::swap(LHS, RHS);
13840         }
13841         Opcode = X86ISD::FMIN;
13842         break;
13843       case ISD::SETOLE:
13844         // Converting this to a min would handle comparisons between positive
13845         // and negative zero incorrectly.
13846         if (!DAG.getTarget().Options.UnsafeFPMath &&
13847             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13848           break;
13849         Opcode = X86ISD::FMIN;
13850         break;
13851       case ISD::SETULE:
13852         // Converting this to a min would handle both negative zeros and NaNs
13853         // incorrectly, but we can swap the operands to fix both.
13854         std::swap(LHS, RHS);
13855       case ISD::SETOLT:
13856       case ISD::SETLT:
13857       case ISD::SETLE:
13858         Opcode = X86ISD::FMIN;
13859         break;
13860
13861       case ISD::SETOGE:
13862         // Converting this to a max would handle comparisons between positive
13863         // and negative zero incorrectly.
13864         if (!DAG.getTarget().Options.UnsafeFPMath &&
13865             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13866           break;
13867         Opcode = X86ISD::FMAX;
13868         break;
13869       case ISD::SETUGT:
13870         // Converting this to a max would handle NaNs incorrectly, and swapping
13871         // the operands would cause it to handle comparisons between positive
13872         // and negative zero incorrectly.
13873         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13874           if (!DAG.getTarget().Options.UnsafeFPMath &&
13875               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13876             break;
13877           std::swap(LHS, RHS);
13878         }
13879         Opcode = X86ISD::FMAX;
13880         break;
13881       case ISD::SETUGE:
13882         // Converting this to a max would handle both negative zeros and NaNs
13883         // incorrectly, but we can swap the operands to fix both.
13884         std::swap(LHS, RHS);
13885       case ISD::SETOGT:
13886       case ISD::SETGT:
13887       case ISD::SETGE:
13888         Opcode = X86ISD::FMAX;
13889         break;
13890       }
13891     // Check for x CC y ? y : x -- a min/max with reversed arms.
13892     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13893                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13894       switch (CC) {
13895       default: break;
13896       case ISD::SETOGE:
13897         // Converting this to a min would handle comparisons between positive
13898         // and negative zero incorrectly, and swapping the operands would
13899         // cause it to handle NaNs incorrectly.
13900         if (!DAG.getTarget().Options.UnsafeFPMath &&
13901             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13902           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13903             break;
13904           std::swap(LHS, RHS);
13905         }
13906         Opcode = X86ISD::FMIN;
13907         break;
13908       case ISD::SETUGT:
13909         // Converting this to a min would handle NaNs incorrectly.
13910         if (!DAG.getTarget().Options.UnsafeFPMath &&
13911             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13912           break;
13913         Opcode = X86ISD::FMIN;
13914         break;
13915       case ISD::SETUGE:
13916         // Converting this to a min would handle both negative zeros and NaNs
13917         // incorrectly, but we can swap the operands to fix both.
13918         std::swap(LHS, RHS);
13919       case ISD::SETOGT:
13920       case ISD::SETGT:
13921       case ISD::SETGE:
13922         Opcode = X86ISD::FMIN;
13923         break;
13924
13925       case ISD::SETULT:
13926         // Converting this to a max would handle NaNs incorrectly.
13927         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13928           break;
13929         Opcode = X86ISD::FMAX;
13930         break;
13931       case ISD::SETOLE:
13932         // Converting this to a max would handle comparisons between positive
13933         // and negative zero incorrectly, and swapping the operands would
13934         // cause it to handle NaNs incorrectly.
13935         if (!DAG.getTarget().Options.UnsafeFPMath &&
13936             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13937           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13938             break;
13939           std::swap(LHS, RHS);
13940         }
13941         Opcode = X86ISD::FMAX;
13942         break;
13943       case ISD::SETULE:
13944         // Converting this to a max would handle both negative zeros and NaNs
13945         // incorrectly, but we can swap the operands to fix both.
13946         std::swap(LHS, RHS);
13947       case ISD::SETOLT:
13948       case ISD::SETLT:
13949       case ISD::SETLE:
13950         Opcode = X86ISD::FMAX;
13951         break;
13952       }
13953     }
13954
13955     if (Opcode)
13956       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13957   }
13958
13959   // If this is a select between two integer constants, try to do some
13960   // optimizations.
13961   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13962     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13963       // Don't do this for crazy integer types.
13964       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13965         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13966         // so that TrueC (the true value) is larger than FalseC.
13967         bool NeedsCondInvert = false;
13968
13969         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13970             // Efficiently invertible.
13971             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13972              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13973               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13974           NeedsCondInvert = true;
13975           std::swap(TrueC, FalseC);
13976         }
13977
13978         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13979         if (FalseC->getAPIntValue() == 0 &&
13980             TrueC->getAPIntValue().isPowerOf2()) {
13981           if (NeedsCondInvert) // Invert the condition if needed.
13982             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13983                                DAG.getConstant(1, Cond.getValueType()));
13984
13985           // Zero extend the condition if needed.
13986           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13987
13988           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13989           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13990                              DAG.getConstant(ShAmt, MVT::i8));
13991         }
13992
13993         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13994         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13995           if (NeedsCondInvert) // Invert the condition if needed.
13996             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13997                                DAG.getConstant(1, Cond.getValueType()));
13998
13999           // Zero extend the condition if needed.
14000           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14001                              FalseC->getValueType(0), Cond);
14002           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14003                              SDValue(FalseC, 0));
14004         }
14005
14006         // Optimize cases that will turn into an LEA instruction.  This requires
14007         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14008         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14009           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14010           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14011
14012           bool isFastMultiplier = false;
14013           if (Diff < 10) {
14014             switch ((unsigned char)Diff) {
14015               default: break;
14016               case 1:  // result = add base, cond
14017               case 2:  // result = lea base(    , cond*2)
14018               case 3:  // result = lea base(cond, cond*2)
14019               case 4:  // result = lea base(    , cond*4)
14020               case 5:  // result = lea base(cond, cond*4)
14021               case 8:  // result = lea base(    , cond*8)
14022               case 9:  // result = lea base(cond, cond*8)
14023                 isFastMultiplier = true;
14024                 break;
14025             }
14026           }
14027
14028           if (isFastMultiplier) {
14029             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14030             if (NeedsCondInvert) // Invert the condition if needed.
14031               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14032                                  DAG.getConstant(1, Cond.getValueType()));
14033
14034             // Zero extend the condition if needed.
14035             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14036                                Cond);
14037             // Scale the condition by the difference.
14038             if (Diff != 1)
14039               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14040                                  DAG.getConstant(Diff, Cond.getValueType()));
14041
14042             // Add the base if non-zero.
14043             if (FalseC->getAPIntValue() != 0)
14044               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14045                                  SDValue(FalseC, 0));
14046             return Cond;
14047           }
14048         }
14049       }
14050   }
14051
14052   // Canonicalize max and min:
14053   // (x > y) ? x : y -> (x >= y) ? x : y
14054   // (x < y) ? x : y -> (x <= y) ? x : y
14055   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14056   // the need for an extra compare
14057   // against zero. e.g.
14058   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14059   // subl   %esi, %edi
14060   // testl  %edi, %edi
14061   // movl   $0, %eax
14062   // cmovgl %edi, %eax
14063   // =>
14064   // xorl   %eax, %eax
14065   // subl   %esi, $edi
14066   // cmovsl %eax, %edi
14067   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14068       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14069       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14070     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14071     switch (CC) {
14072     default: break;
14073     case ISD::SETLT:
14074     case ISD::SETGT: {
14075       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14076       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14077                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
14078       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14079     }
14080     }
14081   }
14082
14083   // If we know that this node is legal then we know that it is going to be
14084   // matched by one of the SSE/AVX BLEND instructions. These instructions only
14085   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14086   // to simplify previous instructions.
14087   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14088   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14089       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14090     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14091
14092     // Don't optimize vector selects that map to mask-registers.
14093     if (BitWidth == 1)
14094       return SDValue();
14095
14096     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14097     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14098
14099     APInt KnownZero, KnownOne;
14100     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14101                                           DCI.isBeforeLegalizeOps());
14102     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14103         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14104       DCI.CommitTargetLoweringOpt(TLO);
14105   }
14106
14107   return SDValue();
14108 }
14109
14110 // Check whether a boolean test is testing a boolean value generated by
14111 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14112 // code.
14113 //
14114 // Simplify the following patterns:
14115 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14116 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14117 // to (Op EFLAGS Cond)
14118 //
14119 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14120 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14121 // to (Op EFLAGS !Cond)
14122 //
14123 // where Op could be BRCOND or CMOV.
14124 //
14125 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14126   // Quit if not CMP and SUB with its value result used.
14127   if (Cmp.getOpcode() != X86ISD::CMP &&
14128       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14129       return SDValue();
14130
14131   // Quit if not used as a boolean value.
14132   if (CC != X86::COND_E && CC != X86::COND_NE)
14133     return SDValue();
14134
14135   // Check CMP operands. One of them should be 0 or 1 and the other should be
14136   // an SetCC or extended from it.
14137   SDValue Op1 = Cmp.getOperand(0);
14138   SDValue Op2 = Cmp.getOperand(1);
14139
14140   SDValue SetCC;
14141   const ConstantSDNode* C = 0;
14142   bool needOppositeCond = (CC == X86::COND_E);
14143
14144   if ((C = dyn_cast<ConstantSDNode>(Op1)))
14145     SetCC = Op2;
14146   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14147     SetCC = Op1;
14148   else // Quit if all operands are not constants.
14149     return SDValue();
14150
14151   if (C->getZExtValue() == 1)
14152     needOppositeCond = !needOppositeCond;
14153   else if (C->getZExtValue() != 0)
14154     // Quit if the constant is neither 0 or 1.
14155     return SDValue();
14156
14157   // Skip 'zext' node.
14158   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14159     SetCC = SetCC.getOperand(0);
14160
14161   switch (SetCC.getOpcode()) {
14162   case X86ISD::SETCC:
14163     // Set the condition code or opposite one if necessary.
14164     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14165     if (needOppositeCond)
14166       CC = X86::GetOppositeBranchCondition(CC);
14167     return SetCC.getOperand(1);
14168   case X86ISD::CMOV: {
14169     // Check whether false/true value has canonical one, i.e. 0 or 1.
14170     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14171     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14172     // Quit if true value is not a constant.
14173     if (!TVal)
14174       return SDValue();
14175     // Quit if false value is not a constant.
14176     if (!FVal) {
14177       // A special case for rdrand, where 0 is set if false cond is found.
14178       SDValue Op = SetCC.getOperand(0);
14179       if (Op.getOpcode() != X86ISD::RDRAND)
14180         return SDValue();
14181     }
14182     // Quit if false value is not the constant 0 or 1.
14183     bool FValIsFalse = true;
14184     if (FVal && FVal->getZExtValue() != 0) {
14185       if (FVal->getZExtValue() != 1)
14186         return SDValue();
14187       // If FVal is 1, opposite cond is needed.
14188       needOppositeCond = !needOppositeCond;
14189       FValIsFalse = false;
14190     }
14191     // Quit if TVal is not the constant opposite of FVal.
14192     if (FValIsFalse && TVal->getZExtValue() != 1)
14193       return SDValue();
14194     if (!FValIsFalse && TVal->getZExtValue() != 0)
14195       return SDValue();
14196     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14197     if (needOppositeCond)
14198       CC = X86::GetOppositeBranchCondition(CC);
14199     return SetCC.getOperand(3);
14200   }
14201   }
14202
14203   return SDValue();
14204 }
14205
14206 /// checkFlaggedOrCombine - DAG combination on X86ISD::OR, i.e. with EFLAGS
14207 /// updated. If only flag result is used and the result is evaluated from a
14208 /// series of element extraction, try to combine it into a PTEST.
14209 static SDValue checkFlaggedOrCombine(SDValue Or, X86::CondCode &CC,
14210                                      SelectionDAG &DAG,
14211                                      const X86Subtarget *Subtarget) {
14212   SDNode *N = Or.getNode();
14213   DebugLoc DL = N->getDebugLoc();
14214
14215   // Only SSE4.1 and beyond supports PTEST or like.
14216   if (!Subtarget->hasSSE41())
14217     return SDValue();
14218
14219   if (N->getOpcode() != X86ISD::OR)
14220     return SDValue();
14221
14222   // Quit if the value result of OR is used.
14223   if (N->hasAnyUseOfValue(0))
14224     return SDValue();
14225
14226   // Quit if not used as a boolean value.
14227   if (CC != X86::COND_E && CC != X86::COND_NE)
14228     return SDValue();
14229
14230   SmallVector<SDValue, 8> Opnds;
14231   SDValue VecIn;
14232   EVT VT = MVT::Other;
14233   unsigned Mask = 0;
14234
14235   // Recognize a special case where a vector is casted into wide integer to
14236   // test all 0s.
14237   Opnds.push_back(N->getOperand(0));
14238   Opnds.push_back(N->getOperand(1));
14239
14240   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
14241     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
14242     // BFS traverse all OR'd operands.
14243     if (I->getOpcode() == ISD::OR) {
14244       Opnds.push_back(I->getOperand(0));
14245       Opnds.push_back(I->getOperand(1));
14246       // Re-evaluate the number of nodes to be traversed.
14247       e += 2; // 2 more nodes (LHS and RHS) are pushed.
14248       continue;
14249     }
14250
14251     // Quit if a non-EXTRACT_VECTOR_ELT
14252     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14253       return SDValue();
14254
14255     // Quit if without a constant index.
14256     SDValue Idx = I->getOperand(1);
14257     if (!isa<ConstantSDNode>(Idx))
14258       return SDValue();
14259
14260     // Check if all elements are extracted from the same vector.
14261     SDValue ExtractedFromVec = I->getOperand(0);
14262     if (VecIn.getNode() == 0) {
14263       VT = ExtractedFromVec.getValueType();
14264       // FIXME: only 128-bit vector is supported so far.
14265       if (!VT.is128BitVector())
14266         return SDValue();
14267       VecIn = ExtractedFromVec;
14268     } else if (VecIn != ExtractedFromVec)
14269       return SDValue();
14270
14271     // Record the constant index.
14272     Mask |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
14273   }
14274
14275   assert(VT.is128BitVector() && "Only 128-bit vector PTEST is supported so far.");
14276
14277   // Quit if not all elements are used.
14278   if (Mask != (1U << VT.getVectorNumElements()) - 1U)
14279     return SDValue();
14280
14281   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIn, VecIn);
14282 }
14283
14284 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14285 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14286                                   TargetLowering::DAGCombinerInfo &DCI,
14287                                   const X86Subtarget *Subtarget) {
14288   DebugLoc DL = N->getDebugLoc();
14289
14290   // If the flag operand isn't dead, don't touch this CMOV.
14291   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14292     return SDValue();
14293
14294   SDValue FalseOp = N->getOperand(0);
14295   SDValue TrueOp = N->getOperand(1);
14296   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14297   SDValue Cond = N->getOperand(3);
14298
14299   if (CC == X86::COND_E || CC == X86::COND_NE) {
14300     switch (Cond.getOpcode()) {
14301     default: break;
14302     case X86ISD::BSR:
14303     case X86ISD::BSF:
14304       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14305       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14306         return (CC == X86::COND_E) ? FalseOp : TrueOp;
14307     }
14308   }
14309
14310   SDValue Flags;
14311
14312   Flags = checkBoolTestSetCCCombine(Cond, CC);
14313   if (Flags.getNode() &&
14314       // Extra check as FCMOV only supports a subset of X86 cond.
14315       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14316     SDValue Ops[] = { FalseOp, TrueOp,
14317                       DAG.getConstant(CC, MVT::i8), Flags };
14318     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14319                        Ops, array_lengthof(Ops));
14320   }
14321
14322   Flags = checkFlaggedOrCombine(Cond, CC, DAG, Subtarget);
14323   if (Flags.getNode()) {
14324     SDValue Ops[] = { FalseOp, TrueOp,
14325                       DAG.getConstant(CC, MVT::i8), Flags };
14326     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14327                        Ops, array_lengthof(Ops));
14328   }
14329
14330   // If this is a select between two integer constants, try to do some
14331   // optimizations.  Note that the operands are ordered the opposite of SELECT
14332   // operands.
14333   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14334     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14335       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14336       // larger than FalseC (the false value).
14337       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14338         CC = X86::GetOppositeBranchCondition(CC);
14339         std::swap(TrueC, FalseC);
14340       }
14341
14342       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
14343       // This is efficient for any integer data type (including i8/i16) and
14344       // shift amount.
14345       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14346         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14347                            DAG.getConstant(CC, MVT::i8), Cond);
14348
14349         // Zero extend the condition if needed.
14350         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14351
14352         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14353         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14354                            DAG.getConstant(ShAmt, MVT::i8));
14355         if (N->getNumValues() == 2)  // Dead flag value?
14356           return DCI.CombineTo(N, Cond, SDValue());
14357         return Cond;
14358       }
14359
14360       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
14361       // for any integer data type, including i8/i16.
14362       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14363         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14364                            DAG.getConstant(CC, MVT::i8), Cond);
14365
14366         // Zero extend the condition if needed.
14367         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14368                            FalseC->getValueType(0), Cond);
14369         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14370                            SDValue(FalseC, 0));
14371
14372         if (N->getNumValues() == 2)  // Dead flag value?
14373           return DCI.CombineTo(N, Cond, SDValue());
14374         return Cond;
14375       }
14376
14377       // Optimize cases that will turn into an LEA instruction.  This requires
14378       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14379       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14380         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14381         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14382
14383         bool isFastMultiplier = false;
14384         if (Diff < 10) {
14385           switch ((unsigned char)Diff) {
14386           default: break;
14387           case 1:  // result = add base, cond
14388           case 2:  // result = lea base(    , cond*2)
14389           case 3:  // result = lea base(cond, cond*2)
14390           case 4:  // result = lea base(    , cond*4)
14391           case 5:  // result = lea base(cond, cond*4)
14392           case 8:  // result = lea base(    , cond*8)
14393           case 9:  // result = lea base(cond, cond*8)
14394             isFastMultiplier = true;
14395             break;
14396           }
14397         }
14398
14399         if (isFastMultiplier) {
14400           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14401           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14402                              DAG.getConstant(CC, MVT::i8), Cond);
14403           // Zero extend the condition if needed.
14404           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14405                              Cond);
14406           // Scale the condition by the difference.
14407           if (Diff != 1)
14408             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14409                                DAG.getConstant(Diff, Cond.getValueType()));
14410
14411           // Add the base if non-zero.
14412           if (FalseC->getAPIntValue() != 0)
14413             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14414                                SDValue(FalseC, 0));
14415           if (N->getNumValues() == 2)  // Dead flag value?
14416             return DCI.CombineTo(N, Cond, SDValue());
14417           return Cond;
14418         }
14419       }
14420     }
14421   }
14422   return SDValue();
14423 }
14424
14425
14426 /// PerformMulCombine - Optimize a single multiply with constant into two
14427 /// in order to implement it with two cheaper instructions, e.g.
14428 /// LEA + SHL, LEA + LEA.
14429 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14430                                  TargetLowering::DAGCombinerInfo &DCI) {
14431   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14432     return SDValue();
14433
14434   EVT VT = N->getValueType(0);
14435   if (VT != MVT::i64)
14436     return SDValue();
14437
14438   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14439   if (!C)
14440     return SDValue();
14441   uint64_t MulAmt = C->getZExtValue();
14442   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14443     return SDValue();
14444
14445   uint64_t MulAmt1 = 0;
14446   uint64_t MulAmt2 = 0;
14447   if ((MulAmt % 9) == 0) {
14448     MulAmt1 = 9;
14449     MulAmt2 = MulAmt / 9;
14450   } else if ((MulAmt % 5) == 0) {
14451     MulAmt1 = 5;
14452     MulAmt2 = MulAmt / 5;
14453   } else if ((MulAmt % 3) == 0) {
14454     MulAmt1 = 3;
14455     MulAmt2 = MulAmt / 3;
14456   }
14457   if (MulAmt2 &&
14458       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14459     DebugLoc DL = N->getDebugLoc();
14460
14461     if (isPowerOf2_64(MulAmt2) &&
14462         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14463       // If second multiplifer is pow2, issue it first. We want the multiply by
14464       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14465       // is an add.
14466       std::swap(MulAmt1, MulAmt2);
14467
14468     SDValue NewMul;
14469     if (isPowerOf2_64(MulAmt1))
14470       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14471                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14472     else
14473       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14474                            DAG.getConstant(MulAmt1, VT));
14475
14476     if (isPowerOf2_64(MulAmt2))
14477       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14478                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14479     else
14480       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14481                            DAG.getConstant(MulAmt2, VT));
14482
14483     // Do not add new nodes to DAG combiner worklist.
14484     DCI.CombineTo(N, NewMul, false);
14485   }
14486   return SDValue();
14487 }
14488
14489 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14490   SDValue N0 = N->getOperand(0);
14491   SDValue N1 = N->getOperand(1);
14492   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14493   EVT VT = N0.getValueType();
14494
14495   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14496   // since the result of setcc_c is all zero's or all ones.
14497   if (VT.isInteger() && !VT.isVector() &&
14498       N1C && N0.getOpcode() == ISD::AND &&
14499       N0.getOperand(1).getOpcode() == ISD::Constant) {
14500     SDValue N00 = N0.getOperand(0);
14501     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14502         ((N00.getOpcode() == ISD::ANY_EXTEND ||
14503           N00.getOpcode() == ISD::ZERO_EXTEND) &&
14504          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14505       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14506       APInt ShAmt = N1C->getAPIntValue();
14507       Mask = Mask.shl(ShAmt);
14508       if (Mask != 0)
14509         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14510                            N00, DAG.getConstant(Mask, VT));
14511     }
14512   }
14513
14514
14515   // Hardware support for vector shifts is sparse which makes us scalarize the
14516   // vector operations in many cases. Also, on sandybridge ADD is faster than
14517   // shl.
14518   // (shl V, 1) -> add V,V
14519   if (isSplatVector(N1.getNode())) {
14520     assert(N0.getValueType().isVector() && "Invalid vector shift type");
14521     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14522     // We shift all of the values by one. In many cases we do not have
14523     // hardware support for this operation. This is better expressed as an ADD
14524     // of two values.
14525     if (N1C && (1 == N1C->getZExtValue())) {
14526       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14527     }
14528   }
14529
14530   return SDValue();
14531 }
14532
14533 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14534 ///                       when possible.
14535 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14536                                    TargetLowering::DAGCombinerInfo &DCI,
14537                                    const X86Subtarget *Subtarget) {
14538   EVT VT = N->getValueType(0);
14539   if (N->getOpcode() == ISD::SHL) {
14540     SDValue V = PerformSHLCombine(N, DAG);
14541     if (V.getNode()) return V;
14542   }
14543
14544   // On X86 with SSE2 support, we can transform this to a vector shift if
14545   // all elements are shifted by the same amount.  We can't do this in legalize
14546   // because the a constant vector is typically transformed to a constant pool
14547   // so we have no knowledge of the shift amount.
14548   if (!Subtarget->hasSSE2())
14549     return SDValue();
14550
14551   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14552       (!Subtarget->hasAVX2() ||
14553        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14554     return SDValue();
14555
14556   SDValue ShAmtOp = N->getOperand(1);
14557   EVT EltVT = VT.getVectorElementType();
14558   DebugLoc DL = N->getDebugLoc();
14559   SDValue BaseShAmt = SDValue();
14560   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14561     unsigned NumElts = VT.getVectorNumElements();
14562     unsigned i = 0;
14563     for (; i != NumElts; ++i) {
14564       SDValue Arg = ShAmtOp.getOperand(i);
14565       if (Arg.getOpcode() == ISD::UNDEF) continue;
14566       BaseShAmt = Arg;
14567       break;
14568     }
14569     // Handle the case where the build_vector is all undef
14570     // FIXME: Should DAG allow this?
14571     if (i == NumElts)
14572       return SDValue();
14573
14574     for (; i != NumElts; ++i) {
14575       SDValue Arg = ShAmtOp.getOperand(i);
14576       if (Arg.getOpcode() == ISD::UNDEF) continue;
14577       if (Arg != BaseShAmt) {
14578         return SDValue();
14579       }
14580     }
14581   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14582              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14583     SDValue InVec = ShAmtOp.getOperand(0);
14584     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14585       unsigned NumElts = InVec.getValueType().getVectorNumElements();
14586       unsigned i = 0;
14587       for (; i != NumElts; ++i) {
14588         SDValue Arg = InVec.getOperand(i);
14589         if (Arg.getOpcode() == ISD::UNDEF) continue;
14590         BaseShAmt = Arg;
14591         break;
14592       }
14593     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14594        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14595          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14596          if (C->getZExtValue() == SplatIdx)
14597            BaseShAmt = InVec.getOperand(1);
14598        }
14599     }
14600     if (BaseShAmt.getNode() == 0) {
14601       // Don't create instructions with illegal types after legalize
14602       // types has run.
14603       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14604           !DCI.isBeforeLegalize())
14605         return SDValue();
14606
14607       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14608                               DAG.getIntPtrConstant(0));
14609     }
14610   } else
14611     return SDValue();
14612
14613   // The shift amount is an i32.
14614   if (EltVT.bitsGT(MVT::i32))
14615     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14616   else if (EltVT.bitsLT(MVT::i32))
14617     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14618
14619   // The shift amount is identical so we can do a vector shift.
14620   SDValue  ValOp = N->getOperand(0);
14621   switch (N->getOpcode()) {
14622   default:
14623     llvm_unreachable("Unknown shift opcode!");
14624   case ISD::SHL:
14625     switch (VT.getSimpleVT().SimpleTy) {
14626     default: return SDValue();
14627     case MVT::v2i64:
14628     case MVT::v4i32:
14629     case MVT::v8i16:
14630     case MVT::v4i64:
14631     case MVT::v8i32:
14632     case MVT::v16i16:
14633       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14634     }
14635   case ISD::SRA:
14636     switch (VT.getSimpleVT().SimpleTy) {
14637     default: return SDValue();
14638     case MVT::v4i32:
14639     case MVT::v8i16:
14640     case MVT::v8i32:
14641     case MVT::v16i16:
14642       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14643     }
14644   case ISD::SRL:
14645     switch (VT.getSimpleVT().SimpleTy) {
14646     default: return SDValue();
14647     case MVT::v2i64:
14648     case MVT::v4i32:
14649     case MVT::v8i16:
14650     case MVT::v4i64:
14651     case MVT::v8i32:
14652     case MVT::v16i16:
14653       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14654     }
14655   }
14656 }
14657
14658
14659 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
14660 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14661 // and friends.  Likewise for OR -> CMPNEQSS.
14662 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14663                             TargetLowering::DAGCombinerInfo &DCI,
14664                             const X86Subtarget *Subtarget) {
14665   unsigned opcode;
14666
14667   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14668   // we're requiring SSE2 for both.
14669   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14670     SDValue N0 = N->getOperand(0);
14671     SDValue N1 = N->getOperand(1);
14672     SDValue CMP0 = N0->getOperand(1);
14673     SDValue CMP1 = N1->getOperand(1);
14674     DebugLoc DL = N->getDebugLoc();
14675
14676     // The SETCCs should both refer to the same CMP.
14677     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14678       return SDValue();
14679
14680     SDValue CMP00 = CMP0->getOperand(0);
14681     SDValue CMP01 = CMP0->getOperand(1);
14682     EVT     VT    = CMP00.getValueType();
14683
14684     if (VT == MVT::f32 || VT == MVT::f64) {
14685       bool ExpectingFlags = false;
14686       // Check for any users that want flags:
14687       for (SDNode::use_iterator UI = N->use_begin(),
14688              UE = N->use_end();
14689            !ExpectingFlags && UI != UE; ++UI)
14690         switch (UI->getOpcode()) {
14691         default:
14692         case ISD::BR_CC:
14693         case ISD::BRCOND:
14694         case ISD::SELECT:
14695           ExpectingFlags = true;
14696           break;
14697         case ISD::CopyToReg:
14698         case ISD::SIGN_EXTEND:
14699         case ISD::ZERO_EXTEND:
14700         case ISD::ANY_EXTEND:
14701           break;
14702         }
14703
14704       if (!ExpectingFlags) {
14705         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14706         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14707
14708         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14709           X86::CondCode tmp = cc0;
14710           cc0 = cc1;
14711           cc1 = tmp;
14712         }
14713
14714         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14715             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14716           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14717           X86ISD::NodeType NTOperator = is64BitFP ?
14718             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14719           // FIXME: need symbolic constants for these magic numbers.
14720           // See X86ATTInstPrinter.cpp:printSSECC().
14721           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14722           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14723                                               DAG.getConstant(x86cc, MVT::i8));
14724           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14725                                               OnesOrZeroesF);
14726           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14727                                       DAG.getConstant(1, MVT::i32));
14728           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14729           return OneBitOfTruth;
14730         }
14731       }
14732     }
14733   }
14734   return SDValue();
14735 }
14736
14737 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14738 /// so it can be folded inside ANDNP.
14739 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14740   EVT VT = N->getValueType(0);
14741
14742   // Match direct AllOnes for 128 and 256-bit vectors
14743   if (ISD::isBuildVectorAllOnes(N))
14744     return true;
14745
14746   // Look through a bit convert.
14747   if (N->getOpcode() == ISD::BITCAST)
14748     N = N->getOperand(0).getNode();
14749
14750   // Sometimes the operand may come from a insert_subvector building a 256-bit
14751   // allones vector
14752   if (VT.is256BitVector() &&
14753       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14754     SDValue V1 = N->getOperand(0);
14755     SDValue V2 = N->getOperand(1);
14756
14757     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14758         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14759         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14760         ISD::isBuildVectorAllOnes(V2.getNode()))
14761       return true;
14762   }
14763
14764   return false;
14765 }
14766
14767 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14768                                  TargetLowering::DAGCombinerInfo &DCI,
14769                                  const X86Subtarget *Subtarget) {
14770   if (DCI.isBeforeLegalizeOps())
14771     return SDValue();
14772
14773   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14774   if (R.getNode())
14775     return R;
14776
14777   EVT VT = N->getValueType(0);
14778
14779   // Create ANDN, BLSI, and BLSR instructions
14780   // BLSI is X & (-X)
14781   // BLSR is X & (X-1)
14782   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14783     SDValue N0 = N->getOperand(0);
14784     SDValue N1 = N->getOperand(1);
14785     DebugLoc DL = N->getDebugLoc();
14786
14787     // Check LHS for not
14788     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14789       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14790     // Check RHS for not
14791     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14792       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14793
14794     // Check LHS for neg
14795     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14796         isZero(N0.getOperand(0)))
14797       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14798
14799     // Check RHS for neg
14800     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14801         isZero(N1.getOperand(0)))
14802       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14803
14804     // Check LHS for X-1
14805     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14806         isAllOnes(N0.getOperand(1)))
14807       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14808
14809     // Check RHS for X-1
14810     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14811         isAllOnes(N1.getOperand(1)))
14812       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14813
14814     return SDValue();
14815   }
14816
14817   // Want to form ANDNP nodes:
14818   // 1) In the hopes of then easily combining them with OR and AND nodes
14819   //    to form PBLEND/PSIGN.
14820   // 2) To match ANDN packed intrinsics
14821   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14822     return SDValue();
14823
14824   SDValue N0 = N->getOperand(0);
14825   SDValue N1 = N->getOperand(1);
14826   DebugLoc DL = N->getDebugLoc();
14827
14828   // Check LHS for vnot
14829   if (N0.getOpcode() == ISD::XOR &&
14830       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14831       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14832     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14833
14834   // Check RHS for vnot
14835   if (N1.getOpcode() == ISD::XOR &&
14836       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14837       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14838     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14839
14840   return SDValue();
14841 }
14842
14843 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14844                                 TargetLowering::DAGCombinerInfo &DCI,
14845                                 const X86Subtarget *Subtarget) {
14846   if (DCI.isBeforeLegalizeOps())
14847     return SDValue();
14848
14849   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14850   if (R.getNode())
14851     return R;
14852
14853   EVT VT = N->getValueType(0);
14854
14855   SDValue N0 = N->getOperand(0);
14856   SDValue N1 = N->getOperand(1);
14857
14858   // look for psign/blend
14859   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14860     if (!Subtarget->hasSSSE3() ||
14861         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14862       return SDValue();
14863
14864     // Canonicalize pandn to RHS
14865     if (N0.getOpcode() == X86ISD::ANDNP)
14866       std::swap(N0, N1);
14867     // or (and (m, y), (pandn m, x))
14868     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14869       SDValue Mask = N1.getOperand(0);
14870       SDValue X    = N1.getOperand(1);
14871       SDValue Y;
14872       if (N0.getOperand(0) == Mask)
14873         Y = N0.getOperand(1);
14874       if (N0.getOperand(1) == Mask)
14875         Y = N0.getOperand(0);
14876
14877       // Check to see if the mask appeared in both the AND and ANDNP and
14878       if (!Y.getNode())
14879         return SDValue();
14880
14881       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14882       // Look through mask bitcast.
14883       if (Mask.getOpcode() == ISD::BITCAST)
14884         Mask = Mask.getOperand(0);
14885       if (X.getOpcode() == ISD::BITCAST)
14886         X = X.getOperand(0);
14887       if (Y.getOpcode() == ISD::BITCAST)
14888         Y = Y.getOperand(0);
14889
14890       EVT MaskVT = Mask.getValueType();
14891
14892       // Validate that the Mask operand is a vector sra node.
14893       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14894       // there is no psrai.b
14895       if (Mask.getOpcode() != X86ISD::VSRAI)
14896         return SDValue();
14897
14898       // Check that the SRA is all signbits.
14899       SDValue SraC = Mask.getOperand(1);
14900       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14901       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14902       if ((SraAmt + 1) != EltBits)
14903         return SDValue();
14904
14905       DebugLoc DL = N->getDebugLoc();
14906
14907       // Now we know we at least have a plendvb with the mask val.  See if
14908       // we can form a psignb/w/d.
14909       // psign = x.type == y.type == mask.type && y = sub(0, x);
14910       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14911           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14912           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14913         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14914                "Unsupported VT for PSIGN");
14915         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14916         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14917       }
14918       // PBLENDVB only available on SSE 4.1
14919       if (!Subtarget->hasSSE41())
14920         return SDValue();
14921
14922       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14923
14924       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14925       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14926       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14927       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14928       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14929     }
14930   }
14931
14932   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14933     return SDValue();
14934
14935   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14936   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14937     std::swap(N0, N1);
14938   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14939     return SDValue();
14940   if (!N0.hasOneUse() || !N1.hasOneUse())
14941     return SDValue();
14942
14943   SDValue ShAmt0 = N0.getOperand(1);
14944   if (ShAmt0.getValueType() != MVT::i8)
14945     return SDValue();
14946   SDValue ShAmt1 = N1.getOperand(1);
14947   if (ShAmt1.getValueType() != MVT::i8)
14948     return SDValue();
14949   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14950     ShAmt0 = ShAmt0.getOperand(0);
14951   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14952     ShAmt1 = ShAmt1.getOperand(0);
14953
14954   DebugLoc DL = N->getDebugLoc();
14955   unsigned Opc = X86ISD::SHLD;
14956   SDValue Op0 = N0.getOperand(0);
14957   SDValue Op1 = N1.getOperand(0);
14958   if (ShAmt0.getOpcode() == ISD::SUB) {
14959     Opc = X86ISD::SHRD;
14960     std::swap(Op0, Op1);
14961     std::swap(ShAmt0, ShAmt1);
14962   }
14963
14964   unsigned Bits = VT.getSizeInBits();
14965   if (ShAmt1.getOpcode() == ISD::SUB) {
14966     SDValue Sum = ShAmt1.getOperand(0);
14967     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14968       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14969       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14970         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14971       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14972         return DAG.getNode(Opc, DL, VT,
14973                            Op0, Op1,
14974                            DAG.getNode(ISD::TRUNCATE, DL,
14975                                        MVT::i8, ShAmt0));
14976     }
14977   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14978     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14979     if (ShAmt0C &&
14980         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14981       return DAG.getNode(Opc, DL, VT,
14982                          N0.getOperand(0), N1.getOperand(0),
14983                          DAG.getNode(ISD::TRUNCATE, DL,
14984                                        MVT::i8, ShAmt0));
14985   }
14986
14987   return SDValue();
14988 }
14989
14990 // Generate NEG and CMOV for integer abs.
14991 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
14992   EVT VT = N->getValueType(0);
14993
14994   // Since X86 does not have CMOV for 8-bit integer, we don't convert
14995   // 8-bit integer abs to NEG and CMOV.
14996   if (VT.isInteger() && VT.getSizeInBits() == 8)
14997     return SDValue();
14998
14999   SDValue N0 = N->getOperand(0);
15000   SDValue N1 = N->getOperand(1);
15001   DebugLoc DL = N->getDebugLoc();
15002
15003   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15004   // and change it to SUB and CMOV.
15005   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15006       N0.getOpcode() == ISD::ADD &&
15007       N0.getOperand(1) == N1 &&
15008       N1.getOpcode() == ISD::SRA &&
15009       N1.getOperand(0) == N0.getOperand(0))
15010     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15011       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15012         // Generate SUB & CMOV.
15013         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15014                                   DAG.getConstant(0, VT), N0.getOperand(0));
15015
15016         SDValue Ops[] = { N0.getOperand(0), Neg,
15017                           DAG.getConstant(X86::COND_GE, MVT::i8),
15018                           SDValue(Neg.getNode(), 1) };
15019         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15020                            Ops, array_lengthof(Ops));
15021       }
15022   return SDValue();
15023 }
15024
15025 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15026 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15027                                  TargetLowering::DAGCombinerInfo &DCI,
15028                                  const X86Subtarget *Subtarget) {
15029   if (DCI.isBeforeLegalizeOps())
15030     return SDValue();
15031
15032   if (Subtarget->hasCMov()) {
15033     SDValue RV = performIntegerAbsCombine(N, DAG);
15034     if (RV.getNode())
15035       return RV;
15036   }
15037
15038   // Try forming BMI if it is available.
15039   if (!Subtarget->hasBMI())
15040     return SDValue();
15041
15042   EVT VT = N->getValueType(0);
15043
15044   if (VT != MVT::i32 && VT != MVT::i64)
15045     return SDValue();
15046
15047   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15048
15049   // Create BLSMSK instructions by finding X ^ (X-1)
15050   SDValue N0 = N->getOperand(0);
15051   SDValue N1 = N->getOperand(1);
15052   DebugLoc DL = N->getDebugLoc();
15053
15054   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15055       isAllOnes(N0.getOperand(1)))
15056     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15057
15058   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15059       isAllOnes(N1.getOperand(1)))
15060     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15061
15062   return SDValue();
15063 }
15064
15065 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15066 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15067                                   TargetLowering::DAGCombinerInfo &DCI,
15068                                   const X86Subtarget *Subtarget) {
15069   LoadSDNode *Ld = cast<LoadSDNode>(N);
15070   EVT RegVT = Ld->getValueType(0);
15071   EVT MemVT = Ld->getMemoryVT();
15072   DebugLoc dl = Ld->getDebugLoc();
15073   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15074
15075   ISD::LoadExtType Ext = Ld->getExtensionType();
15076
15077   // If this is a vector EXT Load then attempt to optimize it using a
15078   // shuffle. We need SSE4 for the shuffles.
15079   // TODO: It is possible to support ZExt by zeroing the undef values
15080   // during the shuffle phase or after the shuffle.
15081   if (RegVT.isVector() && RegVT.isInteger() &&
15082       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15083     assert(MemVT != RegVT && "Cannot extend to the same type");
15084     assert(MemVT.isVector() && "Must load a vector from memory");
15085
15086     unsigned NumElems = RegVT.getVectorNumElements();
15087     unsigned RegSz = RegVT.getSizeInBits();
15088     unsigned MemSz = MemVT.getSizeInBits();
15089     assert(RegSz > MemSz && "Register size must be greater than the mem size");
15090
15091     // All sizes must be a power of two.
15092     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15093       return SDValue();
15094
15095     // Attempt to load the original value using scalar loads.
15096     // Find the largest scalar type that divides the total loaded size.
15097     MVT SclrLoadTy = MVT::i8;
15098     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15099          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15100       MVT Tp = (MVT::SimpleValueType)tp;
15101       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15102         SclrLoadTy = Tp;
15103       }
15104     }
15105
15106     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15107     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15108         (64 <= MemSz))
15109       SclrLoadTy = MVT::f64;
15110
15111     // Calculate the number of scalar loads that we need to perform
15112     // in order to load our vector from memory.
15113     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15114
15115     // Represent our vector as a sequence of elements which are the
15116     // largest scalar that we can load.
15117     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15118       RegSz/SclrLoadTy.getSizeInBits());
15119
15120     // Represent the data using the same element type that is stored in
15121     // memory. In practice, we ''widen'' MemVT.
15122     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15123                                   RegSz/MemVT.getScalarType().getSizeInBits());
15124
15125     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15126       "Invalid vector type");
15127
15128     // We can't shuffle using an illegal type.
15129     if (!TLI.isTypeLegal(WideVecVT))
15130       return SDValue();
15131
15132     SmallVector<SDValue, 8> Chains;
15133     SDValue Ptr = Ld->getBasePtr();
15134     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15135                                         TLI.getPointerTy());
15136     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15137
15138     for (unsigned i = 0; i < NumLoads; ++i) {
15139       // Perform a single load.
15140       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15141                                        Ptr, Ld->getPointerInfo(),
15142                                        Ld->isVolatile(), Ld->isNonTemporal(),
15143                                        Ld->isInvariant(), Ld->getAlignment());
15144       Chains.push_back(ScalarLoad.getValue(1));
15145       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15146       // another round of DAGCombining.
15147       if (i == 0)
15148         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15149       else
15150         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15151                           ScalarLoad, DAG.getIntPtrConstant(i));
15152
15153       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15154     }
15155
15156     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15157                                Chains.size());
15158
15159     // Bitcast the loaded value to a vector of the original element type, in
15160     // the size of the target vector type.
15161     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15162     unsigned SizeRatio = RegSz/MemSz;
15163
15164     // Redistribute the loaded elements into the different locations.
15165     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15166     for (unsigned i = 0; i != NumElems; ++i)
15167       ShuffleVec[i*SizeRatio] = i;
15168
15169     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15170                                          DAG.getUNDEF(WideVecVT),
15171                                          &ShuffleVec[0]);
15172
15173     // Bitcast to the requested type.
15174     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15175     // Replace the original load with the new sequence
15176     // and return the new chain.
15177     return DCI.CombineTo(N, Shuff, TF, true);
15178   }
15179
15180   return SDValue();
15181 }
15182
15183 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15184 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15185                                    const X86Subtarget *Subtarget) {
15186   StoreSDNode *St = cast<StoreSDNode>(N);
15187   EVT VT = St->getValue().getValueType();
15188   EVT StVT = St->getMemoryVT();
15189   DebugLoc dl = St->getDebugLoc();
15190   SDValue StoredVal = St->getOperand(1);
15191   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15192
15193   // If we are saving a concatenation of two XMM registers, perform two stores.
15194   // On Sandy Bridge, 256-bit memory operations are executed by two
15195   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15196   // memory  operation.
15197   if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15198       StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15199       StoredVal.getNumOperands() == 2) {
15200     SDValue Value0 = StoredVal.getOperand(0);
15201     SDValue Value1 = StoredVal.getOperand(1);
15202
15203     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15204     SDValue Ptr0 = St->getBasePtr();
15205     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15206
15207     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15208                                 St->getPointerInfo(), St->isVolatile(),
15209                                 St->isNonTemporal(), St->getAlignment());
15210     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15211                                 St->getPointerInfo(), St->isVolatile(),
15212                                 St->isNonTemporal(), St->getAlignment());
15213     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15214   }
15215
15216   // Optimize trunc store (of multiple scalars) to shuffle and store.
15217   // First, pack all of the elements in one place. Next, store to memory
15218   // in fewer chunks.
15219   if (St->isTruncatingStore() && VT.isVector()) {
15220     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15221     unsigned NumElems = VT.getVectorNumElements();
15222     assert(StVT != VT && "Cannot truncate to the same type");
15223     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15224     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15225
15226     // From, To sizes and ElemCount must be pow of two
15227     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15228     // We are going to use the original vector elt for storing.
15229     // Accumulated smaller vector elements must be a multiple of the store size.
15230     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15231
15232     unsigned SizeRatio  = FromSz / ToSz;
15233
15234     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15235
15236     // Create a type on which we perform the shuffle
15237     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15238             StVT.getScalarType(), NumElems*SizeRatio);
15239
15240     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15241
15242     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15243     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15244     for (unsigned i = 0; i != NumElems; ++i)
15245       ShuffleVec[i] = i * SizeRatio;
15246
15247     // Can't shuffle using an illegal type.
15248     if (!TLI.isTypeLegal(WideVecVT))
15249       return SDValue();
15250
15251     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15252                                          DAG.getUNDEF(WideVecVT),
15253                                          &ShuffleVec[0]);
15254     // At this point all of the data is stored at the bottom of the
15255     // register. We now need to save it to mem.
15256
15257     // Find the largest store unit
15258     MVT StoreType = MVT::i8;
15259     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15260          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15261       MVT Tp = (MVT::SimpleValueType)tp;
15262       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15263         StoreType = Tp;
15264     }
15265
15266     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15267     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15268         (64 <= NumElems * ToSz))
15269       StoreType = MVT::f64;
15270
15271     // Bitcast the original vector into a vector of store-size units
15272     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15273             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15274     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15275     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15276     SmallVector<SDValue, 8> Chains;
15277     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15278                                         TLI.getPointerTy());
15279     SDValue Ptr = St->getBasePtr();
15280
15281     // Perform one or more big stores into memory.
15282     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15283       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15284                                    StoreType, ShuffWide,
15285                                    DAG.getIntPtrConstant(i));
15286       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15287                                 St->getPointerInfo(), St->isVolatile(),
15288                                 St->isNonTemporal(), St->getAlignment());
15289       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15290       Chains.push_back(Ch);
15291     }
15292
15293     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15294                                Chains.size());
15295   }
15296
15297
15298   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
15299   // the FP state in cases where an emms may be missing.
15300   // A preferable solution to the general problem is to figure out the right
15301   // places to insert EMMS.  This qualifies as a quick hack.
15302
15303   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15304   if (VT.getSizeInBits() != 64)
15305     return SDValue();
15306
15307   const Function *F = DAG.getMachineFunction().getFunction();
15308   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
15309   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15310                      && Subtarget->hasSSE2();
15311   if ((VT.isVector() ||
15312        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15313       isa<LoadSDNode>(St->getValue()) &&
15314       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15315       St->getChain().hasOneUse() && !St->isVolatile()) {
15316     SDNode* LdVal = St->getValue().getNode();
15317     LoadSDNode *Ld = 0;
15318     int TokenFactorIndex = -1;
15319     SmallVector<SDValue, 8> Ops;
15320     SDNode* ChainVal = St->getChain().getNode();
15321     // Must be a store of a load.  We currently handle two cases:  the load
15322     // is a direct child, and it's under an intervening TokenFactor.  It is
15323     // possible to dig deeper under nested TokenFactors.
15324     if (ChainVal == LdVal)
15325       Ld = cast<LoadSDNode>(St->getChain());
15326     else if (St->getValue().hasOneUse() &&
15327              ChainVal->getOpcode() == ISD::TokenFactor) {
15328       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15329         if (ChainVal->getOperand(i).getNode() == LdVal) {
15330           TokenFactorIndex = i;
15331           Ld = cast<LoadSDNode>(St->getValue());
15332         } else
15333           Ops.push_back(ChainVal->getOperand(i));
15334       }
15335     }
15336
15337     if (!Ld || !ISD::isNormalLoad(Ld))
15338       return SDValue();
15339
15340     // If this is not the MMX case, i.e. we are just turning i64 load/store
15341     // into f64 load/store, avoid the transformation if there are multiple
15342     // uses of the loaded value.
15343     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15344       return SDValue();
15345
15346     DebugLoc LdDL = Ld->getDebugLoc();
15347     DebugLoc StDL = N->getDebugLoc();
15348     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15349     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15350     // pair instead.
15351     if (Subtarget->is64Bit() || F64IsLegal) {
15352       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15353       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15354                                   Ld->getPointerInfo(), Ld->isVolatile(),
15355                                   Ld->isNonTemporal(), Ld->isInvariant(),
15356                                   Ld->getAlignment());
15357       SDValue NewChain = NewLd.getValue(1);
15358       if (TokenFactorIndex != -1) {
15359         Ops.push_back(NewChain);
15360         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15361                                Ops.size());
15362       }
15363       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15364                           St->getPointerInfo(),
15365                           St->isVolatile(), St->isNonTemporal(),
15366                           St->getAlignment());
15367     }
15368
15369     // Otherwise, lower to two pairs of 32-bit loads / stores.
15370     SDValue LoAddr = Ld->getBasePtr();
15371     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15372                                  DAG.getConstant(4, MVT::i32));
15373
15374     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15375                                Ld->getPointerInfo(),
15376                                Ld->isVolatile(), Ld->isNonTemporal(),
15377                                Ld->isInvariant(), Ld->getAlignment());
15378     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15379                                Ld->getPointerInfo().getWithOffset(4),
15380                                Ld->isVolatile(), Ld->isNonTemporal(),
15381                                Ld->isInvariant(),
15382                                MinAlign(Ld->getAlignment(), 4));
15383
15384     SDValue NewChain = LoLd.getValue(1);
15385     if (TokenFactorIndex != -1) {
15386       Ops.push_back(LoLd);
15387       Ops.push_back(HiLd);
15388       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15389                              Ops.size());
15390     }
15391
15392     LoAddr = St->getBasePtr();
15393     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15394                          DAG.getConstant(4, MVT::i32));
15395
15396     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15397                                 St->getPointerInfo(),
15398                                 St->isVolatile(), St->isNonTemporal(),
15399                                 St->getAlignment());
15400     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15401                                 St->getPointerInfo().getWithOffset(4),
15402                                 St->isVolatile(),
15403                                 St->isNonTemporal(),
15404                                 MinAlign(St->getAlignment(), 4));
15405     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15406   }
15407   return SDValue();
15408 }
15409
15410 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15411 /// and return the operands for the horizontal operation in LHS and RHS.  A
15412 /// horizontal operation performs the binary operation on successive elements
15413 /// of its first operand, then on successive elements of its second operand,
15414 /// returning the resulting values in a vector.  For example, if
15415 ///   A = < float a0, float a1, float a2, float a3 >
15416 /// and
15417 ///   B = < float b0, float b1, float b2, float b3 >
15418 /// then the result of doing a horizontal operation on A and B is
15419 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15420 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15421 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15422 /// set to A, RHS to B, and the routine returns 'true'.
15423 /// Note that the binary operation should have the property that if one of the
15424 /// operands is UNDEF then the result is UNDEF.
15425 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15426   // Look for the following pattern: if
15427   //   A = < float a0, float a1, float a2, float a3 >
15428   //   B = < float b0, float b1, float b2, float b3 >
15429   // and
15430   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15431   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15432   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15433   // which is A horizontal-op B.
15434
15435   // At least one of the operands should be a vector shuffle.
15436   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15437       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15438     return false;
15439
15440   EVT VT = LHS.getValueType();
15441
15442   assert((VT.is128BitVector() || VT.is256BitVector()) &&
15443          "Unsupported vector type for horizontal add/sub");
15444
15445   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15446   // operate independently on 128-bit lanes.
15447   unsigned NumElts = VT.getVectorNumElements();
15448   unsigned NumLanes = VT.getSizeInBits()/128;
15449   unsigned NumLaneElts = NumElts / NumLanes;
15450   assert((NumLaneElts % 2 == 0) &&
15451          "Vector type should have an even number of elements in each lane");
15452   unsigned HalfLaneElts = NumLaneElts/2;
15453
15454   // View LHS in the form
15455   //   LHS = VECTOR_SHUFFLE A, B, LMask
15456   // If LHS is not a shuffle then pretend it is the shuffle
15457   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15458   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15459   // type VT.
15460   SDValue A, B;
15461   SmallVector<int, 16> LMask(NumElts);
15462   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15463     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15464       A = LHS.getOperand(0);
15465     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15466       B = LHS.getOperand(1);
15467     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15468     std::copy(Mask.begin(), Mask.end(), LMask.begin());
15469   } else {
15470     if (LHS.getOpcode() != ISD::UNDEF)
15471       A = LHS;
15472     for (unsigned i = 0; i != NumElts; ++i)
15473       LMask[i] = i;
15474   }
15475
15476   // Likewise, view RHS in the form
15477   //   RHS = VECTOR_SHUFFLE C, D, RMask
15478   SDValue C, D;
15479   SmallVector<int, 16> RMask(NumElts);
15480   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15481     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15482       C = RHS.getOperand(0);
15483     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15484       D = RHS.getOperand(1);
15485     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15486     std::copy(Mask.begin(), Mask.end(), RMask.begin());
15487   } else {
15488     if (RHS.getOpcode() != ISD::UNDEF)
15489       C = RHS;
15490     for (unsigned i = 0; i != NumElts; ++i)
15491       RMask[i] = i;
15492   }
15493
15494   // Check that the shuffles are both shuffling the same vectors.
15495   if (!(A == C && B == D) && !(A == D && B == C))
15496     return false;
15497
15498   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15499   if (!A.getNode() && !B.getNode())
15500     return false;
15501
15502   // If A and B occur in reverse order in RHS, then "swap" them (which means
15503   // rewriting the mask).
15504   if (A != C)
15505     CommuteVectorShuffleMask(RMask, NumElts);
15506
15507   // At this point LHS and RHS are equivalent to
15508   //   LHS = VECTOR_SHUFFLE A, B, LMask
15509   //   RHS = VECTOR_SHUFFLE A, B, RMask
15510   // Check that the masks correspond to performing a horizontal operation.
15511   for (unsigned i = 0; i != NumElts; ++i) {
15512     int LIdx = LMask[i], RIdx = RMask[i];
15513
15514     // Ignore any UNDEF components.
15515     if (LIdx < 0 || RIdx < 0 ||
15516         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15517         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15518       continue;
15519
15520     // Check that successive elements are being operated on.  If not, this is
15521     // not a horizontal operation.
15522     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15523     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15524     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15525     if (!(LIdx == Index && RIdx == Index + 1) &&
15526         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15527       return false;
15528   }
15529
15530   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15531   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15532   return true;
15533 }
15534
15535 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15536 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15537                                   const X86Subtarget *Subtarget) {
15538   EVT VT = N->getValueType(0);
15539   SDValue LHS = N->getOperand(0);
15540   SDValue RHS = N->getOperand(1);
15541
15542   // Try to synthesize horizontal adds from adds of shuffles.
15543   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15544        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15545       isHorizontalBinOp(LHS, RHS, true))
15546     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15547   return SDValue();
15548 }
15549
15550 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15551 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15552                                   const X86Subtarget *Subtarget) {
15553   EVT VT = N->getValueType(0);
15554   SDValue LHS = N->getOperand(0);
15555   SDValue RHS = N->getOperand(1);
15556
15557   // Try to synthesize horizontal subs from subs of shuffles.
15558   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15559        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15560       isHorizontalBinOp(LHS, RHS, false))
15561     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15562   return SDValue();
15563 }
15564
15565 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15566 /// X86ISD::FXOR nodes.
15567 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15568   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15569   // F[X]OR(0.0, x) -> x
15570   // F[X]OR(x, 0.0) -> x
15571   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15572     if (C->getValueAPF().isPosZero())
15573       return N->getOperand(1);
15574   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15575     if (C->getValueAPF().isPosZero())
15576       return N->getOperand(0);
15577   return SDValue();
15578 }
15579
15580 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15581 /// X86ISD::FMAX nodes.
15582 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15583   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15584
15585   // Only perform optimizations if UnsafeMath is used.
15586   if (!DAG.getTarget().Options.UnsafeFPMath)
15587     return SDValue();
15588
15589   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15590   // into FMINC and FMAXC, which are Commutative operations.
15591   unsigned NewOp = 0;
15592   switch (N->getOpcode()) {
15593     default: llvm_unreachable("unknown opcode");
15594     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
15595     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
15596   }
15597
15598   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15599                      N->getOperand(0), N->getOperand(1));
15600 }
15601
15602
15603 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15604 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15605   // FAND(0.0, x) -> 0.0
15606   // FAND(x, 0.0) -> 0.0
15607   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15608     if (C->getValueAPF().isPosZero())
15609       return N->getOperand(0);
15610   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15611     if (C->getValueAPF().isPosZero())
15612       return N->getOperand(1);
15613   return SDValue();
15614 }
15615
15616 static SDValue PerformBTCombine(SDNode *N,
15617                                 SelectionDAG &DAG,
15618                                 TargetLowering::DAGCombinerInfo &DCI) {
15619   // BT ignores high bits in the bit index operand.
15620   SDValue Op1 = N->getOperand(1);
15621   if (Op1.hasOneUse()) {
15622     unsigned BitWidth = Op1.getValueSizeInBits();
15623     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15624     APInt KnownZero, KnownOne;
15625     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15626                                           !DCI.isBeforeLegalizeOps());
15627     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15628     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15629         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15630       DCI.CommitTargetLoweringOpt(TLO);
15631   }
15632   return SDValue();
15633 }
15634
15635 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15636   SDValue Op = N->getOperand(0);
15637   if (Op.getOpcode() == ISD::BITCAST)
15638     Op = Op.getOperand(0);
15639   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15640   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15641       VT.getVectorElementType().getSizeInBits() ==
15642       OpVT.getVectorElementType().getSizeInBits()) {
15643     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15644   }
15645   return SDValue();
15646 }
15647
15648 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15649                                   TargetLowering::DAGCombinerInfo &DCI,
15650                                   const X86Subtarget *Subtarget) {
15651   if (!DCI.isBeforeLegalizeOps())
15652     return SDValue();
15653
15654   if (!Subtarget->hasAVX())
15655     return SDValue();
15656
15657   EVT VT = N->getValueType(0);
15658   SDValue Op = N->getOperand(0);
15659   EVT OpVT = Op.getValueType();
15660   DebugLoc dl = N->getDebugLoc();
15661
15662   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15663       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15664
15665     if (Subtarget->hasAVX2())
15666       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15667
15668     // Optimize vectors in AVX mode
15669     // Sign extend  v8i16 to v8i32 and
15670     //              v4i32 to v4i64
15671     //
15672     // Divide input vector into two parts
15673     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15674     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15675     // concat the vectors to original VT
15676
15677     unsigned NumElems = OpVT.getVectorNumElements();
15678     SDValue Undef = DAG.getUNDEF(OpVT);
15679
15680     SmallVector<int,8> ShufMask1(NumElems, -1);
15681     for (unsigned i = 0; i != NumElems/2; ++i)
15682       ShufMask1[i] = i;
15683
15684     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
15685
15686     SmallVector<int,8> ShufMask2(NumElems, -1);
15687     for (unsigned i = 0; i != NumElems/2; ++i)
15688       ShufMask2[i] = i + NumElems/2;
15689
15690     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
15691
15692     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15693                                   VT.getVectorNumElements()/2);
15694
15695     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15696     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15697
15698     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15699   }
15700   return SDValue();
15701 }
15702
15703 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
15704                                  const X86Subtarget* Subtarget) {
15705   DebugLoc dl = N->getDebugLoc();
15706   EVT VT = N->getValueType(0);
15707
15708   // Let legalize expand this if it isn't a legal type yet.
15709   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15710     return SDValue();
15711
15712   EVT ScalarVT = VT.getScalarType();
15713   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
15714       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
15715     return SDValue();
15716
15717   SDValue A = N->getOperand(0);
15718   SDValue B = N->getOperand(1);
15719   SDValue C = N->getOperand(2);
15720
15721   bool NegA = (A.getOpcode() == ISD::FNEG);
15722   bool NegB = (B.getOpcode() == ISD::FNEG);
15723   bool NegC = (C.getOpcode() == ISD::FNEG);
15724
15725   // Negative multiplication when NegA xor NegB
15726   bool NegMul = (NegA != NegB);
15727   if (NegA)
15728     A = A.getOperand(0);
15729   if (NegB)
15730     B = B.getOperand(0);
15731   if (NegC)
15732     C = C.getOperand(0);
15733
15734   unsigned Opcode;
15735   if (!NegMul)
15736     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
15737   else
15738     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
15739
15740   return DAG.getNode(Opcode, dl, VT, A, B, C);
15741 }
15742
15743 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15744                                   TargetLowering::DAGCombinerInfo &DCI,
15745                                   const X86Subtarget *Subtarget) {
15746   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
15747   //           (and (i32 x86isd::setcc_carry), 1)
15748   // This eliminates the zext. This transformation is necessary because
15749   // ISD::SETCC is always legalized to i8.
15750   DebugLoc dl = N->getDebugLoc();
15751   SDValue N0 = N->getOperand(0);
15752   EVT VT = N->getValueType(0);
15753   EVT OpVT = N0.getValueType();
15754
15755   if (N0.getOpcode() == ISD::AND &&
15756       N0.hasOneUse() &&
15757       N0.getOperand(0).hasOneUse()) {
15758     SDValue N00 = N0.getOperand(0);
15759     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15760       return SDValue();
15761     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15762     if (!C || C->getZExtValue() != 1)
15763       return SDValue();
15764     return DAG.getNode(ISD::AND, dl, VT,
15765                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15766                                    N00.getOperand(0), N00.getOperand(1)),
15767                        DAG.getConstant(1, VT));
15768   }
15769
15770   // Optimize vectors in AVX mode:
15771   //
15772   //   v8i16 -> v8i32
15773   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
15774   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
15775   //   Concat upper and lower parts.
15776   //
15777   //   v4i32 -> v4i64
15778   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
15779   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
15780   //   Concat upper and lower parts.
15781   //
15782   if (!DCI.isBeforeLegalizeOps())
15783     return SDValue();
15784
15785   if (!Subtarget->hasAVX())
15786     return SDValue();
15787
15788   if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15789       ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
15790
15791     if (Subtarget->hasAVX2())
15792       return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15793
15794     SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15795     SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15796     SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15797
15798     EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15799                                VT.getVectorNumElements()/2);
15800
15801     OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15802     OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15803
15804     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15805   }
15806
15807   return SDValue();
15808 }
15809
15810 // Optimize x == -y --> x+y == 0
15811 //          x != -y --> x+y != 0
15812 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15813   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15814   SDValue LHS = N->getOperand(0);
15815   SDValue RHS = N->getOperand(1);
15816
15817   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15818     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15819       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15820         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15821                                    LHS.getValueType(), RHS, LHS.getOperand(1));
15822         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15823                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15824       }
15825   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15826     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15827       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15828         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15829                                    RHS.getValueType(), LHS, RHS.getOperand(1));
15830         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15831                             addV, DAG.getConstant(0, addV.getValueType()), CC);
15832       }
15833   return SDValue();
15834 }
15835
15836 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15837 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
15838                                    TargetLowering::DAGCombinerInfo &DCI,
15839                                    const X86Subtarget *Subtarget) {
15840   DebugLoc DL = N->getDebugLoc();
15841   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
15842   SDValue EFLAGS = N->getOperand(1);
15843
15844   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15845   // a zext and produces an all-ones bit which is more useful than 0/1 in some
15846   // cases.
15847   if (CC == X86::COND_B)
15848     return DAG.getNode(ISD::AND, DL, MVT::i8,
15849                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15850                                    DAG.getConstant(CC, MVT::i8), EFLAGS),
15851                        DAG.getConstant(1, MVT::i8));
15852
15853   SDValue Flags;
15854
15855   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15856   if (Flags.getNode()) {
15857     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15858     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15859   }
15860
15861   Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15862   if (Flags.getNode()) {
15863     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15864     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
15865   }
15866
15867   return SDValue();
15868 }
15869
15870 // Optimize branch condition evaluation.
15871 //
15872 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
15873                                     TargetLowering::DAGCombinerInfo &DCI,
15874                                     const X86Subtarget *Subtarget) {
15875   DebugLoc DL = N->getDebugLoc();
15876   SDValue Chain = N->getOperand(0);
15877   SDValue Dest = N->getOperand(1);
15878   SDValue EFLAGS = N->getOperand(3);
15879   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
15880
15881   SDValue Flags;
15882
15883   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
15884   if (Flags.getNode()) {
15885     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15886     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15887                        Flags);
15888   }
15889
15890   Flags = checkFlaggedOrCombine(EFLAGS, CC, DAG, Subtarget);
15891   if (Flags.getNode()) {
15892     SDValue Cond = DAG.getConstant(CC, MVT::i8);
15893     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
15894                        Flags);
15895   }
15896
15897   return SDValue();
15898 }
15899
15900 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15901   SDValue Op0 = N->getOperand(0);
15902   EVT InVT = Op0->getValueType(0);
15903
15904   // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15905   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15906     DebugLoc dl = N->getDebugLoc();
15907     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15908     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15909     // Notice that we use SINT_TO_FP because we know that the high bits
15910     // are zero and SINT_TO_FP is better supported by the hardware.
15911     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15912   }
15913
15914   return SDValue();
15915 }
15916
15917 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15918                                         const X86TargetLowering *XTLI) {
15919   SDValue Op0 = N->getOperand(0);
15920   EVT InVT = Op0->getValueType(0);
15921
15922   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15923   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15924     DebugLoc dl = N->getDebugLoc();
15925     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15926     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15927     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15928   }
15929
15930   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15931   // a 32-bit target where SSE doesn't support i64->FP operations.
15932   if (Op0.getOpcode() == ISD::LOAD) {
15933     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15934     EVT VT = Ld->getValueType(0);
15935     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15936         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15937         !XTLI->getSubtarget()->is64Bit() &&
15938         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15939       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15940                                           Ld->getChain(), Op0, DAG);
15941       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15942       return FILDChain;
15943     }
15944   }
15945   return SDValue();
15946 }
15947
15948 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15949   EVT VT = N->getValueType(0);
15950
15951   // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15952   if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15953     DebugLoc dl = N->getDebugLoc();
15954     MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15955     SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15956     return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15957   }
15958
15959   return SDValue();
15960 }
15961
15962 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15963 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15964                                  X86TargetLowering::DAGCombinerInfo &DCI) {
15965   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15966   // the result is either zero or one (depending on the input carry bit).
15967   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15968   if (X86::isZeroNode(N->getOperand(0)) &&
15969       X86::isZeroNode(N->getOperand(1)) &&
15970       // We don't have a good way to replace an EFLAGS use, so only do this when
15971       // dead right now.
15972       SDValue(N, 1).use_empty()) {
15973     DebugLoc DL = N->getDebugLoc();
15974     EVT VT = N->getValueType(0);
15975     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15976     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15977                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15978                                            DAG.getConstant(X86::COND_B,MVT::i8),
15979                                            N->getOperand(2)),
15980                                DAG.getConstant(1, VT));
15981     return DCI.CombineTo(N, Res1, CarryOut);
15982   }
15983
15984   return SDValue();
15985 }
15986
15987 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15988 //      (add Y, (setne X, 0)) -> sbb -1, Y
15989 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15990 //      (sub (setne X, 0), Y) -> adc -1, Y
15991 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15992   DebugLoc DL = N->getDebugLoc();
15993
15994   // Look through ZExts.
15995   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15996   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15997     return SDValue();
15998
15999   SDValue SetCC = Ext.getOperand(0);
16000   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16001     return SDValue();
16002
16003   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16004   if (CC != X86::COND_E && CC != X86::COND_NE)
16005     return SDValue();
16006
16007   SDValue Cmp = SetCC.getOperand(1);
16008   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16009       !X86::isZeroNode(Cmp.getOperand(1)) ||
16010       !Cmp.getOperand(0).getValueType().isInteger())
16011     return SDValue();
16012
16013   SDValue CmpOp0 = Cmp.getOperand(0);
16014   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16015                                DAG.getConstant(1, CmpOp0.getValueType()));
16016
16017   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16018   if (CC == X86::COND_NE)
16019     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16020                        DL, OtherVal.getValueType(), OtherVal,
16021                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16022   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16023                      DL, OtherVal.getValueType(), OtherVal,
16024                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16025 }
16026
16027 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16028 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16029                                  const X86Subtarget *Subtarget) {
16030   EVT VT = N->getValueType(0);
16031   SDValue Op0 = N->getOperand(0);
16032   SDValue Op1 = N->getOperand(1);
16033
16034   // Try to synthesize horizontal adds from adds of shuffles.
16035   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16036        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16037       isHorizontalBinOp(Op0, Op1, true))
16038     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16039
16040   return OptimizeConditionalInDecrement(N, DAG);
16041 }
16042
16043 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16044                                  const X86Subtarget *Subtarget) {
16045   SDValue Op0 = N->getOperand(0);
16046   SDValue Op1 = N->getOperand(1);
16047
16048   // X86 can't encode an immediate LHS of a sub. See if we can push the
16049   // negation into a preceding instruction.
16050   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16051     // If the RHS of the sub is a XOR with one use and a constant, invert the
16052     // immediate. Then add one to the LHS of the sub so we can turn
16053     // X-Y -> X+~Y+1, saving one register.
16054     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16055         isa<ConstantSDNode>(Op1.getOperand(1))) {
16056       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16057       EVT VT = Op0.getValueType();
16058       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16059                                    Op1.getOperand(0),
16060                                    DAG.getConstant(~XorC, VT));
16061       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16062                          DAG.getConstant(C->getAPIntValue()+1, VT));
16063     }
16064   }
16065
16066   // Try to synthesize horizontal adds from adds of shuffles.
16067   EVT VT = N->getValueType(0);
16068   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16069        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16070       isHorizontalBinOp(Op0, Op1, true))
16071     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16072
16073   return OptimizeConditionalInDecrement(N, DAG);
16074 }
16075
16076 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16077                                              DAGCombinerInfo &DCI) const {
16078   SelectionDAG &DAG = DCI.DAG;
16079   switch (N->getOpcode()) {
16080   default: break;
16081   case ISD::EXTRACT_VECTOR_ELT:
16082     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16083   case ISD::VSELECT:
16084   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16085   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16086   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
16087   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
16088   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
16089   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
16090   case ISD::SHL:
16091   case ISD::SRA:
16092   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
16093   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
16094   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
16095   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
16096   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
16097   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
16098   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG);
16099   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
16100   case ISD::FP_TO_SINT:     return PerformFP_TO_SINTCombine(N, DAG);
16101   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
16102   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
16103   case X86ISD::FXOR:
16104   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
16105   case X86ISD::FMIN:
16106   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
16107   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
16108   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
16109   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
16110   case ISD::ANY_EXTEND:
16111   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
16112   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
16113   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
16114   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
16115   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16116   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16117   case X86ISD::SHUFP:       // Handle all target specific shuffles
16118   case X86ISD::PALIGN:
16119   case X86ISD::UNPCKH:
16120   case X86ISD::UNPCKL:
16121   case X86ISD::MOVHLPS:
16122   case X86ISD::MOVLHPS:
16123   case X86ISD::PSHUFD:
16124   case X86ISD::PSHUFHW:
16125   case X86ISD::PSHUFLW:
16126   case X86ISD::MOVSS:
16127   case X86ISD::MOVSD:
16128   case X86ISD::VPERMILP:
16129   case X86ISD::VPERM2X128:
16130   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16131   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
16132   }
16133
16134   return SDValue();
16135 }
16136
16137 /// isTypeDesirableForOp - Return true if the target has native support for
16138 /// the specified value type and it is 'desirable' to use the type for the
16139 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16140 /// instruction encodings are longer and some i16 instructions are slow.
16141 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16142   if (!isTypeLegal(VT))
16143     return false;
16144   if (VT != MVT::i16)
16145     return true;
16146
16147   switch (Opc) {
16148   default:
16149     return true;
16150   case ISD::LOAD:
16151   case ISD::SIGN_EXTEND:
16152   case ISD::ZERO_EXTEND:
16153   case ISD::ANY_EXTEND:
16154   case ISD::SHL:
16155   case ISD::SRL:
16156   case ISD::SUB:
16157   case ISD::ADD:
16158   case ISD::MUL:
16159   case ISD::AND:
16160   case ISD::OR:
16161   case ISD::XOR:
16162     return false;
16163   }
16164 }
16165
16166 /// IsDesirableToPromoteOp - This method query the target whether it is
16167 /// beneficial for dag combiner to promote the specified node. If true, it
16168 /// should return the desired promotion type by reference.
16169 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16170   EVT VT = Op.getValueType();
16171   if (VT != MVT::i16)
16172     return false;
16173
16174   bool Promote = false;
16175   bool Commute = false;
16176   switch (Op.getOpcode()) {
16177   default: break;
16178   case ISD::LOAD: {
16179     LoadSDNode *LD = cast<LoadSDNode>(Op);
16180     // If the non-extending load has a single use and it's not live out, then it
16181     // might be folded.
16182     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16183                                                      Op.hasOneUse()*/) {
16184       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16185              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16186         // The only case where we'd want to promote LOAD (rather then it being
16187         // promoted as an operand is when it's only use is liveout.
16188         if (UI->getOpcode() != ISD::CopyToReg)
16189           return false;
16190       }
16191     }
16192     Promote = true;
16193     break;
16194   }
16195   case ISD::SIGN_EXTEND:
16196   case ISD::ZERO_EXTEND:
16197   case ISD::ANY_EXTEND:
16198     Promote = true;
16199     break;
16200   case ISD::SHL:
16201   case ISD::SRL: {
16202     SDValue N0 = Op.getOperand(0);
16203     // Look out for (store (shl (load), x)).
16204     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16205       return false;
16206     Promote = true;
16207     break;
16208   }
16209   case ISD::ADD:
16210   case ISD::MUL:
16211   case ISD::AND:
16212   case ISD::OR:
16213   case ISD::XOR:
16214     Commute = true;
16215     // fallthrough
16216   case ISD::SUB: {
16217     SDValue N0 = Op.getOperand(0);
16218     SDValue N1 = Op.getOperand(1);
16219     if (!Commute && MayFoldLoad(N1))
16220       return false;
16221     // Avoid disabling potential load folding opportunities.
16222     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16223       return false;
16224     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16225       return false;
16226     Promote = true;
16227   }
16228   }
16229
16230   PVT = MVT::i32;
16231   return Promote;
16232 }
16233
16234 //===----------------------------------------------------------------------===//
16235 //                           X86 Inline Assembly Support
16236 //===----------------------------------------------------------------------===//
16237
16238 namespace {
16239   // Helper to match a string separated by whitespace.
16240   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16241     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16242
16243     for (unsigned i = 0, e = args.size(); i != e; ++i) {
16244       StringRef piece(*args[i]);
16245       if (!s.startswith(piece)) // Check if the piece matches.
16246         return false;
16247
16248       s = s.substr(piece.size());
16249       StringRef::size_type pos = s.find_first_not_of(" \t");
16250       if (pos == 0) // We matched a prefix.
16251         return false;
16252
16253       s = s.substr(pos);
16254     }
16255
16256     return s.empty();
16257   }
16258   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16259 }
16260
16261 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16262   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16263
16264   std::string AsmStr = IA->getAsmString();
16265
16266   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16267   if (!Ty || Ty->getBitWidth() % 16 != 0)
16268     return false;
16269
16270   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16271   SmallVector<StringRef, 4> AsmPieces;
16272   SplitString(AsmStr, AsmPieces, ";\n");
16273
16274   switch (AsmPieces.size()) {
16275   default: return false;
16276   case 1:
16277     // FIXME: this should verify that we are targeting a 486 or better.  If not,
16278     // we will turn this bswap into something that will be lowered to logical
16279     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
16280     // lower so don't worry about this.
16281     // bswap $0
16282     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16283         matchAsm(AsmPieces[0], "bswapl", "$0") ||
16284         matchAsm(AsmPieces[0], "bswapq", "$0") ||
16285         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16286         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16287         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16288       // No need to check constraints, nothing other than the equivalent of
16289       // "=r,0" would be valid here.
16290       return IntrinsicLowering::LowerToByteSwap(CI);
16291     }
16292
16293     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
16294     if (CI->getType()->isIntegerTy(16) &&
16295         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16296         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16297          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16298       AsmPieces.clear();
16299       const std::string &ConstraintsStr = IA->getConstraintString();
16300       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16301       std::sort(AsmPieces.begin(), AsmPieces.end());
16302       if (AsmPieces.size() == 4 &&
16303           AsmPieces[0] == "~{cc}" &&
16304           AsmPieces[1] == "~{dirflag}" &&
16305           AsmPieces[2] == "~{flags}" &&
16306           AsmPieces[3] == "~{fpsr}")
16307       return IntrinsicLowering::LowerToByteSwap(CI);
16308     }
16309     break;
16310   case 3:
16311     if (CI->getType()->isIntegerTy(32) &&
16312         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16313         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16314         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16315         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16316       AsmPieces.clear();
16317       const std::string &ConstraintsStr = IA->getConstraintString();
16318       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16319       std::sort(AsmPieces.begin(), AsmPieces.end());
16320       if (AsmPieces.size() == 4 &&
16321           AsmPieces[0] == "~{cc}" &&
16322           AsmPieces[1] == "~{dirflag}" &&
16323           AsmPieces[2] == "~{flags}" &&
16324           AsmPieces[3] == "~{fpsr}")
16325         return IntrinsicLowering::LowerToByteSwap(CI);
16326     }
16327
16328     if (CI->getType()->isIntegerTy(64)) {
16329       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16330       if (Constraints.size() >= 2 &&
16331           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16332           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16333         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
16334         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16335             matchAsm(AsmPieces[1], "bswap", "%edx") &&
16336             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16337           return IntrinsicLowering::LowerToByteSwap(CI);
16338       }
16339     }
16340     break;
16341   }
16342   return false;
16343 }
16344
16345
16346
16347 /// getConstraintType - Given a constraint letter, return the type of
16348 /// constraint it is for this target.
16349 X86TargetLowering::ConstraintType
16350 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16351   if (Constraint.size() == 1) {
16352     switch (Constraint[0]) {
16353     case 'R':
16354     case 'q':
16355     case 'Q':
16356     case 'f':
16357     case 't':
16358     case 'u':
16359     case 'y':
16360     case 'x':
16361     case 'Y':
16362     case 'l':
16363       return C_RegisterClass;
16364     case 'a':
16365     case 'b':
16366     case 'c':
16367     case 'd':
16368     case 'S':
16369     case 'D':
16370     case 'A':
16371       return C_Register;
16372     case 'I':
16373     case 'J':
16374     case 'K':
16375     case 'L':
16376     case 'M':
16377     case 'N':
16378     case 'G':
16379     case 'C':
16380     case 'e':
16381     case 'Z':
16382       return C_Other;
16383     default:
16384       break;
16385     }
16386   }
16387   return TargetLowering::getConstraintType(Constraint);
16388 }
16389
16390 /// Examine constraint type and operand type and determine a weight value.
16391 /// This object must already have been set up with the operand type
16392 /// and the current alternative constraint selected.
16393 TargetLowering::ConstraintWeight
16394   X86TargetLowering::getSingleConstraintMatchWeight(
16395     AsmOperandInfo &info, const char *constraint) const {
16396   ConstraintWeight weight = CW_Invalid;
16397   Value *CallOperandVal = info.CallOperandVal;
16398     // If we don't have a value, we can't do a match,
16399     // but allow it at the lowest weight.
16400   if (CallOperandVal == NULL)
16401     return CW_Default;
16402   Type *type = CallOperandVal->getType();
16403   // Look at the constraint type.
16404   switch (*constraint) {
16405   default:
16406     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16407   case 'R':
16408   case 'q':
16409   case 'Q':
16410   case 'a':
16411   case 'b':
16412   case 'c':
16413   case 'd':
16414   case 'S':
16415   case 'D':
16416   case 'A':
16417     if (CallOperandVal->getType()->isIntegerTy())
16418       weight = CW_SpecificReg;
16419     break;
16420   case 'f':
16421   case 't':
16422   case 'u':
16423       if (type->isFloatingPointTy())
16424         weight = CW_SpecificReg;
16425       break;
16426   case 'y':
16427       if (type->isX86_MMXTy() && Subtarget->hasMMX())
16428         weight = CW_SpecificReg;
16429       break;
16430   case 'x':
16431   case 'Y':
16432     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16433         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16434       weight = CW_Register;
16435     break;
16436   case 'I':
16437     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16438       if (C->getZExtValue() <= 31)
16439         weight = CW_Constant;
16440     }
16441     break;
16442   case 'J':
16443     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16444       if (C->getZExtValue() <= 63)
16445         weight = CW_Constant;
16446     }
16447     break;
16448   case 'K':
16449     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16450       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16451         weight = CW_Constant;
16452     }
16453     break;
16454   case 'L':
16455     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16456       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16457         weight = CW_Constant;
16458     }
16459     break;
16460   case 'M':
16461     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16462       if (C->getZExtValue() <= 3)
16463         weight = CW_Constant;
16464     }
16465     break;
16466   case 'N':
16467     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16468       if (C->getZExtValue() <= 0xff)
16469         weight = CW_Constant;
16470     }
16471     break;
16472   case 'G':
16473   case 'C':
16474     if (dyn_cast<ConstantFP>(CallOperandVal)) {
16475       weight = CW_Constant;
16476     }
16477     break;
16478   case 'e':
16479     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16480       if ((C->getSExtValue() >= -0x80000000LL) &&
16481           (C->getSExtValue() <= 0x7fffffffLL))
16482         weight = CW_Constant;
16483     }
16484     break;
16485   case 'Z':
16486     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16487       if (C->getZExtValue() <= 0xffffffff)
16488         weight = CW_Constant;
16489     }
16490     break;
16491   }
16492   return weight;
16493 }
16494
16495 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16496 /// with another that has more specific requirements based on the type of the
16497 /// corresponding operand.
16498 const char *X86TargetLowering::
16499 LowerXConstraint(EVT ConstraintVT) const {
16500   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16501   // 'f' like normal targets.
16502   if (ConstraintVT.isFloatingPoint()) {
16503     if (Subtarget->hasSSE2())
16504       return "Y";
16505     if (Subtarget->hasSSE1())
16506       return "x";
16507   }
16508
16509   return TargetLowering::LowerXConstraint(ConstraintVT);
16510 }
16511
16512 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16513 /// vector.  If it is invalid, don't add anything to Ops.
16514 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16515                                                      std::string &Constraint,
16516                                                      std::vector<SDValue>&Ops,
16517                                                      SelectionDAG &DAG) const {
16518   SDValue Result(0, 0);
16519
16520   // Only support length 1 constraints for now.
16521   if (Constraint.length() > 1) return;
16522
16523   char ConstraintLetter = Constraint[0];
16524   switch (ConstraintLetter) {
16525   default: break;
16526   case 'I':
16527     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16528       if (C->getZExtValue() <= 31) {
16529         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16530         break;
16531       }
16532     }
16533     return;
16534   case 'J':
16535     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16536       if (C->getZExtValue() <= 63) {
16537         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16538         break;
16539       }
16540     }
16541     return;
16542   case 'K':
16543     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16544       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16545         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16546         break;
16547       }
16548     }
16549     return;
16550   case 'N':
16551     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16552       if (C->getZExtValue() <= 255) {
16553         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16554         break;
16555       }
16556     }
16557     return;
16558   case 'e': {
16559     // 32-bit signed value
16560     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16561       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16562                                            C->getSExtValue())) {
16563         // Widen to 64 bits here to get it sign extended.
16564         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16565         break;
16566       }
16567     // FIXME gcc accepts some relocatable values here too, but only in certain
16568     // memory models; it's complicated.
16569     }
16570     return;
16571   }
16572   case 'Z': {
16573     // 32-bit unsigned value
16574     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16575       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16576                                            C->getZExtValue())) {
16577         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16578         break;
16579       }
16580     }
16581     // FIXME gcc accepts some relocatable values here too, but only in certain
16582     // memory models; it's complicated.
16583     return;
16584   }
16585   case 'i': {
16586     // Literal immediates are always ok.
16587     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16588       // Widen to 64 bits here to get it sign extended.
16589       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16590       break;
16591     }
16592
16593     // In any sort of PIC mode addresses need to be computed at runtime by
16594     // adding in a register or some sort of table lookup.  These can't
16595     // be used as immediates.
16596     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16597       return;
16598
16599     // If we are in non-pic codegen mode, we allow the address of a global (with
16600     // an optional displacement) to be used with 'i'.
16601     GlobalAddressSDNode *GA = 0;
16602     int64_t Offset = 0;
16603
16604     // Match either (GA), (GA+C), (GA+C1+C2), etc.
16605     while (1) {
16606       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16607         Offset += GA->getOffset();
16608         break;
16609       } else if (Op.getOpcode() == ISD::ADD) {
16610         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16611           Offset += C->getZExtValue();
16612           Op = Op.getOperand(0);
16613           continue;
16614         }
16615       } else if (Op.getOpcode() == ISD::SUB) {
16616         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16617           Offset += -C->getZExtValue();
16618           Op = Op.getOperand(0);
16619           continue;
16620         }
16621       }
16622
16623       // Otherwise, this isn't something we can handle, reject it.
16624       return;
16625     }
16626
16627     const GlobalValue *GV = GA->getGlobal();
16628     // If we require an extra load to get this address, as in PIC mode, we
16629     // can't accept it.
16630     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16631                                                         getTargetMachine())))
16632       return;
16633
16634     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16635                                         GA->getValueType(0), Offset);
16636     break;
16637   }
16638   }
16639
16640   if (Result.getNode()) {
16641     Ops.push_back(Result);
16642     return;
16643   }
16644   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16645 }
16646
16647 std::pair<unsigned, const TargetRegisterClass*>
16648 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16649                                                 EVT VT) const {
16650   // First, see if this is a constraint that directly corresponds to an LLVM
16651   // register class.
16652   if (Constraint.size() == 1) {
16653     // GCC Constraint Letters
16654     switch (Constraint[0]) {
16655     default: break;
16656       // TODO: Slight differences here in allocation order and leaving
16657       // RIP in the class. Do they matter any more here than they do
16658       // in the normal allocation?
16659     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16660       if (Subtarget->is64Bit()) {
16661         if (VT == MVT::i32 || VT == MVT::f32)
16662           return std::make_pair(0U, &X86::GR32RegClass);
16663         if (VT == MVT::i16)
16664           return std::make_pair(0U, &X86::GR16RegClass);
16665         if (VT == MVT::i8 || VT == MVT::i1)
16666           return std::make_pair(0U, &X86::GR8RegClass);
16667         if (VT == MVT::i64 || VT == MVT::f64)
16668           return std::make_pair(0U, &X86::GR64RegClass);
16669         break;
16670       }
16671       // 32-bit fallthrough
16672     case 'Q':   // Q_REGS
16673       if (VT == MVT::i32 || VT == MVT::f32)
16674         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16675       if (VT == MVT::i16)
16676         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
16677       if (VT == MVT::i8 || VT == MVT::i1)
16678         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
16679       if (VT == MVT::i64)
16680         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
16681       break;
16682     case 'r':   // GENERAL_REGS
16683     case 'l':   // INDEX_REGS
16684       if (VT == MVT::i8 || VT == MVT::i1)
16685         return std::make_pair(0U, &X86::GR8RegClass);
16686       if (VT == MVT::i16)
16687         return std::make_pair(0U, &X86::GR16RegClass);
16688       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
16689         return std::make_pair(0U, &X86::GR32RegClass);
16690       return std::make_pair(0U, &X86::GR64RegClass);
16691     case 'R':   // LEGACY_REGS
16692       if (VT == MVT::i8 || VT == MVT::i1)
16693         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
16694       if (VT == MVT::i16)
16695         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
16696       if (VT == MVT::i32 || !Subtarget->is64Bit())
16697         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
16698       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
16699     case 'f':  // FP Stack registers.
16700       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
16701       // value to the correct fpstack register class.
16702       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
16703         return std::make_pair(0U, &X86::RFP32RegClass);
16704       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
16705         return std::make_pair(0U, &X86::RFP64RegClass);
16706       return std::make_pair(0U, &X86::RFP80RegClass);
16707     case 'y':   // MMX_REGS if MMX allowed.
16708       if (!Subtarget->hasMMX()) break;
16709       return std::make_pair(0U, &X86::VR64RegClass);
16710     case 'Y':   // SSE_REGS if SSE2 allowed
16711       if (!Subtarget->hasSSE2()) break;
16712       // FALL THROUGH.
16713     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
16714       if (!Subtarget->hasSSE1()) break;
16715
16716       switch (VT.getSimpleVT().SimpleTy) {
16717       default: break;
16718       // Scalar SSE types.
16719       case MVT::f32:
16720       case MVT::i32:
16721         return std::make_pair(0U, &X86::FR32RegClass);
16722       case MVT::f64:
16723       case MVT::i64:
16724         return std::make_pair(0U, &X86::FR64RegClass);
16725       // Vector types.
16726       case MVT::v16i8:
16727       case MVT::v8i16:
16728       case MVT::v4i32:
16729       case MVT::v2i64:
16730       case MVT::v4f32:
16731       case MVT::v2f64:
16732         return std::make_pair(0U, &X86::VR128RegClass);
16733       // AVX types.
16734       case MVT::v32i8:
16735       case MVT::v16i16:
16736       case MVT::v8i32:
16737       case MVT::v4i64:
16738       case MVT::v8f32:
16739       case MVT::v4f64:
16740         return std::make_pair(0U, &X86::VR256RegClass);
16741       }
16742       break;
16743     }
16744   }
16745
16746   // Use the default implementation in TargetLowering to convert the register
16747   // constraint into a member of a register class.
16748   std::pair<unsigned, const TargetRegisterClass*> Res;
16749   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16750
16751   // Not found as a standard register?
16752   if (Res.second == 0) {
16753     // Map st(0) -> st(7) -> ST0
16754     if (Constraint.size() == 7 && Constraint[0] == '{' &&
16755         tolower(Constraint[1]) == 's' &&
16756         tolower(Constraint[2]) == 't' &&
16757         Constraint[3] == '(' &&
16758         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16759         Constraint[5] == ')' &&
16760         Constraint[6] == '}') {
16761
16762       Res.first = X86::ST0+Constraint[4]-'0';
16763       Res.second = &X86::RFP80RegClass;
16764       return Res;
16765     }
16766
16767     // GCC allows "st(0)" to be called just plain "st".
16768     if (StringRef("{st}").equals_lower(Constraint)) {
16769       Res.first = X86::ST0;
16770       Res.second = &X86::RFP80RegClass;
16771       return Res;
16772     }
16773
16774     // flags -> EFLAGS
16775     if (StringRef("{flags}").equals_lower(Constraint)) {
16776       Res.first = X86::EFLAGS;
16777       Res.second = &X86::CCRRegClass;
16778       return Res;
16779     }
16780
16781     // 'A' means EAX + EDX.
16782     if (Constraint == "A") {
16783       Res.first = X86::EAX;
16784       Res.second = &X86::GR32_ADRegClass;
16785       return Res;
16786     }
16787     return Res;
16788   }
16789
16790   // Otherwise, check to see if this is a register class of the wrong value
16791   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16792   // turn into {ax},{dx}.
16793   if (Res.second->hasType(VT))
16794     return Res;   // Correct type already, nothing to do.
16795
16796   // All of the single-register GCC register classes map their values onto
16797   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
16798   // really want an 8-bit or 32-bit register, map to the appropriate register
16799   // class and return the appropriate register.
16800   if (Res.second == &X86::GR16RegClass) {
16801     if (VT == MVT::i8) {
16802       unsigned DestReg = 0;
16803       switch (Res.first) {
16804       default: break;
16805       case X86::AX: DestReg = X86::AL; break;
16806       case X86::DX: DestReg = X86::DL; break;
16807       case X86::CX: DestReg = X86::CL; break;
16808       case X86::BX: DestReg = X86::BL; break;
16809       }
16810       if (DestReg) {
16811         Res.first = DestReg;
16812         Res.second = &X86::GR8RegClass;
16813       }
16814     } else if (VT == MVT::i32) {
16815       unsigned DestReg = 0;
16816       switch (Res.first) {
16817       default: break;
16818       case X86::AX: DestReg = X86::EAX; break;
16819       case X86::DX: DestReg = X86::EDX; break;
16820       case X86::CX: DestReg = X86::ECX; break;
16821       case X86::BX: DestReg = X86::EBX; break;
16822       case X86::SI: DestReg = X86::ESI; break;
16823       case X86::DI: DestReg = X86::EDI; break;
16824       case X86::BP: DestReg = X86::EBP; break;
16825       case X86::SP: DestReg = X86::ESP; break;
16826       }
16827       if (DestReg) {
16828         Res.first = DestReg;
16829         Res.second = &X86::GR32RegClass;
16830       }
16831     } else if (VT == MVT::i64) {
16832       unsigned DestReg = 0;
16833       switch (Res.first) {
16834       default: break;
16835       case X86::AX: DestReg = X86::RAX; break;
16836       case X86::DX: DestReg = X86::RDX; break;
16837       case X86::CX: DestReg = X86::RCX; break;
16838       case X86::BX: DestReg = X86::RBX; break;
16839       case X86::SI: DestReg = X86::RSI; break;
16840       case X86::DI: DestReg = X86::RDI; break;
16841       case X86::BP: DestReg = X86::RBP; break;
16842       case X86::SP: DestReg = X86::RSP; break;
16843       }
16844       if (DestReg) {
16845         Res.first = DestReg;
16846         Res.second = &X86::GR64RegClass;
16847       }
16848     }
16849   } else if (Res.second == &X86::FR32RegClass ||
16850              Res.second == &X86::FR64RegClass ||
16851              Res.second == &X86::VR128RegClass) {
16852     // Handle references to XMM physical registers that got mapped into the
16853     // wrong class.  This can happen with constraints like {xmm0} where the
16854     // target independent register mapper will just pick the first match it can
16855     // find, ignoring the required type.
16856
16857     if (VT == MVT::f32 || VT == MVT::i32)
16858       Res.second = &X86::FR32RegClass;
16859     else if (VT == MVT::f64 || VT == MVT::i64)
16860       Res.second = &X86::FR64RegClass;
16861     else if (X86::VR128RegClass.hasType(VT))
16862       Res.second = &X86::VR128RegClass;
16863     else if (X86::VR256RegClass.hasType(VT))
16864       Res.second = &X86::VR256RegClass;
16865   }
16866
16867   return Res;
16868 }